answer
stringlengths 17
10.2M
|
|---|
package fr.free.nrw.commons.nearby;
import android.app.ListActivity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import fr.free.nrw.commons.R;
public class NearbyActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
private LocationManager locationManager;
private String provider;
private Criteria criteria;
private double currentLatitude, currentLongitude;
//private String gpsCoords;
private static final String TAG = "NearbyActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
registerLocationManager();
}
@Override
protected void onResume(){
super.onResume();
registerLocationManager();
//TODO: Check if we need String or double coords, and in what format
//gpsCoords = String.valueOf(currentLatitude) + "|" + String.valueOf(currentLongitude);
}
/**
* Registers a LocationManager to listen for current location
*/
protected void registerLocationManager() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
myLocationListener = new MyLocationListener();
try {
locationManager.requestLocationUpdates(provider, 400, 1, myLocationListener);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
myLocationListener.onLocationChanged(location);
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Illegal argument exception", e);
} catch (SecurityException e) {
Log.e(TAG, "Security exception", e);
}
}
protected void unregisterLocationManager() {
try {
locationManager.removeUpdates(myLocationListener);
} catch (SecurityException e) {
Log.e(TAG, "Security exception", e);
}
}
/**
* Listen for user's location when it changes
*/
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.d(TAG, "Latitude: " + String.valueOf(currentLatitude) + " Longitude: " + String.valueOf(currentLongitude));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, provider + "'s status changed to " + status);
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Provider " + provider + " enabled");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Provider " + provider + " disabled");
}
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterLocationManager();
}
}
|
package peergos.shared.user;
import jsinterop.annotations.*;
import java.io.*;
import java.util.concurrent.*;
@JsType(namespace = "http", isNative = true)
public class NativeJSHttp {
// public static <T> CompletableFuture<T> incomplete() {
// return new CompletableFuture<>();
public native CompletableFuture<byte[]> post(String url, byte[] payload) ;/*-{
console.log("postProm");
var future = this.incomplete();
new Promise(function(resolve, reject) {
console.log("making http post request");
var req = new XMLHttpRequest();
req.open('POST', window.location.origin + "/" + url);
req.responseType = 'arraybuffer';
req.onload = function() {
console.log("http post returned retrieving " + url);
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
resolve(new Uint8Array(req.response));
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send(new Uint8Array(data));
}).then(function(result, err) {
if (err != null)
future.completeExceptionally(err);
else
future.complete(peergos.shared.user.JavaScriptPoster.convertToBytes(result));
});
return future;
}-*/;
public native CompletableFuture<byte[]> get(String url) ;/*-{
console.log("getProm");
var future = this.incomplete();
new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
resolve(new Uint8Array(req.response));
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
}).then(function(result, err) {
if (err != null)
future.completeExceptionally(err);
else
future.complete(result);
});
return future;
}-*/;
}
|
package peergos.shared.user.fs;
public class MimeTypes {
final static int[] ID3 = new int[]{'I', 'D', '3'};
final static int[] MP3 = new int[]{0xff, 0xfb};
final static int[] WAV_1 = new int[]{'R', 'I', 'F', 'F'};
final static int[] WAV_2 = new int[]{'W', 'A', 'V', 'E'};
final static int[] MP4 = new int[]{'f', 't', 'y', 'p'};
final static int[] ISO2 = new int[]{'i', 's', 'o', '2'};
final static int[] ISOM = new int[]{'i', 's', 'o', 'm'};
final static int[] MP41 = new int[]{'m', 'p', '4', '1'};
final static int[] MP42 = new int[]{'m', 'p', '4', '2'};
final static int[] QT = new int[]{'q', 't', ' ', ' '};
final static int[] THREEGP = new int[]{'3', 'g', 'p'};
final static int[] FLV = new int[]{'F', 'L', 'V'};
final static int[] AVI = new int[]{'A', 'V', 'I', ' '};
final static int[] OGG = new int[]{'O', 'g', 'g', 'S', 0, 2};
final static int[] WEBM = new int[]{'w', 'e', 'b', 'm'};
final static int[] MATROSKA_START = new int[]{0x1a, 0x45, 0xdf, 0xa3};
final static int[] ICO = new int[]{0, 0, 1, 0};
final static int[] CUR = new int[]{0, 0, 2, 0};
final static int[] BMP = new int[]{'B', 'M'};
final static int[] GIF = new int[]{'G', 'I', 'F'};
final static int[] JPEG = new int[]{255, 216};
final static int[] TIFF1 = new int[]{'I', 'I', 0x2A, 0};
final static int[] TIFF2 = new int[]{'M', 'M', 0, 0x2A};
final static int[] PNG = new int[]{137, 'P', 'N', 'G', 13, 10, 26, 10};
final static int HEADER_BYTES_TO_IDENTIFY_MIME_TYPE = 28;
public static final String calculateMimeType(byte[] start) {
if (equalArrays(start, BMP))
return "image/bmp";
if (equalArrays(start, GIF))
return "image/gif";
if (equalArrays(start, PNG))
return "image/png";
if (equalArrays(start, JPEG))
return "image/jpg";
if (equalArrays(start, ICO))
return "image/x-icon";
if (equalArrays(start, CUR))
return "image/x-icon";
// many browsers don't support tiff
if (equalArrays(start, TIFF1))
return "image/tiff";
if (equalArrays(start, TIFF2))
return "image/tiff";
if (equalArrays(start, 4, MP4)) {
if (equalArrays(start, 8, ISO2)
|| equalArrays(start, 8, ISOM)
|| equalArrays(start, 8, MP42)
|| equalArrays(start, 8, MP41))
return "video/mp4";
if (equalArrays(start, 8, QT))
return "video/quicktime";
if (equalArrays(start, 8, THREEGP))
return "video/3gpp";
}
if (equalArrays(start, 24, WEBM))
return "video/webm";
if (equalArrays(start, OGG))
return "video/ogg";
if (equalArrays(start, MATROSKA_START))
return "video/x-matroska";
if (equalArrays(start, FLV))
return "video/x-flv";
if (equalArrays(start, 8, AVI))
return "video/avi";
if (equalArrays(start, ID3))
return "audio/mpeg";
if (equalArrays(start, MP3))
return "audio/mpeg";
if (equalArrays(start, OGG)) // not sure how to distinguish from ogg video easily
return "audio/ogg";
if (equalArrays(start, WAV_1) && equalArrays(start, 8, WAV_2))
return "audio/wav";
if (allAscii(start))
return "text/plain";
return "";
}
private static boolean allAscii(byte[] data) {
for (byte b : data) {
if ((b & 0xff) > 0x80)
return false;
if ((b & 0xff) < 0x20 && b != (byte)0x10 && b != (byte) 0x13)
return false;
}
return true;
}
private static boolean equalArrays(byte[] a, int[] target) {
return equalArrays(a, 0, target);
}
private static boolean equalArrays(byte[] a, int aOffset, int[] target) {
if (a == null || target == null){
return false;
}
for (int i=0; i < target.length; i++) {
if ((a[i + aOffset] & 0xff) != (target[i] & 0xff)) {
return false;
}
}
return true;
}
}
|
package io.quickcoding.dropdownalert;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("QUICKCODING.IO","HELLO");
}
}
|
package playpiano;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.media.AudioClip;
/**
*
* @author pascale
*/
public class FXMLDocumentController implements Initializable {
@FXML
private Button mC;
private Menu file;
private MenuItem close;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
public void close() {
System.exit(0);
}
@FXML
public void playmC(){
AudioClip mC = new AudioClip(getClass().getResource("mC.wav").toString());
mC.play();
}
@FXML
public void playmCsharp(){
AudioClip mCsharp = new AudioClip(getClass().getResource("mC#.wav").toString());
mCsharp.play();
}
@FXML
public void playmD(){
AudioClip mD = new AudioClip(getClass().getResource("mD.wav").toString());
mD.play();
}
@FXML
public void playmDsharp(){
AudioClip mDsharp = new AudioClip(getClass().getResource("mD#.wav").toString());
mDsharp.play();
}
@FXML
public void playhC(){
AudioClip hC = new AudioClip(getClass().getResource("hC.wav").toString());
hC.play();
}
}
|
package playpiano;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.media.AudioClip;
/**
*
* @author pascale
*/
public class FXMLDocumentController implements Initializable {
@FXML
private Button mC;
private Menu file;
private MenuItem close;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
public void close() {
System.exit(0);
}
@FXML
public void playmC(){
AudioClip mC = new AudioClip(getClass().getResource("mC.wav").toString());
mC.play();
}
@FXML
public void playmCsharp(){
AudioClip mCsharp = new AudioClip(getClass().getResource("mC#.wav").toString());
mCsharp.play();
}
@FXML
public void playmD(){
AudioClip mD = new AudioClip(getClass().getResource("mD.wav").toString());
mD.play();
}
@FXML
public void playmDsharp(){
AudioClip mDsharp = new AudioClip(getClass().getResource("mD#.wav").toString());
mDsharp.play();
}
@FXML
public void playmE(){
AudioClip mE = new AudioClip(getClass().getResource("mE.wav").toString());
mE.play();
}
@FXML
public void playhC(){
AudioClip hC = new AudioClip(getClass().getResource("hC.wav").toString());
hC.play();
}
@FXML
public void playhCsharp(){
AudioClip hCsharp = new AudioClip(getClass().getResource("hC#.wav").toString());
hCsharp.play();
}
@FXML
public void playhD(){
AudioClip hD = new AudioClip(getClass().getResource("hD.wav").toString());
hD.play();
}
@FXML
public void playhDsharp(){
AudioClip hDsharp = new AudioClip(getClass().getResource("hD#.wav").toString());
hDsharp.play();
}
@FXML
public void playhE(){
AudioClip hE = new AudioClip(getClass().getResource("hE.wav").toString());
hE.play();
}
}
|
package com.javalearning;
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
import java.util.List;
public class SplitRange {
public static List<Range<Integer>> splitRange(int minId, int maxId, int rangeNo) {
List<Range<Integer>> rangeList = Lists.newArrayList();
if (minId == 0 && maxId == 0) {
Range<Integer> range = Range.closed(minId, maxId);
rangeList.add(range);
return rangeList;
}
// int rangeSize = (maxId - minId)/rangeNo + 1;
int rangeSize = IntMath.divide(maxId - minId + 1, rangeNo, RoundingMode.CEILING);
int startId = minId;
int endId = minId + rangeSize - 1;
while (endId <= maxId) {
Range<Integer> range = Range.closed(startId, endId);
rangeList.add(range);
startId = startId + rangeSize;
endId = endId + rangeSize;
if (startId <= maxId && endId >= maxId) {
endId = maxId;
Range<Integer> lastRange = Range.closed(startId, endId);
rangeList.add(lastRange);
break;
}
}
return rangeList;
}
public static void main(String[] args) {
System.out.println(splitRange(5, 8, 9));
// System.out.println(splitRange(13, 100009, 4));
// System.out.println(splitRange(9, 100009, 2));
}
}
|
package me.ryanpetschek.gatekeeper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import org.spongycastle.jce.ECNamedCurveTable;
import org.spongycastle.jce.spec.ECParameterSpec;
import org.spongycastle.util.encoders.Hex;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import javax.net.ssl.HttpsURLConnection;
public class SignInActivity extends AppCompatActivity {
protected PublicKey pub;
protected PrivateKey priv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences settings = getSharedPreferences("GK_settings", 0);
if (settings.getBoolean("hasAccount", false) == true) {
Intent intent = new Intent(SignInActivity.this, MainActivity.class);
startActivity(intent);
} else {
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("GateKeeper");
final Button button = (Button) findViewById(R.id.signup);
final EditText nameField = (EditText) findViewById(R.id.name);
final EditText pictureUrlField = (EditText) findViewById(R.id.photoUrl);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Validate inputs
String name = nameField.getText().toString().trim();
String pictureUrl = pictureUrlField.getText().toString().trim();
if (name.length() == 0 || pictureUrl.length() == 0) {
alertDialog.setTitle("Error");
alertDialog.setMessage("Name or photo URL cannot be left blank");
alertDialog.show();
return;
}
if (!URLUtil.isValidUrl(pictureUrl)) {
alertDialog.setTitle("Error");
alertDialog.setMessage("Invalid photo URL");
alertDialog.show();
return;
}
KeyPair keyPair = generateKeys();
if (keyPair == null) {
alertDialog.setTitle("Error");
alertDialog.setMessage("No Keys Generated!");
alertDialog.show();
return;
}
priv = keyPair.getPrivate();
pub = keyPair.getPublic();
String pubKeyHex = Hex.toHexString(pub.getEncoded());
//Make the signatures
String sigHex = "";
String signingPayload = new String(name + pictureUrl + pubKeyHex);
byte[] digested;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(signingPayload.getBytes()); // Change this to "UTF-16" if needed
digested = md.digest();
Signature signature = Signature.getInstance("ECDSA", "SC");
signature.initSign(priv);
signature.update(digested);
byte[] sigData = signature.sign();
sigHex = Hex.toHexString(sigData);
} catch (NoSuchAlgorithmException | java.security.SignatureException
| java.security.InvalidKeyException
| java.security.NoSuchProviderException e) {}
new PostCrypto().execute(name, pictureUrl, pubKeyHex, sigHex);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasAccount", true);
editor.putString("name", name);
editor.putString("imageUrl", pictureUrl);
editor.commit();
storeKeyPair(priv, pub);
Intent intent = new Intent(SignInActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
private KeyPair generateKeys() {
//Generates an elliptic curve encryption key-pair with a secp256k1 curve
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 3);
ECParameterSpec specs = ECNamedCurveTable.getParameterSpec("secp256k1");
try {
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");
g.initialize(specs, new SecureRandom());
KeyPair pair = g.generateKeyPair();
return pair;
}
catch (java.security.NoSuchAlgorithmException | java.security.NoSuchProviderException |
java.security.InvalidAlgorithmParameterException err) {
Log.e("KeyGen", err.getMessage());
err.printStackTrace();
return null;
}
}
private void storeKeyPair(PrivateKey privKey, PublicKey pubKey) {
String pubKeyHex = Hex.toHexString(pubKey.getEncoded());
String privKeyHex = Hex.toHexString(privKey.getEncoded());
SharedPreferences.Editor settings = getSharedPreferences("GK_settings", 0).edit();
settings.putString("publicKey", pubKeyHex);
settings.putString("privateKey", privKeyHex);
}
private String getPublicKey() {
SharedPreferences settings = getSharedPreferences("GK_settings", 0);
return settings.getString("publicKey", "keyNotFound");
}
private class PostCrypto extends AsyncTask<String, Void, String> {
public PostCrypto() {}
@Override
public String doInBackground(String ... strings ) {
//Post everything to the Server
try {
URL url = new URL("https://gatekeeper.ryanpetschek.me");
HttpsURLConnection connect = (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("User-Agent", "Fu[sic]GA");
connect.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connect.setRequestProperty("Content-Type", "application/json");
connect.setRequestProperty("Accept", "application/json");
JSONObject payload = new JSONObject();
try {
payload.put("name", strings[0]);
payload.put("pictureURL", strings[1]);
payload.put("publicKey", strings[2]);
payload.put("signature", strings[3]);
} catch (org.json.JSONException err) {
}
//Initiate the post
connect.setDoOutput(true);
DataOutputStream write = new DataOutputStream(connect.getOutputStream());
write.writeBytes(payload.toString());
write.flush();
write.close();
//Get response data
Integer respCode = connect.getResponseCode();
Log.d("RESPONSE-CODE: ", respCode.toString());
BufferedReader in = new BufferedReader(
new InputStreamReader(connect.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String finalResp = response.toString();
//Parse the JSON
JSONObject jsonData = null;
try {
jsonData = new JSONObject(finalResp);
} catch (org.json.JSONException err) {
}
try {
jsonData.getBoolean("success");
return null;
} catch (org.json.JSONException e) {
try {
return jsonData.getString("error");
} catch (org.json.JSONException err) {
}
}
} catch (ProtocolException err1) {
Log.e("ERROR", err1.getMessage());
err1.printStackTrace();
} catch (IOException err2) {
Log.e("ERROR", err2.getMessage());
err2.printStackTrace();
}
return null;
}
}
}
|
package org.commcare.dalvik.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.adapters.EntityListAdapter;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.logic.DetailCalloutListenerDefaultImpl;
import org.commcare.android.models.AndroidSessionWrapper;
import org.commcare.android.models.Entity;
import org.commcare.android.models.NodeEntityFactory;
import org.commcare.android.tasks.EntityLoaderListener;
import org.commcare.android.tasks.EntityLoaderTask;
import org.commcare.android.util.CommCareInstanceInitializer;
import org.commcare.android.util.DetailCalloutListener;
import org.commcare.android.util.SerializationUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.view.EntityView;
import org.commcare.android.view.TabbedDetailView;
import org.commcare.android.view.ViewUtil;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.preferences.DeveloperPreferences;
import org.commcare.suite.model.Action;
import org.commcare.suite.model.Callout;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.SessionDatum;
import org.commcare.util.CommCareSession;
import org.commcare.util.SessionFrame;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.AbstractTreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.model.xform.XPathReference;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
/**
*
* TODO: Lots of locking and state-based cleanup
*
* @author ctsims
*
*/
public class EntitySelectActivity extends CommCareActivity implements TextWatcher, EntityLoaderListener, OnItemClickListener, TextToSpeech.OnInitListener, DetailCalloutListener {
private CommCareSession session;
private AndroidSessionWrapper asw;
public static final String EXTRA_ENTITY_KEY = "esa_entity_key";
public static final String EXTRA_IS_MAP = "is_map";
private static final int CONFIRM_SELECT = 0;
private static final int BARCODE_FETCH = 1;
private static final int MAP_SELECT = 2;
private static final int CALLOUT = 3;
private static final int MENU_SORT = Menu.FIRST;
private static final int MENU_MAP = Menu.FIRST + 1;
private static final int MENU_ACTION = Menu.FIRST + 2;
EditText searchbox;
TextView searchResultStatus;
EntityListAdapter adapter;
LinearLayout header;
ImageButton calloutButton;
TextToSpeech tts;
SessionDatum selectDatum;
EvaluationContext entityContext;
boolean mResultIsMap = false;
boolean mMappingEnabled = false;
// Is the detail screen for showing entities, without option for moving
// forward on to form manipulation?
boolean mViewMode = false;
// Has a detail screen not been defined?
boolean mNoDetailMode = false;
private EntityLoaderTask loader;
private boolean inAwesomeMode = false;
FrameLayout rightFrame;
TabbedDetailView detailView;
Intent selectedIntent = null;
String filterString = "";
private Detail shortSelect;
private DataSetObserver mListStateObserver;
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createDataSetObserver();
EntitySelectActivity oldActivity = (EntitySelectActivity)this.getDestroyedActivityState();
if(savedInstanceState != null) {
mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false);
}
try {
asw = CommCareApplication._().getCurrentSessionWrapper();
session = asw.getSession();
} catch(SessionUnavailableException sue){
//The user isn't logged in! bounce this back to where we came from
this.setResult(Activity.RESULT_CANCELED);
this.finish();
return;
}
selectDatum = session.getNeededDatum();
shortSelect = session.getDetail(selectDatum.getShortDetail());
mNoDetailMode = selectDatum.getLongDetail() == null;
if(this.getString(R.string.panes).equals("two") && !mNoDetailMode) {
//See if we're on a big 'ol screen.
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//If we're in landscape mode, we can display this with the awesome UI.
//Inflate and set up the normal view for now.
setContentView(R.layout.screen_compound_select);
View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane));
inAwesomeMode = true;
rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane);
TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt);
message.setText(localize("select.placeholder.message", new String[]{Localization.get("cchq.case")}));
} else {
setContentView(R.layout.entity_select_layout);
//So we're not in landscape mode anymore, but were before. If we had something selected, we
//need to go to the detail screen instead.
if (oldActivity != null) {
Intent intent = this.getIntent();
TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
if (selectedRef != null) {
// remove the reference from this intent, ensuring we
// don't re-launch the detail for an entity even after
// it being de-selected.
intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE);
// attach the selected entity to the new detail intent
// we're launching
Intent detailIntent = getDetailIntent(selectedRef, null);
startOther = true;
startActivityForResult(detailIntent, CONFIRM_SELECT);
}
}
}
} else {
setContentView(R.layout.entity_select_layout);
}
((ListView)this.findViewById(R.id.screen_entity_select_list)).setOnItemClickListener(this);
TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label);
searchLabel.setText(Localization.get("select.search.label"));
searchLabel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// get the focus on the edittext by performing click
searchbox.performClick();
// then force the keyboard up since performClick() apparently isn't enough on some devices
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT);
}
});
searchbox = (EditText)findViewById(R.id.searchbox);
searchbox.setMaxLines(3);
searchbox.setHorizontallyScrolling(false);
searchResultStatus = (TextView) findViewById(R.id.no_search_results);
header = (LinearLayout)findViewById(R.id.entity_select_header);
mViewMode = session.isViewCommand(session.getCommand());
Callout callout = shortSelect.getCallout();
calloutButton = (ImageButton) findViewById(R.id.barcodeButton);
if(callout == null) {
calloutButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent("com.google.zxing.client.android.SCAN");
try {
startActivityForResult(i, BARCODE_FETCH);
} catch (ActivityNotFoundException anfe) {
Toast noReader = Toast.makeText(EntitySelectActivity.this, "No barcode reader available! You can install one from the android market.", Toast.LENGTH_LONG);
noReader.show();
}
}
});
} else {
final String actionName = callout.getActionName();
final Hashtable<String, String> extras = callout.getExtras();
final Vector<String> responses = callout.getResponses();
if(callout.getImage() != null) {
setupImageLayout(calloutButton, callout.getImage());
}
calloutButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(actionName);
for(String key: extras.keySet()){
i.putExtra(key, extras.get(key));
}
try {
startActivityForResult(i, CALLOUT);
} catch (ActivityNotFoundException anfe) {
Toast noReader = Toast.makeText(EntitySelectActivity.this, "No application found for action: " + actionName, Toast.LENGTH_LONG);
noReader.show();
}
}
});
}
searchbox.addTextChangedListener(this);
searchbox.requestFocus();
if(oldActivity != null) {
adapter = oldActivity.adapter;
//not sure how this happens, but seem plausible.
if(adapter != null) {
adapter.setController(this);
((ListView)this.findViewById(R.id.screen_entity_select_list)).setAdapter(adapter);
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
//Disconnect the old adapter
adapter.unregisterDataSetObserver(oldActivity.mListStateObserver);
//connect the new one
adapter.registerDataSetObserver(this.mListStateObserver);
}
}
//cts: disabling for non-demo purposes
//tts = new TextToSpeech(this, this);
}
/*
* Updates the ImageView layout that is passed in, based on the
* new id and source
*/
public void setupImageLayout(View layout, final String source) {
ImageView iv = (ImageView) layout;
Bitmap b;
if (!source.equals("")) {
try {
b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream());
if (b == null) {
//Input stream could not be used to derive bitmap, so showing error-indicating image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
else {
iv.setImageBitmap(b);
}
} catch (IOException ex) {
ex.printStackTrace();
//Error loading image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
} catch (InvalidReferenceException ex) {
ex.printStackTrace();
//No image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
}
else {
iv.setImageDrawable(getResources().getDrawable(R.color.white));
}
}
private void createDataSetObserver() {
mListStateObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
//update the search results box
String query = searchbox.getText().toString();
if (!"".equals(query)) {
searchResultStatus.setText(Localization.get("select.search.status", new String[] {
""+adapter.getCount(true, false),
""+adapter.getCount(true, true),
query
}));
searchResultStatus.setVisibility(View.VISIBLE);
}
else {
searchResultStatus.setVisibility(View.GONE);
}
}
};
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#isTopNavEnabled()
*/
@Override
protected boolean isTopNavEnabled() {
return true;
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#getActivityTitle()
*/
@Override
public String getActivityTitle() {
//Skipping this until it's a more general pattern
// String title = Localization.get("select.list.title");
// try {
// Detail detail = session.getDetail(selectDatum.getShortDetail());
// title = detail.getTitle().evaluate();
// } catch(Exception e) {
// return title;
return null;
}
boolean resuming = false;
boolean startOther = false;
public void onResume() {
super.onResume();
//Don't go through making the whole thing if we're finishing anyway.
if (this.isFinishing() || startOther) { return; }
if(!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) {
TreeReference entity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY));
if(entity != null) {
if(inAwesomeMode) {
if (adapter != null) {
displayReferenceAwesome(entity, adapter.getPosition(entity));
adapter.setAwesomeMode(true);
updateSelectedItem(entity, true);
}
} else {
//Once we've done the initial dispatch, we don't want to end up triggering it later.
this.getIntent().removeExtra(EXTRA_ENTITY_KEY);
Intent i = getDetailIntent(entity, null);
if (adapter != null) {
i.putExtra("entity_detail_index", adapter.getPosition(entity));
i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID, selectDatum.getShortDetail());
}
startActivityForResult(i, CONFIRM_SELECT);
return;
}
}
}
refreshView();
}
/**
* Get form list from database and insert into view.
*/
private void refreshView() {
try {
//TODO: Get ec into these text's
String[] headers = new String[shortSelect.getFields().length];
for(int i = 0 ; i < headers.length ; ++i) {
headers[i] = shortSelect.getFields()[i].getHeader().evaluate();
if("address".equals(shortSelect.getFields()[i].getTemplateForm())) {
this.mMappingEnabled = true;
}
}
//Hm, sadly we possibly need to rebuild this each time.
EntityView v = new EntityView(this, shortSelect, headers);
header.removeAllViews();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
v.setBackgroundResource(R.drawable.blue_tabbed_box);
// only add headers if we're not using grid mode
if(!shortSelect.usesGridView()){
header.addView(v,params);
}
if(adapter == null && loader == null && !EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
} else {
startTimer();
}
} catch(SessionUnavailableException sue) {
//TODO: login and return
}
}
@Override
protected void onPause() {
super.onPause();
stopTimer();
}
@Override
public void onStop() {
super.onStop();
stopTimer();
}
protected Intent getDetailIntent(TreeReference contextRef, Intent detailIntent) {
if (detailIntent == null) {
detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class);
}
// grab the session's (form) element reference, and load it.
TreeReference elementRef =
XPathReference.getPathExpr(selectDatum.getValue()).getReference(true);
AbstractTreeElement element =
asw.getEvaluationContext().resolveReference(elementRef.contextualize(contextRef));
String value = "";
// get the case id and add it to the intent
if(element != null && element.getValue() != null) {
value = element.getValue().uncast().getString();
}
detailIntent.putExtra(SessionFrame.STATE_DATUM_VAL, value);
// Include long datum info if present. Otherwise that'll be the queue
// to just return
if (selectDatum.getLongDetail() != null) {
detailIntent.putExtra(EntityDetailActivity.DETAIL_ID,
selectDatum.getLongDetail());
detailIntent.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID,
selectDatum.getPersistentDetail());
}
SerializationUtil.serializeToIntent(detailIntent,
EntityDetailActivity.CONTEXT_REFERENCE, contextRef);
return detailIntent;
}
/*
* (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
if(id == EntityListAdapter.SPECIAL_ACTION) {
triggerDetailAction();
return;
}
TreeReference selection = adapter.getItem(position);
if(inAwesomeMode) {
displayReferenceAwesome(selection, position);
updateSelectedItem(selection, false);
} else {
Intent i = getDetailIntent(selection, null);
i.putExtra("entity_detail_index", position);
if (mNoDetailMode) {
returnWithResult(i);
} else {
startActivityForResult(i, CONFIRM_SELECT);
}
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch(requestCode){
case BARCODE_FETCH:
if(resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("SCAN_RESULT");
this.searchbox.setText(result);
}
break;
case CALLOUT:
if(resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("odk_intent_data");
if(result != null){
this.searchbox.setText(result);
break;
}
//just use first non-null response for now
Callout callout = shortSelect.getCallout();
for (String key: callout.getResponses()){
String result2 = intent.getStringExtra(key);
if(result != null) {
this.searchbox.setText(result2);
break;
}
}
}
case CONFIRM_SELECT:
resuming = true;
if(resultCode == RESULT_OK && !mViewMode) {
// create intent for return and store path
returnWithResult(intent);
return;
} else {
//Did we enter the detail from mapping mode? If so, go back to that
if(mResultIsMap) {
mResultIsMap = false;
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return;
}
if (inAwesomeMode) {
// Retain original element selection
TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
if (r != null && adapter != null) {
// TODO: added 'adapter != null' due to a
// NullPointerException, we need to figure out how to
// make sure adapter is never null -- PLM
this.displayReferenceAwesome(r, adapter.getPosition(r));
updateSelectedItem(r, true);
}
releaseCurrentMediaEntity();
}
return;
}
case MAP_SELECT:
if(resultCode == RESULT_OK) {
TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
if(inAwesomeMode) {
this.displayReferenceAwesome(r, adapter.getPosition(r));
} else {
Intent i = this.getDetailIntent(r, null);
if(mNoDetailMode) {
returnWithResult(i);
} else {
//To go back to map mode if confirm is false
mResultIsMap = true;
i.putExtra("entity_detail_index", adapter.getPosition(r));
startActivityForResult(i, CONFIRM_SELECT);
}
return;
}
} else {
refreshView();
return;
}
default:
super.onActivityResult(requestCode, resultCode, intent);
}
}
private void returnWithResult(Intent intent) {
Intent i = new Intent(this.getIntent());
i.putExtras(intent.getExtras());
setResult(RESULT_OK, i);
finish();
}
public void afterTextChanged(Editable s) {
if(searchbox.getText() == s) {
filterString = s.toString();
if(adapter != null) {
adapter.applyFilter(filterString);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SORT, MENU_SORT, localize("select.menu.sort")).setIcon(
android.R.drawable.ic_menu_sort_alphabetically);
if(mMappingEnabled) {
menu.add(0, MENU_MAP, MENU_MAP, localize("select.menu.map")).setIcon(
android.R.drawable.ic_menu_mapmode);
}
Action action = shortSelect.getCustomAction();
if(action != null) {
ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION, action.getDisplay());
}
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//only display the sort menu if we're going to be able to sort
//(IE: not until the items have loaded)
menu.findItem(MENU_SORT).setEnabled(adapter != null);
return super.onPrepareOptionsMenu(menu);
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SORT:
createSortMenu();
return true;
case MENU_MAP:
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return true;
case MENU_ACTION:
triggerDetailAction();
return true;
}
return super.onOptionsItemSelected(item);
}
private void triggerDetailAction() {
Action action = shortSelect.getCustomAction();
asw.executeStackActions(action.getStackOperations());
this.setResult(CommCareHomeActivity.RESULT_RESTART);
this.finish();
}
private void createSortMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(localize("select.menu.sort"));
SessionDatum datum = session.getNeededDatum();
DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields();
List<String> namesList = new ArrayList<String>();
final int[] keyarray = new int[fields.length];
int[] sorts = adapter.getCurrentSort();
int currentSort = sorts.length == 1 ? sorts[0] : -1;
boolean reversed = adapter.isCurrentSortReversed();
int added = 0;
for(int i = 0 ; i < fields.length ; ++i) {
String result = fields[i].getHeader().evaluate();
if(!"".equals(result)) {
String prepend = "";
if(currentSort == -1) {
for(int j = 0 ; j < sorts.length ; ++ j) {
if(sorts[j] == i) {
prepend = (j+1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ");
}
}
} else if(currentSort == i) {
prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ";
}
namesList.add(prepend + result);
keyarray[added] = i;
added++;
}
}
final String[] names = namesList.toArray(new String[0]);
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
adapter.sortEntities(new int[] { keyarray[item]});
adapter.applyFilter(searchbox.getText().toString());
}
});
builder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
if(loader != null) {
if(isFinishing()) {
loader.cancel(false);
} else {
loader.detachActivity();
}
}
if(adapter != null) {
adapter.signalKilled();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
/*
* (non-Javadoc)
* @see android.speech.tts.TextToSpeech.OnInitListener#onInit(int)
*/
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//using the default speech engine for now.
} else {
}
}
/*
* (non-Javadoc)
* @see org.commcare.android.tasks.EntityLoaderListener#deliverResult(java.util.List, java.util.List)
*/
@Override
public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references, NodeEntityFactory factory) {
loader = null;
Detail detail = session.getDetail(selectDatum.getShortDetail());
int[] order = detail.getSortOrder();
for(int i = 0 ; i < detail.getFields().length ; ++i) {
String header = detail.getFields()[i].getHeader().evaluate();
if(order.length == 0 && !"".equals(header)) {
order = new int[] {i};
}
}
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, this, factory);
view.setAdapter(adapter);
adapter.registerDataSetObserver(this.mListStateObserver);
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
if(adapter != null && filterString != null && !"".equals(filterString)) {
adapter.applyFilter(filterString);
}
//In landscape we want to select something now. Either the top item, or the most recently selected one
if(inAwesomeMode) {
updateSelectedItem(true);
}
this.startTimer();
}
private void updateSelectedItem(boolean forceMove) {
TreeReference chosen = null;
if(selectedIntent != null) {
chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
}
updateSelectedItem(chosen, forceMove);
}
private void updateSelectedItem(TreeReference selected, boolean forceMove) {
if(adapter == null) {return;}
if(selected != null) {
adapter.notifyCurrentlyHighlighted(selected);
if(forceMove) {
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
view.setSelection(adapter.getPosition(selected));
}
return;
}
}
/*
* (non-Javadoc)
* @see org.commcare.android.tasks.EntityLoaderListener#attach(org.commcare.android.tasks.EntityLoaderTask)
*/
@Override
public void attach(EntityLoaderTask task) {
findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE);
this.loader = task;
}
public boolean inAwesomeMode(){
return inAwesomeMode;
}
boolean rightFrameSetup = false;
NodeEntityFactory factory;
private void select() {
// create intent for return and store path
Intent i = new Intent(EntitySelectActivity.this.getIntent());
i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL));
setResult(RESULT_OK, i);
finish();
}
// CommCare-159503: implementing DetailCalloutListener so it will not crash the app when requesting call/sms
public void callRequested(String phoneNumber) {
DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber);
}
public void addressRequested(String address) {
DetailCalloutListenerDefaultImpl.addressRequested(this, address);
}
public void playVideo(String videoRef) {
DetailCalloutListenerDefaultImpl.playVideo(this, videoRef);
}
public void performCallout(Callout callout, int id) {
DetailCalloutListenerDefaultImpl.performCallout(this, callout, id);
}
public void displayReferenceAwesome(final TreeReference selection, int detailIndex) {
selectedIntent = getDetailIntent(selection, getIntent());
//this should be 100% "fragment" able
if(!rightFrameSetup) {
findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE);
View.inflate(this, R.layout.entity_detail, rightFrame);
Button next = (Button)findViewById(R.id.entity_select_button);
next.setText(Localization.get("select.detail.confirm"));
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
select();
return;
}
});
if (mViewMode) {
next.setVisibility(View.GONE);
}
String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID);
if (passedCommand != null) {
mViewMode = session.isViewCommand(passedCommand);
} else {
mViewMode = session.isViewCommand(session.getCommand());
}
detailView = new TabbedDetailView(this);
detailView.setRoot((ViewGroup) rightFrame.findViewById(R.id.entity_detail_tabs));
factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new CommCareInstanceInitializer(session)));
Detail detail = factory.getDetail();
detailView.setDetail(detail);
if (detail.isCompound()) {
// border around right panel doesn't look right when there are tabs
rightFrame.setBackgroundDrawable(null);
}
rightFrameSetup = true;
}
detailView.refresh(factory.getDetail(), selection, detailIndex, false);
}
/*
* (non-Javadoc)
* @see org.commcare.android.tasks.EntityLoaderListener#deliverError(java.lang.Exception)
*/
@Override
public void deliverError(Exception e) {
displayException(e);
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onForwardSwipe()
*/
@Override
protected boolean onForwardSwipe() {
// If user has picked an entity, move along to form entry
if (selectedIntent != null) {
if (inAwesomeMode && detailView != null && detailView.getCurrentTab() < detailView.getTabCount() - 1) {
return false;
}
if (!mViewMode) {
select();
}
}
return true;
}
/*
* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onBackwardSwipe()
*/
@Override
protected boolean onBackwardSwipe() {
if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) {
return false;
}
finish();
return true;
}
//Below is helper code for the Refresh Feature.
//this is a dev feature and should get restructured before release in prod.
//If the devloper setting is turned off this code should do nothing.
private void triggerRebuild() {
if(loader == null && !EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
}
}
private Timer myTimer;
private Object timerLock = new Object();
boolean cancelled;
private void startTimer() {
if(!DeveloperPreferences.isListRefreshEnabled()) { return; }
synchronized(timerLock) {
if(myTimer == null) {
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread( new Runnable() {
@Override
public void run() {
if(!cancelled) {
triggerRebuild();
}
}
});
}
}, 15*1000, 15 * 1000);
cancelled = false;
}
}
}
private void stopTimer() {
synchronized(timerLock) {
if(myTimer != null) {
myTimer.cancel();
myTimer = null;
cancelled = true;
}
}
}
}
|
package org.commcare.dalvik.application;
import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteException;
import org.acra.annotation.ReportsCrashes;
import org.commcare.android.database.AndroidDbHelper;
import org.commcare.android.database.MigrationException;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.UserStorageClosedException;
import org.commcare.android.database.app.DatabaseAppOpenHelper;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.global.DatabaseGlobalOpenHelper;
import org.commcare.android.database.global.models.ApplicationRecord;
import org.commcare.android.database.user.CommCareUserOpenHelper;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.android.db.legacy.LegacyInstallUtils;
import org.commcare.android.framework.SessionActivityRegistration;
import org.commcare.android.javarosa.AndroidLogEntry;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.javarosa.PreInitLogger;
import org.commcare.android.logic.GlobalConstants;
import org.commcare.android.models.AndroidSessionWrapper;
import org.commcare.android.models.notifications.NotificationClearReceiver;
import org.commcare.android.models.notifications.NotificationMessage;
import org.commcare.android.references.ArchiveFileRoot;
import org.commcare.android.references.AssetFileRoot;
import org.commcare.android.references.JavaHttpRoot;
import org.commcare.android.resource.ResourceInstallUtils;
import org.commcare.android.storage.framework.Table;
import org.commcare.android.tasks.DataSubmissionListener;
import org.commcare.android.tasks.ExceptionReportTask;
import org.commcare.android.tasks.LogSubmissionTask;
import org.commcare.android.tasks.PurgeStaleArchivedFormsTask;
import org.commcare.android.tasks.UpdateTask;
import org.commcare.android.tasks.templates.ManagedAsyncTask;
import org.commcare.android.util.ACRAUtil;
import org.commcare.android.util.AndroidCommCarePlatform;
import org.commcare.android.util.AndroidUtil;
import org.commcare.android.util.CallInPhoneListener;
import org.commcare.android.util.CommCareExceptionHandler;
import org.commcare.android.util.FileUtil;
import org.commcare.android.util.ODKPropertyManager;
import org.commcare.android.util.SessionStateUninitException;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.activities.LoginActivity;
import org.commcare.dalvik.activities.MessageActivity;
import org.commcare.dalvik.activities.UnrecoverableErrorActivity;
import org.commcare.dalvik.odk.provider.ProviderUtils;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.commcare.dalvik.services.CommCareSessionService;
import org.commcare.session.CommCareSession;
import org.commcare.suite.model.Profile;
import org.commcare.util.externalizable.AndroidClassHasher;
import org.javarosa.core.model.User;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.EntityFilter;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.PropertyUtils;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import javax.crypto.SecretKey;
/**
* @author ctsims
*/
@ReportsCrashes(
formUri = "https://your/cloudant/report",
formUriBasicAuthLogin = "your_username",
formUriBasicAuthPassword = "your_password",
reportType = org.acra.sender.HttpSender.Type.JSON,
httpMethod = org.acra.sender.HttpSender.Method.PUT)
public class CommCareApplication extends Application {
private static final String TAG = CommCareApplication.class.getSimpleName();
private static final int STATE_UNINSTALLED = 0;
public static final int STATE_UPGRADE = 1;
private static final int STATE_READY = 2;
public static final int STATE_CORRUPTED = 4;
public static final int STATE_DELETE_REQUESTED = 8;
public static final int STATE_MIGRATION_FAILED = 16;
public static final int STATE_MIGRATION_QUESTIONABLE = 32;
private static final String ACTION_PURGE_NOTIFICATIONS = "CommCareApplication_purge";
private int dbState;
private static CommCareApplication app;
private CommCareApp currentApp;
// stores current state of application: the session, form
private AndroidSessionWrapper sessionWrapper;
private final Object globalDbHandleLock = new Object();
private SQLiteDatabase globalDatabase;
private ArchiveFileRoot mArchiveFileRoot;
// Fields for managing a connection to the CommCareSessionService
// A bound service is created out of the CommCareSessionService to ensure
// it stays in memory.
private CommCareSessionService mBoundService;
private ServiceConnection mConnection;
private final Object serviceLock = new Object();
// Has the CommCareSessionService been bound?
private boolean mIsBound = false;
// Has CommCareSessionService initilization finished?
// Important so we don't use the service before the db is initialized.
private boolean mIsBinding = false;
//Milliseconds to wait for bind
private static final int MAX_BIND_TIMEOUT = 5000;
private int mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT;
private CallInPhoneListener listener = null;
/**
* Handler to receive notifications and show them the user using toast.
*/
private final PopupHandler toaster = new PopupHandler(this);
@Override
public void onCreate() {
super.onCreate();
//Sets the static strategy for the deserializtion code to be
//based on an optimized md5 hasher. Major speed improvements.
AndroidClassHasher.registerAndroidClassHashStrategy();
AndroidUtil.initializeStaticHandlers();
CommCareApplication.app = this;
//TODO: Make this robust
PreInitLogger pil = new PreInitLogger();
Logger.registerLogger(pil);
//Workaround because android is written by 7 year olds.
//(reuses http connection pool improperly, so the second https
//request in a short time period will flop)
System.setProperty("http.keepAlive", "false");
Thread.setDefaultUncaughtExceptionHandler(new CommCareExceptionHandler(Thread.getDefaultUncaughtExceptionHandler(), this));
PropertyManager.setPropertyManager(new ODKPropertyManager());
SQLiteDatabase.loadLibs(this);
setRoots();
prepareTemporaryStorage();
//Init global storage (Just application records, logs, etc)
dbState = initGlobalDb();
//This is where we go through and check for updates between major transitions.
//Soon we should start doing this differently, and actually go to an activity
//first which tells the user what's going on.
//The rule about this transition is that if the user had logs pending, we still want them in order, so
//we aren't going to dump our logs from the Pre-init logger until after this transition occurs.
try {
LegacyInstallUtils.checkForLegacyInstall(this, this.getGlobalStorage(ApplicationRecord.class));
} catch (SessionUnavailableException sfe) {
throw new RuntimeException(sfe);
} finally {
//No matter what happens, set up our new logger, we want those logs!
Logger.registerLogger(new AndroidLogger(this.getGlobalStorage(AndroidLogEntry.STORAGE_KEY, AndroidLogEntry.class)));
pil.dumpToNewLogger();
}
intializeDefaultLocalizerData();
if (dbState != STATE_MIGRATION_FAILED && dbState != STATE_MIGRATION_QUESTIONABLE) {
initializeAnAppOnStartup();
}
ACRAUtil.initACRA(this);
}
public void triggerHandledAppExit(Context c, String message) {
triggerHandledAppExit(c, message, Localization.get("app.handled.error.title"));
}
public void triggerHandledAppExit(Context c, String message, String title) {
triggerHandledAppExit(c, message, title, true);
}
public void triggerHandledAppExit(Context c, String message, String title,
boolean useExtraMessage) {
Intent i = new Intent(c, UnrecoverableErrorActivity.class);
i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_TITLE, title);
i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_MESSAGE, message);
i.putExtra(UnrecoverableErrorActivity.EXTRA_USE_MESSAGE, useExtraMessage);
// start a new stack and forget where we were (so we don't restart the
// app from there)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_CLEAR_TOP);
c.startActivity(i);
}
public void startUserSession(byte[] symetricKey, UserKeyRecord record) {
synchronized (serviceLock) {
// if we already have a connection established to
// CommCareSessionService, close it and open a new one
if (this.mIsBound) {
releaseUserResourcesAndServices();
}
bindUserSessionService(symetricKey, record);
}
}
/**
* Closes down the user service, resources, and background tasks. Used for
* manual user log-outs.
*/
public void closeUserSession() {
synchronized (serviceLock) {
// Cancel any running tasks before closing down the user databse.
ManagedAsyncTask.cancelTasks();
releaseUserResourcesAndServices();
}
}
/**
* Closes down the user service, resources, and background tasks,
* broadcasting an intent to redirect the user to the login screen. Used
* for session-expiration related user logouts.
*/
public void expireUserSession() {
synchronized (serviceLock) {
closeUserSession();
SessionActivityRegistration.registerSessionExpiration();
sendBroadcast(new Intent(SessionActivityRegistration.USER_SESSION_EXPIRED));
}
}
public void releaseUserResourcesAndServices() {
try {
CommCareApplication._().getSession().closeServiceResources();
} catch (SessionUnavailableException e) {
Log.w(TAG, "User's session services have unexpectedly already " +
"been closed down. Proceeding to close the session.");
}
unbindUserSessionService();
}
public SecretKey createNewSymetricKey() throws SessionUnavailableException {
return getSession().createNewSymetricKey();
}
private void attachCallListener() {
TelephonyManager tManager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);
listener = new CallInPhoneListener(this, this.getCommCarePlatform());
listener.startCache();
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
public CallInPhoneListener getCallListener() {
return listener;
}
public int[] getCommCareVersion() {
return this.getResources().getIntArray(R.array.commcare_version);
}
public AndroidCommCarePlatform getCommCarePlatform() {
if (this.currentApp == null) {
throw new RuntimeException("No App installed!!!");
} else {
return this.currentApp.getCommCarePlatform();
}
}
public CommCareApp getCurrentApp() {
return this.currentApp;
}
/**
* Get the current CommCare session that's being executed
*/
public CommCareSession getCurrentSession() {
return getCurrentSessionWrapper().getSession();
}
public AndroidSessionWrapper getCurrentSessionWrapper() {
if (sessionWrapper == null) {
throw new SessionStateUninitException("CommCare user session isn't available");
}
return sessionWrapper;
}
public int getDatabaseState() {
return dbState;
}
public void initializeGlobalResources(CommCareApp app) {
if (dbState != STATE_UNINSTALLED) {
initializeAppResources(app);
}
}
public String getPhoneId() {
TelephonyManager manager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);
String imei = manager.getDeviceId();
if (imei == null) {
imei = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
}
return imei;
}
public void intializeDefaultLocalizerData() {
Localization.init(true);
Localization.registerLanguageReference("default",
"jr://asset/locales/messages_ccodk_default.txt");
Localization.setDefaultLocale("default");
//For now. Possibly handle this better in the future
Localization.setLocale("default");
}
private void setRoots() {
JavaHttpRoot http = new JavaHttpRoot();
AssetFileRoot afr = new AssetFileRoot(this);
ArchiveFileRoot arfr = new ArchiveFileRoot();
mArchiveFileRoot = arfr;
ReferenceManager._().addReferenceFactory(http);
ReferenceManager._().addReferenceFactory(afr);
ReferenceManager._().addReferenceFactory(arfr);
ReferenceManager._().addRootTranslator(new RootTranslator("jr://media/",
GlobalConstants.MEDIA_REF));
}
/**
* Performs the appropriate initialization of an application when this CommCareApplication is
* first launched
*/
private void initializeAnAppOnStartup() {
// Before we try to initialize a new app, check if any existing apps were left in a
// partially deleted state, and finish uninstalling them if so
for (ApplicationRecord record : getGlobalStorage(ApplicationRecord.class)) {
if (record.getStatus() == ApplicationRecord.STATUS_DELETE_REQUESTED) {
try {
uninstall(record);
} catch (RuntimeException e) {
Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Unable to uninstall an app " +
"during startup that was previously left partially-deleted");
}
}
}
// There may now be multiple app records in storage, because of multiple apps support. We
// want to initialize one of them to start, so that there will be currently-seated app when
// the login screen starts up
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String lastAppId = prefs.getString(LoginActivity.KEY_LAST_APP, "");
if (!"".equals(lastAppId)) {
// If there is a 'last app' set in shared preferences, try to initialize that application.
ApplicationRecord lastApp = getAppById(lastAppId);
if (lastApp == null || !lastApp.isUsable()) {
// This app record could be null if it has since been uninstalled, or unusable if
// it has since been archived, etc. In either case, just revert to picking the
// first app
initFirstUsableAppRecord();
} else {
initializeAppResources(new CommCareApp(lastApp));
}
} else {
// Otherwise, just pick the first app in the list to initialize
initFirstUsableAppRecord();
}
}
/**
* Initializes the first "usable" application from the list of globally installed app records,
* if there is one
*/
public void initFirstUsableAppRecord() {
for (ApplicationRecord record : getUsableAppRecords()) {
initializeAppResources(new CommCareApp(record));
break;
}
}
/**
* Initialize all of the given app's resources, and set the state of its resources accordingly
*
* @param app the CC app to initialize
*/
public void initializeAppResources(CommCareApp app) {
int resourceState;
try {
currentApp = app;
if (currentApp.initializeApplication()) {
resourceState = STATE_READY;
this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform());
} else {
resourceState = STATE_CORRUPTED;
}
} catch (Exception e) {
Log.i("FAILURE", "Problem with loading");
Log.i("FAILURE", "E: " + e.getMessage());
e.printStackTrace();
ExceptionReportTask ert = new ExceptionReportTask();
ert.execute(e);
resourceState = STATE_CORRUPTED;
}
app.setAppResourceState(resourceState);
}
/**
* @return all ApplicationRecords in storage, regardless of their status, in alphabetical order
*/
public ArrayList<ApplicationRecord> getInstalledAppRecords() {
ArrayList<ApplicationRecord> records = new ArrayList<>();
for (ApplicationRecord r : getGlobalStorage(ApplicationRecord.class)) {
records.add(r);
}
Collections.sort(records, new Comparator<ApplicationRecord>() {
@Override
public int compare(ApplicationRecord lhs, ApplicationRecord rhs) {
return lhs.getDisplayName().compareTo(rhs.getDisplayName());
}
});
return records;
}
/**
* @return all ApplicationRecords that have status installed and are NOT archived
*/
public ArrayList<ApplicationRecord> getVisibleAppRecords() {
ArrayList<ApplicationRecord> visible = new ArrayList<>();
for (ApplicationRecord r : getInstalledAppRecords()) {
if (r.isVisible()) {
visible.add(r);
}
}
return visible;
}
/**
* @return all ApplicationRecords that are installed AND are not archived AND have MM verified
*/
public ArrayList<ApplicationRecord> getUsableAppRecords() {
ArrayList<ApplicationRecord> ready = new ArrayList<>();
for (ApplicationRecord r : getInstalledAppRecords()) {
if (r.isUsable()) {
ready.add(r);
}
}
return ready;
}
/**
* @return whether the user should be sent to CommCareVerificationActivity. Current logic is
* that this should occur only if there is exactly one visible app and it is missing its MM
* (because we are then assuming the user is not currently using multiple apps functionality)
*/
public boolean shouldSeeMMVerification() {
return (CommCareApplication._().getVisibleAppRecords().size() == 1 &&
CommCareApplication._().getUsableAppRecords().size() == 0);
}
public boolean usableAppsPresent() {
return getUsableAppRecords().size() > 0;
}
/**
* @return the list of all installed apps as an array
*/
public ApplicationRecord[] appRecordArray() {
ArrayList<ApplicationRecord> appList = CommCareApplication._().getInstalledAppRecords();
ApplicationRecord[] appArray = new ApplicationRecord[appList.size()];
int index = 0;
for (ApplicationRecord r : appList) {
appArray[index++] = r;
}
return appArray;
}
/**
* @param uniqueId - the uniqueId of the ApplicationRecord being sought
* @return the ApplicationRecord corresponding to the given id, if it exists. Otherwise,
* return null
*/
public ApplicationRecord getAppById(String uniqueId) {
for (ApplicationRecord r : getInstalledAppRecords()) {
if (r.getUniqueId().equals(uniqueId)) {
return r;
}
}
return null;
}
/**
* @return if the given ApplicationRecord is the currently seated one
*/
public boolean isSeated(ApplicationRecord record) {
return currentApp != null && currentApp.getUniqueId().equals(record.getUniqueId());
}
/**
* If the given record is the currently seated app, unseat it
*/
public void unseat(ApplicationRecord record) {
if (isSeated(record)) {
this.currentApp.teardownSandbox();
this.currentApp = null;
}
}
/**
* Completes a full uninstall of the CC app that the given ApplicationRecord represents.
* This method should be idempotent and should be capable of completing an uninstall
* regardless of previous failures
*/
public void uninstall(ApplicationRecord record) {
CommCareApp app = new CommCareApp(record);
// 1) If the app we are uninstalling is the currently-seated app, tear down its sandbox
if (isSeated(record)) {
getCurrentApp().teardownSandbox();
}
// 2) Set record's status to delete requested, so we know if we have left it in a bad
// state later
record.setStatus(ApplicationRecord.STATUS_DELETE_REQUESTED);
getGlobalStorage(ApplicationRecord.class).write(record);
// 3) Delete the directory containing all of this app's resources
if (!FileUtil.deleteFileOrDir(app.storageRoot())) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "App storage root was unable to be " +
"deleted during app uninstall. Aborting uninstall process for now.");
return;
}
// 4) Delete all the user databases associated with this app
SqlStorage<UserKeyRecord> userDatabase = app.getStorage(UserKeyRecord.class);
for (UserKeyRecord user : userDatabase) {
File f = getDatabasePath(CommCareUserOpenHelper.getDbName(user.getUuid()));
if (!FileUtil.deleteFileOrDir(f)) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "A user database was unable to be " +
"deleted during app uninstall. Aborting uninstall process for now.");
// If we failed to delete a file, it is likely because there is an open pointer
// to that db still in use, so stop the uninstall for now, and rely on it to
// complete the next time the app starts up
return;
}
}
// 5) Delete the forms database for this app
File formsDb = getDatabasePath(ProviderUtils.getProviderDbName(
ProviderUtils.ProviderType.FORMS,
app.getAppRecord().getApplicationId()));
if (!FileUtil.deleteFileOrDir(formsDb)) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's forms database was unable to be " +
"deleted during app uninstall. Aborting uninstall process for now.");
return;
}
// 6) Delete the instances database for this app
File instancesDb = getDatabasePath(ProviderUtils.getProviderDbName(
ProviderUtils.ProviderType.INSTANCES,
app.getAppRecord().getApplicationId()));
if (!FileUtil.deleteFileOrDir(instancesDb)) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's instances database was unable to" +
" be deleted during app uninstall. Aborting uninstall process for now.");
return;
}
// 7) Delete the app database
File f = getDatabasePath(DatabaseAppOpenHelper.getDbName(app.getAppRecord().getApplicationId()));
if (!FileUtil.deleteFileOrDir(f)) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "The app database was unable to be deleted" +
"during app uninstall. Aborting uninstall process for now.");
return;
}
// 8) Delete the ApplicationRecord
getGlobalStorage(ApplicationRecord.class).remove(record.getID());
}
private int initGlobalDb() {
SQLiteDatabase database;
try {
database = new DatabaseGlobalOpenHelper(this).getWritableDatabase("null");
database.close();
return STATE_READY;
} catch (SQLiteException e) {
//Only thrown if DB isn't there
return STATE_UNINSTALLED;
} catch (MigrationException e) {
if (e.isDefiniteFailure()) {
return STATE_MIGRATION_FAILED;
} else {
return STATE_MIGRATION_QUESTIONABLE;
}
}
}
public SQLiteDatabase getUserDbHandle() throws SessionUnavailableException {
return this.getSession().getUserDbHandle();
}
public <T extends Persistable> SqlStorage<T> getGlobalStorage(Class<T> c) {
return getGlobalStorage(c.getAnnotation(Table.class).value(), c);
}
public <T extends Persistable> SqlStorage<T> getGlobalStorage(String table, Class<T> c) {
return new SqlStorage<>(table, c, new AndroidDbHelper(this.getApplicationContext()) {
@Override
public SQLiteDatabase getHandle() {
synchronized (globalDbHandleLock) {
if (globalDatabase == null || !globalDatabase.isOpen()) {
globalDatabase = new DatabaseGlobalOpenHelper(this.c).getWritableDatabase("null");
}
return globalDatabase;
}
}
});
}
public <T extends Persistable> SqlStorage<T> getAppStorage(Class<T> c) {
return getAppStorage(c.getAnnotation(Table.class).value(), c);
}
public <T extends Persistable> SqlStorage<T> getAppStorage(String name, Class<T> c) {
return currentApp.getStorage(name, c);
}
public <T extends Persistable> SqlStorage<T> getUserStorage(Class<T> c) {
return getUserStorage(c.getAnnotation(Table.class).value(), c);
}
public <T extends Persistable> SqlStorage<T> getUserStorage(String storage, Class<T> c) {
return new SqlStorage<>(storage, c, new AndroidDbHelper(this.getApplicationContext()) {
@Override
public SQLiteDatabase getHandle() throws SessionUnavailableException {
SQLiteDatabase database = getUserDbHandle();
if (database == null) {
throw new SessionUnavailableException("The user database has been closed!");
}
return database;
}
});
}
public <T extends Persistable> SqlStorage<T> getRawStorage(String storage, Class<T> c, final SQLiteDatabase handle) {
return new SqlStorage<>(storage, c, new AndroidDbHelper(this.getApplicationContext()) {
@Override
public SQLiteDatabase getHandle() {
return handle;
}
});
}
public static CommCareApplication _() {
return app;
}
/**
* This method wipes out all local user data (users, referrals, etc) but leaves
* application resources in place.
*
* It makes no attempt to make sure this is a safe operation when called, so
* it shouldn't be used lightly.
*/
public void clearUserData() {
// //First clear anything that will require the user's key, since we're going to wipe it out!
// getStorage(ACase.STORAGE_KEY, ACase.class).removeAll();
// //TODO: We should really be wiping out the _stored_ instances here, too
// getStorage(FormRecord.STORAGE_KEY, FormRecord.class).removeAll();
// //Also, any of the sessions we've got saved
// getStorage(SessionStateDescriptor.STORAGE_KEY, SessionStateDescriptor.class).removeAll();
// //Now we wipe out the user entirely
// getStorage(User.STORAGE_KEY, User.class).removeAll();
// //Get rid of any user fixtures
// getStorage("fixture", FormInstance.class).removeAll();
// getStorage(GeocodeCacheModel.STORAGE_KEY, GeocodeCacheModel.class).removeAll();
final String username;
try {
username = this.getSession().getLoggedInUser().getUsername();
} catch (SessionUnavailableException e) {
return;
}
final Set<String> dbIdsToRemove = new HashSet<>();
this.getAppStorage(UserKeyRecord.class).removeAll(new EntityFilter<UserKeyRecord>() {
@Override
public boolean matches(UserKeyRecord ukr) {
if (ukr.getUsername().equalsIgnoreCase(username.toLowerCase())) {
dbIdsToRemove.add(ukr.getUuid());
return true;
}
return false;
}
});
//TODO: We can just delete the db entirely.
Editor sharedPreferencesEditor = CommCareApplication._().getCurrentApp().getAppPreferences().edit();
sharedPreferencesEditor.putString(CommCarePreferences.LAST_LOGGED_IN_USER, null);
sharedPreferencesEditor.commit();
for (String id : dbIdsToRemove) {
//TODO: We only wanna do this if the user is the _last_ one with a key to this id, actually.
//(Eventually)
this.getDatabasePath(CommCareUserOpenHelper.getDbName(id)).delete();
}
CommCareApplication._().closeUserSession();
}
public void prepareTemporaryStorage() {
String tempRoot = this.getAndroidFsTemp();
FileUtil.deleteFileOrDir(tempRoot);
boolean success = FileUtil.createFolder(tempRoot);
if (!success) {
Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Couldn't create temp folder");
}
}
public String getCurrentVersionString() {
PackageManager pm = this.getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
return "ERROR! Incorrect package version requested";
}
int[] versions = this.getCommCareVersion();
String ccv = "";
for (int vn : versions) {
if (!"".equals(ccv)) {
ccv += ".";
}
ccv += vn;
}
String profileVersion = "";
Profile p = this.currentApp == null ? null : this.getCommCarePlatform().getCurrentProfile();
if (p != null) {
profileVersion = String.valueOf(p.getVersion());
}
String buildDate = BuildConfig.BUILD_DATE;
String buildNumber = BuildConfig.BUILD_NUMBER;
return Localization.get(getString(R.string.app_version_string), new String[]{pi.versionName, String.valueOf(pi.versionCode), ccv, buildNumber, buildDate, profileVersion});
}
/**
* Allows something within the current service binding to update the app to let it
* know that the bind may take longer than the current timeout can allow
*/
public void setCustomServiceBindTimeout(int timeout) {
synchronized (serviceLock) {
this.mCurrentServiceBindTimeout = timeout;
}
}
private void bindUserSessionService(final byte[] key, final UserKeyRecord record) {
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
User user = null;
synchronized (serviceLock) {
mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT;
mBoundService = ((CommCareSessionService.LocalBinder)service).getService();
//Don't let anyone touch this until it's logged in
// Open user database
mBoundService.prepareStorage(key, record);
if (record != null) {
//Ok, so we have a login that was successful, but do we have a user model in the DB?
//We need to check before we're logged in, so we get the handle raw, here
for (User u : getRawStorage("USER", User.class, mBoundService.getUserDbHandle())) {
if (record.getUsername().equals(u.getUsername())) {
user = u;
}
}
}
//service available
mIsBound = true;
//Don't signal bind completion until the db is initialized.
mIsBinding = false;
if (user != null) {
mBoundService.startSession(user);
attachCallListener();
CommCareApplication.this.sessionWrapper = new AndroidSessionWrapper(CommCareApplication.this.getCommCarePlatform());
if (shouldAutoUpdate()) {
startAutoUpdate();
}
syncPending = getPendingSyncStatus();
doReportMaintenance(false);
//Register that this user was the last to successfully log in if it's a real user
if (!User.TYPE_DEMO.equals(user.getUserType())) {
getCurrentApp().getAppPreferences().edit().putString(CommCarePreferences.LAST_LOGGED_IN_USER, record.getUsername()).commit();
PurgeStaleArchivedFormsTask.launchPurgeTask();
}
}
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
}
};
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
startService(new Intent(this, CommCareSessionService.class));
bindService(new Intent(this, CommCareSessionService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBinding = true;
}
@SuppressLint("NewApi")
protected void doReportMaintenance(boolean force) {
//OK. So for now we're going to daily report sends and not bother with any of the frequency properties.
//Create a new submission task no matter what. If nothing is pending, it'll see if there are unsent reports
//and try to send them. Otherwise, it'll create the report
SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences();
String url = settings.getString("PostURL", null);
if (url == null) {
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "PostURL isn't set. This should never happen");
return;
}
DataSubmissionListener dataListener;
try {
dataListener =
CommCareApplication.this.getSession().startDataSubmissionListener(R.string.submission_logs_title);
} catch (SessionUnavailableException sue) {
// abort since it looks like the session expired
return;
}
LogSubmissionTask task = new LogSubmissionTask(
force || isPending(settings.getLong(CommCarePreferences.LOG_LAST_DAILY_SUBMIT, 0), DateUtils.DAY_IN_MILLIS),
dataListener,
url);
//Execute on a true multithreaded chain, since this is an asynchronous process
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}
}
/**
* @return True if we aren't a demo user and the time to check for an
* update has elapsed or we logged out while an auto-update was downlaoding
* or queued for retry.
*/
private boolean shouldAutoUpdate() {
return (!areAutomatedActionsInvalid() &&
(ResourceInstallUtils.shouldAutoUpdateResume(getCurrentApp()) ||
isUpdatePending()));
}
private void startAutoUpdate() {
Logger.log(AndroidLogger.TYPE_MAINTENANCE, "Auto-Update Triggered");
String ref = ResourceInstallUtils.getDefaultProfileRef();
try {
UpdateTask updateTask = UpdateTask.getNewInstance();
updateTask.startPinnedNotification(this);
updateTask.setAsAutoUpdate();
updateTask.execute(ref);
} catch (IllegalStateException e) {
Log.w(TAG, "Trying trigger auto-update when it is already running. " +
"Should only happen if the user triggered a manual update before this fired.");
}
}
public boolean isUpdatePending() {
SharedPreferences preferences = getCurrentApp().getAppPreferences();
//Establish whether or not an AutoUpdate is Pending
String autoUpdateFreq =
preferences.getString(CommCarePreferences.AUTO_UPDATE_FREQUENCY,
CommCarePreferences.FREQUENCY_NEVER);
//See if auto update is even turned on
if (!autoUpdateFreq.equals(CommCarePreferences.FREQUENCY_NEVER)) {
long lastUpdateCheck =
preferences.getLong(CommCarePreferences.LAST_UPDATE_ATTEMPT, 0);
return isTimeForAutoUpdateCheck(lastUpdateCheck, autoUpdateFreq);
}
return false;
}
public boolean isTimeForAutoUpdateCheck(long lastUpdateCheck, String autoUpdateFreq) {
int checkEveryNDays;
if (CommCarePreferences.FREQUENCY_DAILY.equals(autoUpdateFreq)) {
checkEveryNDays = 1;
} else {
checkEveryNDays = 7;
}
long duration = DateUtils.DAY_IN_MILLIS * checkEveryNDays;
return isPending(lastUpdateCheck, duration);
}
private boolean isPending(long last, long period) {
long now = new Date().getTime();
//1) Straightforward - Time is greater than last + duration
long diff = now - last;
if (diff > period) {
return true;
}
//2) For daily stuff, we want it to be the case that if the last time you synced was the day prior,
//you still sync, so people can get into the cycle of doing it once in the morning, which
//is more valuable than syncing mid-day.
if (isDifferentDayInPast(now, last, period)) {
return true;
}
//3) Major time change - (Phone might have had its calendar day manipulated).
//for now we'll simply say that if last was more than a day in the future (timezone blur)
//we should also trigger
return (now < (last - DateUtils.DAY_IN_MILLIS));
}
private boolean isDifferentDayInPast(long now, long last, long period) {
Calendar lastRestoreCalendar = Calendar.getInstance();
lastRestoreCalendar.setTimeInMillis(last);
return period == DateUtils.DAY_IN_MILLIS &&
lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK) &&
now > last;
}
/**
* Whether automated stuff like auto-updates/syncing are valid and should
* be triggered.
*/
private boolean areAutomatedActionsInvalid() {
try {
return User.TYPE_DEMO.equals(getSession().getLoggedInUser().getUserType());
} catch (SessionUnavailableException sue) {
return true;
}
}
private void unbindUserSessionService() {
synchronized (serviceLock) {
if (mIsBound) {
if (sessionWrapper != null) {
sessionWrapper.reset();
}
mIsBound = false;
// Detach our existing connection.
unbindService(mConnection);
stopService(new Intent(this, CommCareSessionService.class));
}
}
}
public CommCareSessionService getSession() throws SessionUnavailableException {
long started = System.currentTimeMillis();
//If binding is currently in process, just wait for it.
while (mIsBinding) {
if (System.currentTimeMillis() - started > mCurrentServiceBindTimeout) {
//Something bad happened
unbindUserSessionService();
throw new SessionUnavailableException("Timeout binding to session service");
}
}
if (mIsBound) {
synchronized (serviceLock) {
return mBoundService;
}
} else {
throw new SessionUnavailableException();
}
}
/**
* @return A pair comprised of last sync time and an array with unsent and
* incomplete form counts. If the user storage isn't open, return 0 vals
* for unsent/incomplete forms.
*/
public Pair<Long, int[]> getSyncDisplayParameters() {
SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
long lastSync = prefs.getLong("last-succesful-sync", 0);
SqlStorage<FormRecord> formsStorage = this.getUserStorage(FormRecord.class);
try {
int unsentForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_UNSENT).size();
int incompleteForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE).size();
return new Pair<>(lastSync, new int[]{unsentForms, incompleteForms});
} catch (UserStorageClosedException e) {
return new Pair<>(lastSync, new int[]{0, 0});
}
}
// Start - Error message Hooks
private final int MESSAGE_NOTIFICATION = org.commcare.dalvik.R.string.notification_message_title;
private final ArrayList<NotificationMessage> pendingMessages = new ArrayList<>();
public void reportNotificationMessage(NotificationMessage message) {
reportNotificationMessage(message, false);
}
public void reportNotificationMessage(final NotificationMessage message, boolean notifyUser) {
synchronized (pendingMessages) {
//make sure there is no matching message pending
for (NotificationMessage msg : pendingMessages) {
if (msg.equals(message)) {
//If so, bail.
return;
}
}
if (notifyUser) {
Bundle b = new Bundle();
b.putParcelable("message", message);
Message m = Message.obtain(toaster);
m.setData(b);
toaster.sendMessage(m);
}
//Otherwise, add it to the queue, and update the notification
pendingMessages.add(message);
updateMessageNotification();
}
}
public void updateMessageNotification() {
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
synchronized (pendingMessages) {
if (pendingMessages.size() == 0) {
mNM.cancel(MESSAGE_NOTIFICATION);
return;
}
String title = pendingMessages.get(0).getTitle();
Notification messageNotification = new Notification(org.commcare.dalvik.R.drawable.notification, title, System.currentTimeMillis());
messageNotification.number = pendingMessages.size();
// The PendingIntent to launch our activity if the user selects this notification
Intent i = new Intent(this, MessageActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
String additional = pendingMessages.size() > 1 ? Localization.get("notifications.prompt.more", new String[]{String.valueOf(pendingMessages.size() - 1)}) : "";
// Set the info for the views that show in the notification panel.
messageNotification.setLatestEventInfo(this, title, Localization.get("notifications.prompt.details", new String[]{additional}), contentIntent);
messageNotification.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, NotificationClearReceiver.class), 0);
//Send the notification.
mNM.notify(MESSAGE_NOTIFICATION, messageNotification);
}
}
public ArrayList<NotificationMessage> purgeNotifications() {
synchronized (pendingMessages) {
this.sendBroadcast(new Intent(ACTION_PURGE_NOTIFICATIONS));
ArrayList<NotificationMessage> cloned = (ArrayList<NotificationMessage>)pendingMessages.clone();
clearNotifications(null);
return cloned;
}
}
public void clearNotifications(String category) {
synchronized (pendingMessages) {
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Vector<NotificationMessage> toRemove = new Vector<>();
for (NotificationMessage message : pendingMessages) {
if (category == null || category.equals(message.getCategory())) {
toRemove.add(message);
}
}
for (NotificationMessage message : toRemove) {
pendingMessages.remove(message);
}
if (pendingMessages.size() == 0) {
mNM.cancel(MESSAGE_NOTIFICATION);
} else {
updateMessageNotification();
}
}
}
private boolean syncPending = false;
/**
* @return True if there is a sync action pending.
*/
private boolean getPendingSyncStatus() {
SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
long period = -1;
//Old flag, use a day by default
if ("true".equals(prefs.getString("cc-auto-update", "false"))) {
period = DateUtils.DAY_IN_MILLIS;
}
//new flag, read what it is.
String periodic = prefs.getString(CommCarePreferences.AUTO_SYNC_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER);
if (!periodic.equals(CommCarePreferences.FREQUENCY_NEVER)) {
period = DateUtils.DAY_IN_MILLIS * (periodic.equals(CommCarePreferences.FREQUENCY_DAILY) ? 1 : 7);
}
//If we didn't find a period, bail
if (period == -1) {
return false;
}
long lastRestore = prefs.getLong(CommCarePreferences.LAST_SYNC_ATTEMPT, 0);
return (isPending(lastRestore, period));
}
public synchronized boolean isSyncPending(boolean clearFlag) {
if (areAutomatedActionsInvalid()) {
return false;
}
//We only set this to true occasionally, but in theory it could be set to false
//from other factors, so turn it off if it is.
if (!getPendingSyncStatus()) {
syncPending = false;
}
if (!syncPending) {
return false;
}
if (clearFlag) {
syncPending = false;
}
return true;
}
public boolean isStorageAvailable() {
try {
File storageRoot = new File(getAndroidFsRoot());
return storageRoot.exists();
} catch (Exception e) {
return false;
}
}
/**
* Notify the application that something has occurred which has been
* logged, and which should cause log submission to occur as soon as
* possible.
*/
public void notifyLogsPending() {
doReportMaintenance(true);
}
public String getAndroidFsRoot() {
return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/files/";
}
public String getAndroidFsTemp() {
return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/temp/";
}
/**
* @return a path to a file location that can be used to store a file
* temporarily and will be cleaned up as part of CommCare's application
* lifecycle
*/
public String getTempFilePath() {
return getAndroidFsTemp() + PropertyUtils.genUUID();
}
public ArchiveFileRoot getArchiveFileRoot() {
return mArchiveFileRoot;
}
/**
* Message handler that pops-up notifications to the user via toast.
*/
private static class PopupHandler extends Handler {
/**
* Reference to the context used to show pop-ups (the parent class).
* Reference is weak to avoid memory leaks.
*/
private final WeakReference<CommCareApplication> mActivity;
/**
* @param activity Is the context used to pop-up the toast message.
*/
public PopupHandler(CommCareApplication activity) {
mActivity = new WeakReference<>(activity);
}
/**
* Pops up the message to the user by way of toast
*
* @param m Has a 'message' parcel storing pop-up message text
*/
@Override
public void handleMessage(Message m) {
NotificationMessage message = m.getData().getParcelable("message");
CommCareApplication activity = mActivity.get();
if (activity != null && message != null) {
Toast.makeText(activity,
Localization.get("notification.for.details.wrapper",
new String[]{message.getTitle()}),
Toast.LENGTH_LONG).show();
}
}
}
/**
* Used for manually linking to a session service during tests
*/
public void setTestingService(CommCareSessionService service) {
mIsBound = true;
mBoundService = service;
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
}
public void onServiceDisconnected(ComponentName className) {
}
};
}
}
|
package processing.app.syntax;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaDefaultInputMap;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RTextAreaEditorKit;
import processing.app.PreferencesData;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class SketchTextAreaDefaultInputMap extends RSyntaxTextAreaDefaultInputMap {
public SketchTextAreaDefaultInputMap() {
int defaultModifier = getDefaultModifier();
int alt = InputEvent.ALT_MASK;
int shift = InputEvent.SHIFT_MASK;
boolean isOSX = RTextArea.isOSX();
int moveByWordMod = isOSX ? alt : defaultModifier;
remove(KeyStroke.getKeyStroke(KeyEvent.VK_K, defaultModifier));
if (PreferencesData.getBoolean("editor.advanced")) {
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt), RTextAreaEditorKit.rtaLineDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt), RTextAreaEditorKit.rtaLineUpAction);
} else {
remove(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt));
remove(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt));
}
remove(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier));
put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, moveByWordMod), RTextAreaEditorKit.rtaDeletePrevWordAction);
if (isOSX) {
put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), SketchTextAreaEditorKit.rtaDeleteLineToCursorAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier), DefaultEditorKit.beginAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier), DefaultEditorKit.endAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier | shift), DefaultEditorKit.selectLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier | shift), DefaultEditorKit.selectLineAction);
remove(KeyStroke.getKeyStroke(KeyEvent.VK_J, defaultModifier));
put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultModifier), DefaultEditorKit.insertTabAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_CLOSE_BRACKET, defaultModifier), RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction);
}
put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultModifier), RSyntaxTextAreaEditorKit.rstaToggleCommentAction);
}
}
|
package io.reark.reark.pojo;
import android.support.annotation.NonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import io.reark.reark.utils.Log;
import io.reark.reark.utils.Preconditions;
/**
* Pojo base class that supports overwriting the fields with fields from
* another instance of the same class.
*/
public abstract class OverwritablePojo<T extends OverwritablePojo> {
private static final String TAG = OverwritablePojo.class.getSimpleName();
@NonNull
protected abstract Class<T> getTypeParameterClass();
@NonNull
@SuppressWarnings("unchecked")
public T overwrite(@NonNull T other) {
Preconditions.checkNotNull(other, "Can't overwrite with null value");
if (equals(other)) {
return (T) this;
}
for (Field field : getTypeParameterClass().getDeclaredFields()) {
final int modifiers = field.getModifiers();
if (hasIllegalAccessModifiers(modifiers)) {
continue;
} else if (!Modifier.isPublic(modifiers)) {
// We want to overwrite also protected and private fields. This allows field access
// for this instance of the field. The actual field of the class isn't modified.
field.setAccessible(true);
}
try {
if (!isEmpty(field, other)) {
field.set(this, field.get(other));
}
} catch (IllegalAccessException e) {
Log.e(TAG, "Failed set at " + field.getName(), e);
}
}
return (T) this;
}
protected boolean hasIllegalAccessModifiers(int modifiers) {
return Modifier.isFinal(modifiers)
|| Modifier.isStatic(modifiers)
|| Modifier.isTransient(modifiers);
}
protected boolean isEmpty(Field field, OverwritablePojo pojo) {
try {
Object value = field.get(pojo);
if (value == null) {
return true;
} else if (value instanceof String) {
return isEmpty((String) value);
} else if (value instanceof Boolean) {
return false;
} else if (value instanceof Long) {
return isEmpty((Long) value);
} else if (value instanceof Integer) {
return isEmpty((Integer) value);
} else if (value instanceof Double) {
return isEmpty((Double) value);
} else if (value instanceof Float) {
return isEmpty((Float) value);
} else if (value instanceof Short) {
return isEmpty((Short) value);
} else if (value instanceof Byte) {
return isEmpty((Byte) value);
} else if (value instanceof Character) {
return isEmpty((Character) value);
}
} catch (IllegalAccessException e) {
Log.e(TAG, "Failed get at " + field.getName(), e);
}
// Derived objects with more types should first check the new types, and then the base
// types with this method. Thus, we can assume reaching here is always an error.
Log.e(TAG, "Unknown field type: " + field.getName());
return true;
}
protected boolean isEmpty(String value) {
return false;
}
protected boolean isEmpty(long value) {
return false;
}
protected boolean isEmpty(int value) {
return false;
}
protected boolean isEmpty(double value) {
return false;
}
protected boolean isEmpty(float value) {
return false;
}
protected boolean isEmpty(short value) {
return false;
}
protected boolean isEmpty(byte value) {
return false;
}
protected boolean isEmpty(char value) {
return false;
}
@Override
public boolean equals(Object o) {
if (!getTypeParameterClass().isInstance(o)) {
return false;
}
return true;
}
}
|
package com.ptsmods.morecommands.gui.infohud;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.mojang.datafixers.util.Either;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.MoreCommandsArch;
import com.ptsmods.morecommands.MoreCommandsClient;
import com.ptsmods.morecommands.api.IMoreCommands;
import com.ptsmods.morecommands.api.util.compat.Compat;
import com.ptsmods.morecommands.api.util.text.LiteralTextBuilder;
import com.ptsmods.morecommands.gui.infohud.variables.*;
import com.ptsmods.morecommands.mixin.client.accessor.MixinMinecraftClientAccessor;
import com.ptsmods.morecommands.mixin.common.accessor.MixinEntityAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Pair;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.LightType;
import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.StreamSupport;
public class InfoHud extends DrawableHelper {
public static final InfoHud INSTANCE = new InfoHud();
private static final File file = MoreCommandsArch.getConfigDirectory().resolve("infoHud.txt").toFile();
private static final Pattern varPattern = Pattern.compile("var (?<key>[A-Za-z]*?) *?= *?(?<value>.*)");
private static final List<StackTraceElement> printedExceptions = new ArrayList<>();
private static final Map<String, Function<KeyContext, Object>> keys;
private static final Map<String, Variable<?>> variables = new HashMap<>();
private static final Map<String, Object> variableValues = new HashMap<>();
private static final MinecraftClient client = MinecraftClient.getInstance();
private static final List<String> lines = new ArrayList<>();
private static List<Pair<Integer, String>> parsedLines = Collections.emptyList();
private static HitResult result;
private static long lastRead = 0;
private static int width = 0, height = 0;
private static int decimals = 2;
static {
registerVariable(new IntVariable("xOffset", 2, (matrixStack, val) -> matrixStack.translate(val, 0, 0)));
registerVariable(new IntVariable("yOffset", 2, (matrixStack, val) -> matrixStack.translate(0, val, 0)));
registerVariable(new DoubleVariable("scale", 1.0, (matrixStack, val) -> matrixStack.scale(val.floatValue(), val.floatValue(), val.floatValue())));
registerVariable(new IntVariable("decimals", 2, (matrixStack, val) -> decimals = val).clamped(0, 7));
AtomicInteger backgroundOpacity = new AtomicInteger();
AtomicBoolean perLineBackground = new AtomicBoolean();
registerVariable(new IntVariable("backgroundOpacity", 0, ((matrixStack, val) -> backgroundOpacity.set(val))).clamped(0, 100));
registerVariable(new BooleanVariable("perLineBackground", false, (matrixStack, val) -> perLineBackground.set(val)));
registerVariable(new ColourVariable("backgroundColour", Color.BLACK, (matrixStack, val) -> {
if (backgroundOpacity.get() == 0) return;
int c = new Color(val.getRed(), val.getGreen(), val.getBlue(), (int) (backgroundOpacity.get() / 100f * 255)).getRGB();
if (!perLineBackground.get()) {
fill(matrixStack, -2, -2, width + 2, height, c);
return;
}
for (int i = 0; i < parsedLines.size(); i++)
fill(matrixStack, -2, i * 10 - 2, parsedLines.get(i).getLeft() + 2, (i + 1) * 10 - (i == parsedLines.size() - 1 ? 2 : 0), c);
}));
keys = registerKeys();
}
private static void registerVariable(Variable<?> variable) {
variables.put(variable.getName(), variable);
}
private static Map<String, Function<KeyContext, Object>> registerKeys() {
ImmutableMap.Builder<String, Function<KeyContext, Object>> keysBuilder = ImmutableMap.builder();
keysBuilder.put("DF", ctx -> MoreCommands.DF);
keysBuilder.put("SF", ctx -> MoreCommands.SF);
keysBuilder.put("playerName", ctx -> IMoreCommands.get().textToString(ctx.getPlayer().getName(), null, true));
keysBuilder.put("x", ctx -> MoreCommands.formatDouble(ctx.getPlayer().getPos().getX(), decimals));
keysBuilder.put("y", ctx -> MoreCommands.formatDouble(ctx.getPlayer().getPos().getY(), decimals));
keysBuilder.put("z", ctx -> MoreCommands.formatDouble(ctx.getPlayer().getPos().getZ(), decimals));
keysBuilder.put("chunkX", ctx -> (ctx.getPlayer().getBlockPos().getX()) >> 4);
keysBuilder.put("chunkY", ctx -> (ctx.getPlayer().getBlockPos().getY()) >> 4);
keysBuilder.put("chunkZ", ctx -> (ctx.getPlayer().getBlockPos().getZ()) >> 4);
keysBuilder.put("yaw", ctx -> MoreCommands.formatDouble(MathHelper.wrapDegrees(((MixinEntityAccessor) ctx.getPlayer()).getYaw_()), decimals));
keysBuilder.put("pitch", ctx -> MoreCommands.formatDouble(MathHelper.wrapDegrees(((MixinEntityAccessor) ctx.getPlayer()).getPitch_()), decimals));
keysBuilder.put("biome", ctx -> Objects.requireNonNull(Compat.get().getRegistry(ctx.getWorld().getRegistryManager(), Registry.BIOME_KEY)
.getId(Compat.get().getBiome(ctx.getWorld(), ctx.getPlayer().getBlockPos()))));
keysBuilder.put("difficulty", ctx -> ctx.getWorld().getLevelProperties().getDifficulty().name());
keysBuilder.put("blocksPerSec", ctx -> MoreCommands.formatDouble(MoreCommandsClient.getSpeed(), decimals) + " blocks/sec");
keysBuilder.put("avgSpeed", ctx -> MoreCommands.formatDouble(MoreCommandsClient.getAvgSpeed(), decimals) + " blocks/sec");
keysBuilder.put("toggleKey", ctx -> IMoreCommands.get().textToString(MoreCommandsClient.toggleInfoHudBinding.getBoundKeyLocalizedText(), null, true));
keysBuilder.put("configFile", ctx -> file.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
keysBuilder.put("facing", ctx -> MoreCommands.getLookDirection(MathHelper.wrapDegrees(((MixinEntityAccessor) ctx.getPlayer()).getYaw_()), ((MixinEntityAccessor) ctx.getPlayer()).getPitch_()));
keysBuilder.put("time", ctx -> MoreCommands.parseTime(ctx.getWorld().getTime() % 24000L, false));
keysBuilder.put("time12", ctx -> MoreCommands.parseTime(ctx.getWorld().getTime() % 24000L, true));
keysBuilder.put("UUID", ctx -> ctx.getPlayer().getUuidAsString());
keysBuilder.put("holding", ctx -> I18n.translate(ctx.getPlayer().getMainHandStack().getItem().getTranslationKey()));
keysBuilder.put("xp", ctx -> ctx.getPlayer().totalExperience);
keysBuilder.put("xpLevel", ctx -> ctx.getPlayer().experienceLevel);
keysBuilder.put("gamemode", ctx -> ctx.getInteractionManager().getCurrentGameMode().name());
keysBuilder.put("fps", ctx -> MixinMinecraftClientAccessor.getCurrentFps());
keysBuilder.put("blockLight", ctx -> ctx.getWorld().getChunkManager().getLightingProvider().get(LightType.BLOCK).getLightLevel(ctx.getPlayer().getBlockPos()));
keysBuilder.put("skyLight", ctx -> ctx.getWorld().getChunkManager().getLightingProvider().get(LightType.SKY).getLightLevel(ctx.getPlayer().getBlockPos()));
keysBuilder.put("lookingAtX", ctx -> ctx.getHit().map(bHit -> bHit.getBlockPos().getX(), eHit -> eHit.getPos().getX()));
keysBuilder.put("lookingAtY", ctx -> ctx.getHit().map(bHit -> bHit.getBlockPos().getY(), eHit -> eHit.getPos().getY()));
keysBuilder.put("lookingAtZ", ctx -> ctx.getHit().map(bHit -> bHit.getBlockPos().getZ(), eHit -> eHit.getPos().getZ()));
keysBuilder.put("lookingAt", ctx -> IMoreCommands.get().textToString(ctx.getHit().map(bHit -> MoreObjects.firstNonNull(ctx.getWorld()
.getBlockState(bHit.getBlockPos()).getBlock().getPickStack(ctx.getWorld(), bHit.getBlockPos(), ctx.getWorld().getBlockState(bHit.getBlockPos())), ItemStack.EMPTY).getName(),
eHit -> eHit.getEntity().getName()), null, true));
keysBuilder.put("lookingAtSide", ctx -> ctx.getHit().map(bHit -> bHit.getSide().getName(), eHit -> "none"));
keysBuilder.put("language", ctx -> ctx.getClient().options.language);
keysBuilder.put("lookingVecX", ctx -> result.getPos().getX());
keysBuilder.put("lookingVecY", ctx -> result.getPos().getY());
keysBuilder.put("lookingVecZ", ctx -> result.getPos().getZ());
keysBuilder.put("entities", ctx -> StreamSupport.stream(ctx.getWorld().getEntities().spliterator(), false).count());
return keysBuilder.buildOrThrow();
}
public void render(MatrixStack matrices) {
matrices.push();
result = MoreCommands.getRayTraceTarget(client.player, 160f, false, true);
if (System.currentTimeMillis() - lastRead >= 500) try {
if (file.lastModified() > lastRead) loadLines();
lastRead = System.currentTimeMillis();
} catch (IOException e) {
MoreCommands.LOG.catching(e);
setupDefaultLines();
}
parsedLines = parseLines();
width = parsedLines.stream()
.mapToInt(Pair::getLeft)
.max()
.orElse(0);
height = parsedLines.size() * 10;
variables.forEach((name, var) -> {
if (variableValues.containsKey(name))
var.apply(matrices, var.upcast(variableValues.get(name)));
else var.applyDefault(matrices);
});
int row = 0;
for (Pair<Integer, String> line : parsedLines)
drawString(matrices, line.getRight(), row++);
matrices.pop();
}
private void drawString(MatrixStack matrices, String s, int row) {
client.textRenderer.drawWithShadow(matrices, LiteralTextBuilder.literal(s), 0, row * 10, 0xFFFFFF);
}
private void setupDefaultLines() {
lines.clear();
lines.add("
lines.add("{DF}Player: {SF}{playerName}");
lines.add("{DF}FPS: {SF}{fps}");
lines.add("{DF}X: {SF}{x}");
lines.add("{DF}Y: {SF}{y}");
lines.add("{DF}Z: {SF}{z}");
lines.add("{DF}Pitch: {SF}{pitch}");
lines.add("{DF}Yaw: {SF}{yaw}");
lines.add("{DF}Facing: {SF}{facing}");
lines.add("{DF}Biome: {SF}{biome}");
lines.add("{DF}Speed: {SF}{avgSpeed}");
try {
saveLines();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void loadLines() throws IOException {
if (!file.exists()) {
setupDefaultLines();
} else {
lines.clear();
lines.addAll(Files.readAllLines(file.toPath()));
}
if (lines.isEmpty()) setupDefaultLines();
}
private void saveLines() throws FileNotFoundException {
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8))) {
for (String line : lines)
writer.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<Pair<Integer, String>> parseLines() {
variableValues.clear();
List<Pair<Integer, String>> output = new ArrayList<>();
for (String line : lines) {
Matcher varMatcher = varPattern.matcher(line);
if (varMatcher.matches()) {
String key = varMatcher.group("key");
if (!variables.containsKey(key)) continue;
try {
variableValues.put(key, variables.get(key).fromString(varMatcher.group("value").trim()));
} catch (Exception ignored) {}
} else {
StringBuilder s = new StringBuilder();
int index = -1;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '{') index = i;
else if (line.charAt(i) == '}' && index >= 0) {
try {
s.append(translate(line.substring(index + 1, i)));
index = -1;
} catch (PatternSyntaxException e) {
s.replace(0, s.length(), "Error parsing line, please make sure all regex characters are escaped.");
break;
}
} else if (index == -1) s.append(line.charAt(i));
}
String parsedLine = s.toString();
line = Arrays.stream(s.toString().split("//")).findFirst().orElse(""); // handling comments in the config, this should be exactly the same as how
if (parsedLine.equals("") || !line.equals("")) output.add(new Pair<>(client.textRenderer.getWidth(line), line));
// normal, non-multiline Java comments work.
}
}
return output;
}
private String translate(String key) {
String output = "{" + key + "}";
if (!keys.containsKey(key)) return output;
BlockHitResult bHit = result instanceof BlockHitResult ? (BlockHitResult) result : null;
EntityHitResult eHit = result instanceof EntityHitResult ? (EntityHitResult) result : null;
MinecraftClient mc = MinecraftClient.getInstance();
if (mc.player == null || mc.world == null || bHit == null && eHit == null) return output;
KeyContext ctx = new KeyContext(mc, bHit != null ? Either.left(bHit) : Either.right(eHit));
try {
output = String.valueOf(keys.get(key).apply(ctx));
} catch (Exception e) {
if (e.getStackTrace().length != 0) {
StackTraceElement element = e.getStackTrace()[0];
if (!printedExceptions.contains(element)) {
MoreCommands.LOG.error("An error occurred while translating key " + key, e);
printedExceptions.add(element);
}
}
output = "ERROR";
}
return output;
}
}
|
// BioFormatsItkBridge.java
package loci.formats.tools;
import java.io.IOException;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.ImageReader;
public class BioFormatsItkBridge {
private static ImageReader reader;
public BioFormatsItkBridge() {
reader = new ImageReader();
}
public static boolean canReadFile(String id) {
System.out.println("In BFITKBridge\nid: " + id);
boolean h = false;
try {
h = reader.isThisType(id);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("h is: " + h);
return h;
}
public static int[] readImageInfo(String id) {
try {
reader.setId(id);
} catch (FormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ORDERING: 0 little, 1 seriesCount, 2 pixelType, 3 bpp, 4 itkComponentType, 5 sizeX,
// 6 sizeY, 7 sizeZ, 8 sizeT, 9 sizeC, 10 effSizeC, 11 rgbChannelCount, 12 imageCount
int[] returnValues = new int[13];
// return this and use SetByteOrderToLittleEndian or SetByteOrderToBigEndian in C++ land
boolean little = reader.isLittleEndian();
if(little) {
returnValues[0] = 1;
}
else {
returnValues[0] = 0;
}
returnValues[1] = reader.getSeriesCount();
// return bpp and set an IOComponent based on it
int pixelType = reader.getPixelType();
returnValues[2] = pixelType;
returnValues[3] = FormatTools.getBytesPerPixel(returnValues[2]);
// 0 UCHAR, 1 CHAR, 2 USHORT, 3 SHORT, 4 UINT, 5 INT, 6 FLOAT, 7 DOUBLE, 8 UNKNOWN
if (pixelType == FormatTools.UINT8)
returnValues[4] = 0;
else if (pixelType == FormatTools.INT8)
returnValues[4] = 1;
else if (pixelType == FormatTools.UINT16)
returnValues[4] = 2;
else if (pixelType == FormatTools.INT16)
returnValues[4] = 3;
else if (pixelType == FormatTools.UINT32)
returnValues[4] = 4;
else if (pixelType == FormatTools.INT32)
returnValues[4] = 5;
else if (pixelType == FormatTools.FLOAT)
returnValues[4] = 6;
else if (pixelType == FormatTools.DOUBLE)
returnValues[4] = 7;
else
returnValues[4] = 8;
// return these
returnValues[5] = reader.getSizeX();
returnValues[6] = reader.getSizeY();
returnValues[7] = reader.getSizeZ();
returnValues[8] = reader.getSizeT();
returnValues[9] = reader.getSizeC();
returnValues[10] = reader.getEffectiveSizeC();
returnValues[11] = reader.getRGBChannelCount();
returnValues[12] = reader.getImageCount();
return returnValues;
}
public static void readPlane(int p) {
}
public void quit() {
System.exit(0);
}
}
|
// JAIIIOServiceTest.java
package loci.formats.utests;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.codec.JPEG2000CodecOptions;
import loci.formats.services.JAIIIOService;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class JAIIIOServiceTest {
private static final int SIZE_X = 64;
private static final int SIZE_Y = 96;
//Code block size minimum is 4x4
private static final int[] CODE_BLOCK = new int[] { 4, 4 };
private static final int IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
private JAIIIOService service;
@BeforeMethod
public void setUp() throws DependencyException {
ServiceFactory sf = new ServiceFactory();
service = sf.getInstance(JAIIIOService.class);
}
private ByteArrayOutputStream writeImage(JPEG2000CodecOptions options)
throws IOException, ServiceException {
BufferedImage image = new BufferedImage(SIZE_X, SIZE_Y, IMAGE_TYPE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
service.writeImage(stream, image, options);
return stream;
}
private ByteArrayOutputStream assertWriteImageLossy()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.lossless = false;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
ByteArrayOutputStream stream = writeImage(options);
assertTrue(stream.size() > 0);
return stream;
}
private ByteArrayOutputStream assertWriteImageLossless()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.lossless = true;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
ByteArrayOutputStream stream = writeImage(options);
assertTrue(stream.size() > 0);
return stream;
}
@Test
public void testWriteTiledImageLossy()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.lossless = false;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
options.tileWidth = 32;
options.tileHeight = 32;
options.tileGridXOffset = 0;
options.tileGridYOffset = 0;
ByteArrayOutputStream stream = writeImage(options);
assertTrue(stream.size() > 0);
}
@Test
public void testWriteTiledImageLossless()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.lossless = true;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
options.tileWidth = 32;
options.tileHeight = 32;
options.tileGridXOffset = 0;
options.tileGridYOffset = 0;
ByteArrayOutputStream stream = writeImage(options);
assertTrue(stream.size() > 0);
}
@Test
public void testReadImageLossy() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossy();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
BufferedImage image = service.readImage(inputStream);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
@Test
public void testReadImageLossless() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossless();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
BufferedImage image = service.readImage(inputStream);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
@Test
public void testReadRasterLossy() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossy();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
Raster image = service.readRaster(inputStream);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
@Test
public void testReadRasterLossless() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossless();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
Raster image = service.readRaster(inputStream);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
@Test
public void testReadImageLevel0Lossy() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossy();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.resolution = 0;
BufferedImage image = service.readImage(inputStream, options);
assertNotNull(image);
assertEquals(2, image.getWidth());
assertEquals(3, image.getHeight());
}
@Test
public void testReadImageLevel0Lossless() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossless();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.resolution = 0;
BufferedImage image = service.readImage(inputStream, options);
assertNotNull(image);
assertEquals(2, image.getWidth());
assertEquals(3, image.getHeight());
}
@Test
public void testReadRasterLevel0Lossy() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossy();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.resolution = 0;
Raster image = service.readRaster(inputStream, options);
assertNotNull(image);
assertEquals(2, image.getWidth());
assertEquals(3, image.getHeight());
}
@Test
public void testReadRasterLevel0Lossless() throws IOException, ServiceException {
ByteArrayOutputStream outputStream = assertWriteImageLossless();
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.resolution = 0;
Raster image = service.readRaster(inputStream, options);
assertNotNull(image);
assertEquals(2, image.getWidth());
assertEquals(3, image.getHeight());
}
@Test
public void testNumDecompositionLevelsLossy()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.numDecompositionLevels = 2;
options.resolution = 2;
options.lossless = false;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
ByteArrayOutputStream outputStream = writeImage(options);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
BufferedImage image = service.readImage(inputStream, options);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
@Test
public void testNumDecompositionLevelsLossless()
throws IOException, ServiceException {
JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions();
options.numDecompositionLevels = 2;
options.resolution = 2;
options.lossless = true;
options.codeBlockSize = CODE_BLOCK;
options.quality = 1.0f;
ByteArrayOutputStream outputStream = writeImage(options);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
BufferedImage image = service.readImage(inputStream, options);
assertNotNull(image);
assertEquals(SIZE_X, image.getWidth());
assertEquals(SIZE_Y, image.getHeight());
}
}
|
package com.yahoo.vespa.model;
import com.yahoo.config.*;
import com.yahoo.config.codegen.CNode;
import com.yahoo.config.codegen.ConfigGenerator;
import com.yahoo.config.codegen.InnerCNode;
import com.yahoo.config.codegen.LeafCNode;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.buildergen.ConfigDefinition;
import com.yahoo.yolean.Exceptions;
import com.yahoo.vespa.config.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* <p>
* This class is capable of resolving config from a config model for a given request. It will handle
* incompatibilities of the def version in the request and the version of the config classes the model
* is using.
* </p>
* <p>
* This class is agnostic of transport protocol and server implementation.
* </p>
* <p>
* Thread safe.
* </p>
*
* @author vegardh
* @since 5.1.5
*/
// TODO This functionality should be on VespaModel itself, but we don't have a way right now to apply a config override to a ConfigInstance.Builder
class InstanceResolver {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InstanceResolver.class.getName());
/**
* Resolves this config key into a correctly typed ConfigInstance using the given config builder.
* FIXME: Make private once config overrides are deprecated.?
*
* @param key a ConfigKey
* @param builder a ConfigBuilder to create the instance from.
* @param targetDef the def to use
* @return the config instance or null of no producer for this found in model
*/
@SuppressWarnings("unchecked")
static ConfigInstance resolveToInstance(ConfigKey<?> key, ConfigBuilder builder, InnerCNode targetDef) {
try {
if (targetDef != null) applyDef(builder, targetDef);
Class<?> clazz = builder.getClass().getEnclosingClass();
if (!(ConfigInstance.class.isAssignableFrom(clazz))) {
throw new ConfigurationRuntimeException("Cannot produce config for the name '" + key.getName() + ", as "
+ clazz.getName() + " is not a ConfigInstance.");
}
Class<? extends ConfigInstance> configClass = (Class<? extends ConfigInstance>)clazz;
Constructor<? extends ConfigInstance> constructor = configClass.getDeclaredConstructor(builder.getClass(), boolean.class);
constructor.setAccessible(true);
return constructor.newInstance(builder, /*throwIfUninitialized*/ false);
} catch (Exception e) {
throw new ConfigurationRuntimeException(e);
}
}
/**
* Resolves this config key into a correctly typed ConfigBuilder using the given config model.
* FIXME: Make private once config overrides are deprecated.?
*
* @return the config builder or null if no producer for this found in model
*/
static ConfigBuilder resolveToBuilder(ConfigKey<?> key, VespaModel model, ConfigDefinition targetDef) {
if (model == null) return null;
ConfigDefinitionKey defKey = new ConfigDefinitionKey(key);
ConfigInstance.Builder builder = model.createBuilder(defKey, targetDef);
model.getConfig(builder, key.getConfigId());
return builder;
}
/**
* If some fields on the builder are null now, set them from the def. Do recursively.
* <p>
* If the targetDef has some schema incompatibilities, they are not handled here
* (except logging in some cases), but in ConfigInstance.serialize().
*
* @param builder a {@link com.yahoo.config.ConfigBuilder}
* @param targetDef a config definition
* @throws Exception if applying values form config definitions fails
*/
static void applyDef(ConfigBuilder builder, InnerCNode targetDef) throws Exception {
for (Map.Entry<String, CNode> e: targetDef.children().entrySet()) {
CNode node = e.getValue();
if (node instanceof LeafCNode) {
setLeafValueIfUnset(targetDef, builder, (LeafCNode)node);
} else if (node instanceof InnerCNode) {
// Is there a private field on the builder that matches this inner node in the def?
if (hasField(builder.getClass(), node.getName())) {
Field innerField = builder.getClass().getDeclaredField(node.getName());
innerField.setAccessible(true);
Object innerFieldVal = innerField.get(builder);
if (innerFieldVal instanceof List) {
// inner array? Check that list elems are ConfigBuilder
List<?> innerList = (List<?>) innerFieldVal;
for (Object b : innerList) {
if (b instanceof ConfigBuilder) {
applyDef((ConfigBuilder) b, (InnerCNode) node);
}
}
} else if (innerFieldVal instanceof ConfigBuilder) {
// Struct perhaps
applyDef((ConfigBuilder) innerFieldVal, (InnerCNode) node);
} else {
// Likely a config value mismatch. That is handled in ConfigInstance.serialize() (error message, omit from response.)
}
}
}
}
}
private static boolean hasField(Class<?> aClass, String name) {
for (Field field : aClass.getDeclaredFields()) {
if (name.equals(field.getName())) {
return true;
}
}
return false;
}
private static void setLeafValueIfUnset(InnerCNode targetDef, Object builder, LeafCNode node) throws Exception {
if (hasField(builder.getClass(), node.getName())) {
Field field = builder.getClass().getDeclaredField(node.getName());
field.setAccessible(true);
Object val = field.get(builder);
if (val==null) {
// Not set on builder, if the leaf node has a default value, try the private setter that takes String
try {
if (node.getDefaultValue()!=null) {
Method setter = builder.getClass().getDeclaredMethod(node.getName(), String.class);
setter.setAccessible(true);
setter.invoke(builder, node.getDefaultValue().getValue());
}
} catch (Exception e) {
log.severe("For config '"+targetDef.getFullName()+"': Unable to apply the default value for field '"+node.getName()+
"' to config Builder (where it wasn't set): "+
Exceptions.toMessageString(e));
}
}
}
}
static String packageName(ConfigDefinitionKey cKey) {
String prefix = "com.yahoo.";
return prefix + (cKey.getNamespace().isEmpty() ? CNode.DEFAULT_NAMESPACE : cKey.getNamespace());
}
}
|
package forklift.connectors;
import forklift.consumer.ForkliftConsumerI;
import forklift.consumer.KafkaTopicConsumer;
import forklift.controller.KafkaController;
import forklift.message.MessageStream;
import forklift.producers.ForkliftProducerI;
import forklift.producers.KafkaForkliftProducer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* Manages both consuming and producing events on the kafka message broker.
*/
public class KafkaConnector implements ForkliftConnectorI {
private static final Logger log = LoggerFactory.getLogger(KafkaConnector.class);
private final String kafkaHosts;
private final String schemaRegistries;
private final String groupId;
private KafkaProducer<?, ?> kafkaProducer;
private MessageStream messageStream = new MessageStream();
private KafkaController controller;
public KafkaConnector(String kafkaHosts, String schemaRegistries, String groupId) {
this.kafkaHosts = kafkaHosts;
this.schemaRegistries = schemaRegistries;
this.groupId = groupId;
}
@Override
public void start() throws ConnectorException {
//We do nothing here. Consumer and producer are created when needed
}
private KafkaProducer createKafkaProducer() {
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHosts);
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
io.confluent.kafka.serializers.KafkaAvroSerializer.class);
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
io.confluent.kafka.serializers.KafkaAvroSerializer.class);
//schema.registry.url is a comma separated list of urls
producerProperties.put("schema.registry.url", schemaRegistries);
return new KafkaProducer(producerProperties);
}
private KafkaController createController() {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHosts);
props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroDeserializer.class);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 200);
props.put("schema.registry.url", schemaRegistries);
props.put("specific.avro.reader", false);
KafkaConsumer<?, ?> kafkaConsumer = new KafkaConsumer(props);
return new KafkaController(kafkaConsumer, messageStream);
}
@Override
public synchronized void stop() throws ConnectorException {
try {
if (controller != null) {
this.controller.stop(2000, TimeUnit.MILLISECONDS);
this.controller = null;
}
} catch (InterruptedException e) {
log.error("KafkaConnector interrupted while stopping");
}
if (kafkaProducer != null) {
this.kafkaProducer.close();
this.kafkaProducer = null;
}
}
@Override
public ForkliftConsumerI getQueue(String name) throws ConnectorException {
return this.getTopic(name);
}
@Override
public synchronized ForkliftConsumerI getTopic(String name) throws ConnectorException {
if (this.controller == null || !this.controller.isRunning()) {
this.controller = createController();
this.controller.start();
}
return new KafkaTopicConsumer(name, controller);
}
@Override
public ForkliftProducerI getQueueProducer(String name) {
return this.getTopicProducer(name);
}
@Override
public synchronized ForkliftProducerI getTopicProducer(String name) {
if (this.kafkaProducer == null) {
this.kafkaProducer = createKafkaProducer();
}
return new KafkaForkliftProducer(name, this.kafkaProducer);
}
@Override
public boolean supportsResponse() {
return true;
}
@Override
public boolean supportsTopic() {
return true;
}
@Override
public boolean supportsQueue() {
return true;
}
}
|
package org.exist.util;
import com.evolvedbinary.j8fu.tuple.Tuple2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.backup.SystemExport;
import org.exist.collections.CollectionCache;
import org.exist.repo.Deployment;
import org.exist.resolver.ResolverFactory;
import org.exist.start.Main;
import org.exist.storage.lock.LockManager;
import org.exist.storage.lock.LockTable;
import org.exist.xquery.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.exist.Indexer;
import org.exist.indexing.IndexManager;
import org.exist.dom.memtree.SAXAdapter;
import org.exist.scheduler.JobConfig;
import org.exist.scheduler.JobException;
import org.exist.storage.BrokerFactory;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.IndexSpec;
import org.exist.storage.NativeBroker;
import org.exist.storage.NativeValueIndex;
import org.exist.storage.XQueryPool;
import org.exist.storage.journal.Journal;
import org.exist.storage.serializers.CustomMatchListenerFactory;
import org.exist.storage.serializers.Serializer;
import org.exist.validation.GrammarPool;
import org.exist.xmldb.DatabaseImpl;
import org.exist.xslt.TransformerFactoryAllocator;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.exist.Namespaces;
import org.exist.scheduler.JobType;
import org.xmlresolver.Resolver;
import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple;
import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING;
public class Configuration implements ErrorHandler
{
private final static Logger LOG = LogManager.getLogger(Configuration.class); //Logger
protected Optional<Path> configFilePath = Optional.empty();
protected Optional<Path> existHome = Optional.empty();
protected DocumentBuilder builder = null;
protected HashMap<String, Object> config = new HashMap<>(); //Configuration
private static final String XQUERY_CONFIGURATION_ELEMENT_NAME = "xquery";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME = "builtin-modules";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME = "module";
public final static String BINARY_CACHE_CLASS_PROPERTY = "binary.cache.class";
public Configuration() throws DatabaseConfigurationException {
this(DatabaseImpl.CONF_XML, Optional.empty());
}
public Configuration(final String configFilename) throws DatabaseConfigurationException {
this(configFilename, Optional.empty());
}
public Configuration(String configFilename, Optional<Path> existHomeDirname) throws DatabaseConfigurationException {
InputStream is = null;
try {
if(configFilename == null) {
// Default file name
configFilename = DatabaseImpl.CONF_XML;
}
// firstly, try to read the configuration from a file within the
// classpath
try {
is = Configuration.class.getClassLoader().getResourceAsStream(configFilename);
if(is != null) {
LOG.info("Reading configuration from classloader");
configFilePath = Optional.of(Paths.get(Configuration.class.getClassLoader().getResource(configFilename).toURI()));
}
} catch(final Exception e) {
// EB: ignore and go forward, e.g. in case there is an absolute
// file name for configFileName
LOG.debug( e );
}
// otherwise, secondly try to read configuration from file. Guess the
// location if necessary
if(is == null) {
existHome = existHomeDirname.map(Optional::of).orElse(ConfigurationHelper.getExistHome(configFilename));
if(!existHome.isPresent()) {
// EB: try to create existHome based on location of config file
// when config file points to absolute file location
final Path absoluteConfigFile = Paths.get(configFilename);
if(absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) {
existHome = Optional.of(absoluteConfigFile.getParent());
configFilename = FileUtils.fileName(absoluteConfigFile);
}
}
Path configFile = Paths.get(configFilename);
if(!configFile.isAbsolute() && existHome.isPresent()) {
// try the passed or constructed existHome first
configFile = existHome.get().resolve(configFilename);
if (!Files.exists(configFile)) {
configFile = existHome.get().resolve(Main.CONFIG_DIR_NAME).resolve(configFilename);
}
}
//if( configFile == null ) {
// configFile = ConfigurationHelper.lookup( configFilename );
if(!Files.exists(configFile) || !Files.isReadable(configFile)) {
throw new DatabaseConfigurationException("Unable to read configuration file at " + configFile);
}
configFilePath = Optional.of(configFile.toAbsolutePath());
is = Files.newInputStream(configFile);
}
LOG.info("Reading configuration from file {}", configFilePath.map(Path::toString).orElse("Unknown"));
// set dbHome to parent of the conf file found, to resolve relative
// path from conf file
existHomeDirname = configFilePath.map(Path::getParent);
// initialize xml parser
// we use eXist's in-memory DOM implementation to work
// around a bug in Xerces
final SAXParserFactory factory = ExistSAXParserFactory.getSAXParserFactory();
factory.setNamespaceAware(true);
final InputSource src = new InputSource(is);
final SAXParser parser = factory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.setFeature(FEATURE_SECURE_PROCESSING, true);
final SAXAdapter adapter = new SAXAdapter((Expression) null);
reader.setContentHandler(adapter);
reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
reader.parse(src);
final Document doc = adapter.getDocument();
//indexer settings
final NodeList indexers = doc.getElementsByTagName(Indexer.CONFIGURATION_ELEMENT_NAME);
if(indexers.getLength() > 0) {
configureIndexer( existHomeDirname, doc, (Element)indexers.item( 0 ) );
}
//scheduler settings
final NodeList schedulers = doc.getElementsByTagName(JobConfig.CONFIGURATION_ELEMENT_NAME);
if(schedulers.getLength() > 0) {
configureScheduler((Element)schedulers.item(0));
}
//db connection settings
final NodeList dbcon = doc.getElementsByTagName(BrokerPool.CONFIGURATION_CONNECTION_ELEMENT_NAME);
if(dbcon.getLength() > 0) {
configureBackend(existHomeDirname, (Element)dbcon.item(0));
}
// lock-table settings
final NodeList lockManager = doc.getElementsByTagName("lock-manager");
if(lockManager.getLength() > 0) {
configureLockManager((Element) lockManager.item(0));
}
// repository settings
final NodeList repository = doc.getElementsByTagName("repository");
if(repository.getLength() > 0) {
configureRepository((Element) repository.item(0));
}
// binary manager settings
final NodeList binaryManager = doc.getElementsByTagName("binary-manager");
if(binaryManager.getLength() > 0) {
configureBinaryManager((Element)binaryManager.item(0));
}
//transformer settings
final NodeList transformers = doc.getElementsByTagName(TransformerFactoryAllocator.CONFIGURATION_ELEMENT_NAME);
if( transformers.getLength() > 0 ) {
configureTransformer((Element)transformers.item(0));
}
//parser settings
final NodeList parsers = doc.getElementsByTagName(HtmlToXmlParser.PARSER_ELEMENT_NAME);
if(parsers.getLength() > 0) {
configureParser((Element)parsers.item(0));
}
//serializer settings
final NodeList serializers = doc.getElementsByTagName(Serializer.CONFIGURATION_ELEMENT_NAME);
if(serializers.getLength() > 0) {
configureSerializer((Element)serializers.item(0));
}
//XUpdate settings
final NodeList xupdates = doc.getElementsByTagName(DBBroker.CONFIGURATION_ELEMENT_NAME);
if(xupdates.getLength() > 0) {
configureXUpdate((Element)xupdates.item(0));
}
//XQuery settings
final NodeList xquery = doc.getElementsByTagName(XQUERY_CONFIGURATION_ELEMENT_NAME);
if(xquery.getLength() > 0) {
configureXQuery((Element)xquery.item(0));
}
//Validation
final NodeList validations = doc.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_ELEMENT_NAME);
if(validations.getLength() > 0) {
configureValidation(existHomeDirname, (Element)validations.item(0));
}
}
catch(final SAXException | IOException | ParserConfigurationException e) {
LOG.error("error while reading config file: {}", configFilename, e);
throw new DatabaseConfigurationException(e.getMessage(), e);
} finally {
if(is != null) {
try {
is.close();
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
}
private void configureLockManager(final Element lockManager) throws DatabaseConfigurationException {
final boolean upgradeCheck = parseBoolean(getConfigAttributeValue(lockManager, "upgrade-check"), false);
final boolean warnWaitOnReadForWrite = parseBoolean(getConfigAttributeValue(lockManager, "warn-wait-on-read-for-write"), false);
final boolean pathsMultiWriter = parseBoolean(getConfigAttributeValue(lockManager, "paths-multi-writer"), false);
config.put(LockManager.CONFIGURATION_UPGRADE_CHECK, upgradeCheck);
config.put(LockManager.CONFIGURATION_WARN_WAIT_ON_READ_FOR_WRITE, warnWaitOnReadForWrite);
config.put(LockManager.CONFIGURATION_PATHS_MULTI_WRITER, pathsMultiWriter);
final NodeList nlLockTable = lockManager.getElementsByTagName("lock-table");
if(nlLockTable.getLength() > 0) {
final Element lockTable = (Element)nlLockTable.item(0);
final boolean lockTableDisabled = parseBoolean(getConfigAttributeValue(lockTable, "disabled"), false);
final int lockTableTraceStackDepth = parseInt(getConfigAttributeValue(lockTable, "trace-stack-depth"), 0);
config.put(LockTable.CONFIGURATION_DISABLED, lockTableDisabled);
config.put(LockTable.CONFIGURATION_TRACE_STACK_DEPTH, lockTableTraceStackDepth);
}
final NodeList nlDocument = lockManager.getElementsByTagName("document");
if(nlDocument.getLength() > 0) {
final Element document = (Element)nlDocument.item(0);
final boolean documentUsePathLocks = parseBoolean(getConfigAttributeValue(document, "use-path-locks"), false);
config.put(LockManager.CONFIGURATION_PATH_LOCKS_FOR_DOCUMENTS, documentUsePathLocks);
}
}
private void configureRepository(Element element) {
String root = getConfigAttributeValue(element, "root");
if (root != null && !root.isEmpty()) {
if (!root.endsWith("/"))
{root += "/";}
config.put(Deployment.PROPERTY_APP_ROOT, root);
}
}
private void configureBinaryManager(Element binaryManager) throws DatabaseConfigurationException {
final NodeList nlCache = binaryManager.getElementsByTagName("cache");
if(nlCache.getLength() > 0) {
final Element cache = (Element)nlCache.item(0);
final String binaryCacheClass = getConfigAttributeValue(cache, "class");
config.put(BINARY_CACHE_CLASS_PROPERTY, binaryCacheClass);
LOG.debug(BINARY_CACHE_CLASS_PROPERTY + ": {}", config.get(BINARY_CACHE_CLASS_PROPERTY));
}
}
private void configureXQuery( Element xquery ) throws DatabaseConfigurationException
{
//java binding
final String javabinding = getConfigAttributeValue( xquery, FunctionFactory.ENABLE_JAVA_BINDING_ATTRIBUTE );
if( javabinding != null ) {
config.put( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING, javabinding );
LOG.debug(FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING + ": {}", config.get(FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING));
}
final String disableDeprecated = getConfigAttributeValue( xquery, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_ATTRIBUTE );
config.put( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, Configuration.parseBoolean( disableDeprecated, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_BY_DEFAULT ) );
LOG.debug(FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS + ": {}", config.get(FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS));
final String optimize = getConfigAttributeValue( xquery, XQueryContext.ENABLE_QUERY_REWRITING_ATTRIBUTE );
if( ( optimize != null ) && (!optimize.isEmpty()) ) {
config.put( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING, optimize );
LOG.debug(XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING + ": {}", config.get(XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING));
}
final String enforceIndexUse = getConfigAttributeValue( xquery, XQueryContext.ENFORCE_INDEX_USE_ATTRIBUTE );
if (enforceIndexUse != null) {
config.put( XQueryContext.PROPERTY_ENFORCE_INDEX_USE, enforceIndexUse );
}
final String backwardCompatible = getConfigAttributeValue( xquery, XQueryContext.XQUERY_BACKWARD_COMPATIBLE_ATTRIBUTE );
if( ( backwardCompatible != null ) && (!backwardCompatible.isEmpty()) ) {
config.put( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE, backwardCompatible );
LOG.debug(XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE + ": {}", config.get(XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE));
}
final String raiseErrorOnFailedRetrieval = getConfigAttributeValue( xquery, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_ATTRIBUTE );
config.put( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, Configuration.parseBoolean( raiseErrorOnFailedRetrieval, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_DEFAULT ) );
LOG.debug(XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL + ": {}", config.get(XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL));
final String trace = getConfigAttributeValue( xquery, PerformanceStats.CONFIG_ATTR_TRACE );
config.put( PerformanceStats.CONFIG_PROPERTY_TRACE, trace );
// built-in-modules
final Map<String, Class<?>> classMap = new HashMap<>();
final Map<String, String> knownMappings = new HashMap<>();
final Map<String, Map<String, List<? extends Object>>> moduleParameters = new HashMap<>();
loadModuleClasses(xquery, classMap, knownMappings, moduleParameters);
config.put( XQueryContext.PROPERTY_BUILT_IN_MODULES, classMap);
config.put( XQueryContext.PROPERTY_STATIC_MODULE_MAP, knownMappings);
config.put( XQueryContext.PROPERTY_MODULE_PARAMETERS, moduleParameters);
}
/**
* Read list of built-in modules from the configuration. This method will only make sure
* that the specified module class exists and is a subclass of {@link org.exist.xquery.Module}.
*
* @param xquery configuration root
* @param modulesClassMap map containing all classes of modules
* @param modulesSourceMap map containing all source uris to external resources
*
* @throws DatabaseConfigurationException
*/
private void loadModuleClasses( Element xquery, Map<String, Class<?>> modulesClassMap, Map<String, String> modulesSourceMap, Map<String, Map<String, List<? extends Object>>> moduleParameters) throws DatabaseConfigurationException {
// add the standard function module
modulesClassMap.put(Namespaces.XPATH_FUNCTIONS_NS, org.exist.xquery.functions.fn.FnModule.class);
// add other modules specified in configuration
final NodeList builtins = xquery.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME);
// search under <builtin-modules>
if(builtins.getLength() > 0) {
Element elem = (Element)builtins.item(0);
final NodeList modules = elem.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME);
if(modules.getLength() > 0) {
// iterate over all <module src= uri= class=> entries
for(int i = 0; i < modules.getLength(); i++) {
// Get element.
elem = (Element)modules.item(i);
// Get attributes uri class and src
final String uri = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_URI_ATTRIBUTE);
final String clazz = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_CLASS_ATTRIBUTE);
final String source = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_SOURCE_ATTRIBUTE);
// uri attribute is the identifier and is always required
if(uri == null) {
throw(new DatabaseConfigurationException("element 'module' requires an attribute 'uri'" ));
}
// either class or source attribute must be present
if((clazz == null) && (source == null)) {
throw(new DatabaseConfigurationException("element 'module' requires either an attribute " + "'class' or 'src'" ));
}
if(source != null) {
// Store src attribute info
modulesSourceMap.put(uri, source);
if(LOG.isDebugEnabled()) {
LOG.debug("Registered mapping for module '{}' to '{}'", uri, source);
}
} else {
// source class attribute info
// Get class of module
final Class<?> moduleClass = lookupModuleClass(uri, clazz);
// Store class if thw module class actually exists
if( moduleClass != null) {
modulesClassMap.put(uri, moduleClass);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Configured module '{}' implemented in '{}'", uri, clazz);
}
}
//parse any module parameters
moduleParameters.put(uri, ParametersExtractor.extract(elem.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME)));
}
}
}
}
/**
* Returns the Class object associated with the with the given module class name. All
* important exceptions are caught. @see org.exist.xquery.Module
*
* @param uri namespace of class. For logging purposes only.
* @param clazz the fully qualified name of the desired module class.
* @return the module Class object for the module with the specified name.
* @throws DatabaseConfigurationException if the given module class is not an instance
* of org.exist.xquery.Module
*/
private Class<?> lookupModuleClass(String uri, String clazz) throws DatabaseConfigurationException
{
Class<?> mClass = null;
try {
mClass = Class.forName( clazz );
if( !( Module.class.isAssignableFrom( mClass ) ) ) {
throw( new DatabaseConfigurationException( "Failed to load module: " + uri
+ ". Class " + clazz + " is not an instance of org.exist.xquery.Module." ) );
}
} catch( final ClassNotFoundException e ) {
// Note: can't throw an exception here since this would create
// problems with test cases and jar dependencies
LOG.error("Configuration problem: class not found for module '{}' (ClassNotFoundException); class:'{}'; message:'{}'", uri, clazz, e.getMessage());
} catch( final NoClassDefFoundError e ) {
LOG.error("Module {} could not be initialized due to a missing dependancy (NoClassDefFoundError): {}", uri, e.getMessage(), e);
}
return mClass;
}
/**
* DOCUMENT ME!
*
* @param xupdate
*
* @throws NumberFormatException
*/
private void configureXUpdate( Element xupdate ) throws NumberFormatException
{
final String fragmentation = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_FRAGMENTATION_FACTOR_ATTRIBUTE );
if( fragmentation != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR, Integer.valueOf(fragmentation) );
LOG.debug(DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR + ": {}", config.get(DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR));
}
final String consistencyCheck = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_CONSISTENCY_CHECKS_ATTRIBUTE );
if( consistencyCheck != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS, parseBoolean( consistencyCheck, false ) );
LOG.debug(DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS + ": {}", config.get(DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS));
}
}
private void configureTransformer( Element transformer )
{
final String className = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CLASS_ATTRIBUTE );
if( className != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS, className );
LOG.debug(TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS + ": {}", config.get(TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS));
// Process any specified attributes that should be passed to the transformer factory
final NodeList attrs = transformer.getElementsByTagName( TransformerFactoryAllocator.CONFIGURATION_TRANSFORMER_ATTRIBUTE_ELEMENT_NAME );
final Hashtable<Object, Object> attributes = new Properties();
for( int a = 0; a < attrs.getLength(); a++ ) {
final Element attr = (Element)attrs.item( a );
final String name = attr.getAttribute( "name" );
final String value = attr.getAttribute( "value" );
final String type = attr.getAttribute( "type" );
if( ( name == null ) || (name.isEmpty()) ) {
LOG.warn("Discarded invalid attribute for TransformerFactory: '{}', name not specified", className);
} else if( ( type == null ) || (type.isEmpty()) || type.equalsIgnoreCase( "string" ) ) {
attributes.put( name, value );
} else if( type.equalsIgnoreCase( "boolean" ) ) {
attributes.put( name, Boolean.valueOf( value ) );
} else if( type.equalsIgnoreCase( "integer" ) ) {
try {
attributes.put( name, Integer.valueOf( value ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Discarded invalid attribute for TransformerFactory: '{}', name: {}, value not integer: {}", className, name, value, nfe);
}
} else {
// Assume string type
attributes.put( name, value );
}
}
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_ATTRIBUTES, attributes );
}
final String cachingValue = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CACHING_ATTRIBUTE );
if( cachingValue != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE, parseBoolean( cachingValue, false ) );
LOG.debug(TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE + ": {}", config.get(TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE));
}
}
private void configureParser(final Element parser) {
configureXmlParser(parser);
configureHtmlToXmlParser(parser);
}
private void configureXmlParser(final Element parser) {
final NodeList nlXml = parser.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_ELEMENT);
if(nlXml.getLength() > 0) {
final Element xml = (Element)nlXml.item(0);
final NodeList nlFeatures = xml.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
private void configureHtmlToXmlParser(final Element parser) {
final NodeList nlHtmlToXml = parser.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_ELEMENT);
if(nlHtmlToXml.getLength() > 0) {
final Element htmlToXml = (Element)nlHtmlToXml.item(0);
final String htmlToXmlParserClass = getConfigAttributeValue(htmlToXml, HtmlToXmlParser.HTML_TO_XML_PARSER_CLASS_ATTRIBUTE);
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTY, htmlToXmlParserClass);
final NodeList nlProperties = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_ELEMENT);
if(nlProperties.getLength() > 0) {
final Properties pProperties = ParametersExtractor.parseProperties(nlProperties.item(0));
if(pProperties != null) {
final Map<String, Object> properties = new HashMap<>();
pProperties.forEach((k,v) -> properties.put(k.toString(), v));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_PROPERTY, properties);
}
}
final NodeList nlFeatures = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param serializer
*/
private void configureSerializer( Element serializer )
{
final String xinclude = getConfigAttributeValue( serializer, Serializer.ENABLE_XINCLUDE_ATTRIBUTE );
if( xinclude != null ) {
config.put( Serializer.PROPERTY_ENABLE_XINCLUDE, xinclude );
LOG.debug(Serializer.PROPERTY_ENABLE_XINCLUDE + ": {}", config.get(Serializer.PROPERTY_ENABLE_XINCLUDE));
}
final String xsl = getConfigAttributeValue( serializer, Serializer.ENABLE_XSL_ATTRIBUTE );
if( xsl != null ) {
config.put( Serializer.PROPERTY_ENABLE_XSL, xsl );
LOG.debug(Serializer.PROPERTY_ENABLE_XSL + ": {}", config.get(Serializer.PROPERTY_ENABLE_XSL));
}
final String indent = getConfigAttributeValue( serializer, Serializer.INDENT_ATTRIBUTE );
if( indent != null ) {
config.put( Serializer.PROPERTY_INDENT, indent );
LOG.debug(Serializer.PROPERTY_INDENT + ": {}", config.get(Serializer.PROPERTY_INDENT));
}
final String compress = getConfigAttributeValue( serializer, Serializer.COMPRESS_OUTPUT_ATTRIBUTE );
if( compress != null ) {
config.put( Serializer.PROPERTY_COMPRESS_OUTPUT, compress );
LOG.debug(Serializer.PROPERTY_COMPRESS_OUTPUT + ": {}", config.get(Serializer.PROPERTY_COMPRESS_OUTPUT));
}
final String internalId = getConfigAttributeValue( serializer, Serializer.ADD_EXIST_ID_ATTRIBUTE );
if( internalId != null ) {
config.put( Serializer.PROPERTY_ADD_EXIST_ID, internalId );
LOG.debug(Serializer.PROPERTY_ADD_EXIST_ID + ": {}", config.get(Serializer.PROPERTY_ADD_EXIST_ID));
}
final String tagElementMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ELEMENTS_ATTRIBUTE );
if( tagElementMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS, tagElementMatches );
LOG.debug(Serializer.PROPERTY_TAG_MATCHING_ELEMENTS + ": {}", config.get(Serializer.PROPERTY_TAG_MATCHING_ELEMENTS));
}
final String tagAttributeMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ATTRIBUTES_ATTRIBUTE );
if( tagAttributeMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES, tagAttributeMatches );
LOG.debug(Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES + ": {}", config.get(Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES));
}
final NodeList nlFilters = serializer.getElementsByTagName( CustomMatchListenerFactory.CONFIGURATION_ELEMENT );
if( nlFilters != null ) {
final List<String> filters = new ArrayList<>(nlFilters.getLength());
for (int i = 0; i < nlFilters.getLength(); i++) {
final Element filterElem = (Element) nlFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": {}", filterClass);
} else {
LOG.warn("Configuration element " + CustomMatchListenerFactory.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
config.put(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS, filters);
}
final NodeList backupFilters = serializer.getElementsByTagName( SystemExport.CONFIGURATION_ELEMENT );
if( backupFilters != null ) {
final List<String> filters = new ArrayList<>(backupFilters.getLength());
for (int i = 0; i < backupFilters.getLength(); i++) {
final Element filterElem = (Element) backupFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": {}", filterClass);
} else {
LOG.warn("Configuration element " + SystemExport.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
if (!filters.isEmpty()) config.put(SystemExport.CONFIG_FILTERS, filters);
}
}
/**
* Reads the scheduler configuration.
*
* @param scheduler DOCUMENT ME!
*/
private void configureScheduler(final Element scheduler)
{
final NodeList nlJobs = scheduler.getElementsByTagName(JobConfig.CONFIGURATION_JOB_ELEMENT_NAME);
if(nlJobs == null) {
return;
}
final List<JobConfig> jobList = new ArrayList<>();
for(int i = 0; i < nlJobs.getLength(); i++) {
final Element job = (Element)nlJobs.item( i );
//get the job type
final String strJobType = getConfigAttributeValue(job, JobConfig.JOB_TYPE_ATTRIBUTE);
final JobType jobType;
if(strJobType == null) {
jobType = JobType.USER; //default to user if unspecified
} else {
jobType = JobType.valueOf(strJobType.toUpperCase(Locale.ENGLISH));
}
final String jobName = getConfigAttributeValue(job, JobConfig.JOB_NAME_ATTRIBUTE);
//get the job resource
String jobResource = getConfigAttributeValue(job, JobConfig.JOB_CLASS_ATTRIBUTE);
if(jobResource == null) {
jobResource = getConfigAttributeValue(job, JobConfig.JOB_XQUERY_ATTRIBUTE);
}
//get the job schedule
String jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_CRON_TRIGGER_ATTRIBUTE);
if(jobSchedule == null) {
jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_PERIOD_ATTRIBUTE);
}
final String jobUnschedule = getConfigAttributeValue(job, JobConfig.JOB_UNSCHEDULE_ON_EXCEPTION);
//create the job config
try {
final JobConfig jobConfig = new JobConfig(jobType, jobName, jobResource, jobSchedule, jobUnschedule);
//get and set the job delay
final String jobDelay = getConfigAttributeValue(job, JobConfig.JOB_DELAY_ATTRIBUTE);
if((jobDelay != null) && (!jobDelay.isEmpty())) {
jobConfig.setDelay(Long.parseLong(jobDelay));
}
//get and set the job repeat
final String jobRepeat = getConfigAttributeValue(job, JobConfig.JOB_REPEAT_ATTRIBUTE);
if((jobRepeat != null) && (!jobRepeat.isEmpty())) {
jobConfig.setRepeat(Integer.parseInt(jobRepeat));
}
final NodeList nlParam = job.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME);
final Map<String, List<? extends Object>> params = ParametersExtractor.extract(nlParam);
for(final Entry<String, List<? extends Object>> param : params.entrySet()) {
final List<? extends Object> values = param.getValue();
if(values != null && !values.isEmpty()) {
jobConfig.addParameter(param.getKey(), values.get(0).toString());
if(values.size() > 1) {
LOG.warn("Parameter '{}' for job '{}' has more than one value, ignoring further values.", param.getKey(), jobName);
}
}
}
jobList.add(jobConfig);
LOG.debug("Configured scheduled '{}' job '{}{}{}{}'", jobType, jobResource, (jobSchedule == null) ? "" : ("' with trigger '" + jobSchedule), (jobDelay == null) ? "" : ("' with delay '" + jobDelay), (jobRepeat == null) ? "" : ("' repetitions '" + jobRepeat));
} catch(final JobException je) {
LOG.error(je);
}
}
if(!jobList.isEmpty()) {
final JobConfig[] configs = new JobConfig[jobList.size()];
for(int i = 0; i < jobList.size(); i++) {
configs[i] = (JobConfig)jobList.get(i);
}
config.put(JobConfig.PROPERTY_SCHEDULER_JOBS, configs);
}
}
/**
* DOCUMENT ME!
*
* @param dbHome
* @param con
*
* @throws DatabaseConfigurationException
*/
private void configureBackend( final Optional<Path> dbHome, Element con ) throws DatabaseConfigurationException
{
final String database = getConfigAttributeValue(con, BrokerFactory.PROPERTY_DATABASE);
if (database != null) {
config.put(BrokerFactory.PROPERTY_DATABASE, database);
LOG.debug(BrokerFactory.PROPERTY_DATABASE + ": {}", config.get(BrokerFactory.PROPERTY_DATABASE));
}
// directory for database files
final String dataFiles = getConfigAttributeValue( con, BrokerPool.DATA_DIR_ATTRIBUTE );
if (dataFiles != null) {
final Path df = ConfigurationHelper.lookup( dataFiles, dbHome );
if (!Files.isReadable(df)) {
try {
Files.createDirectories(df);
} catch (final IOException ioe) {
throw new DatabaseConfigurationException("cannot read data directory: " + df.toAbsolutePath().toString(), ioe);
}
}
config.put(BrokerPool.PROPERTY_DATA_DIR, df.toAbsolutePath());
LOG.debug(BrokerPool.PROPERTY_DATA_DIR + ": {}", config.get(BrokerPool.PROPERTY_DATA_DIR));
}
String cacheMem = getConfigAttributeValue( con, DefaultCacheManager.CACHE_SIZE_ATTRIBUTE );
if( cacheMem != null ) {
if( cacheMem.endsWith( "M" ) || cacheMem.endsWith( "m" ) ) {
cacheMem = cacheMem.substring( 0, cacheMem.length() - 1 );
}
try {
config.put( DefaultCacheManager.PROPERTY_CACHE_SIZE, Integer.valueOf(cacheMem) );
LOG.debug(DefaultCacheManager.PROPERTY_CACHE_SIZE + ": {}m", config.get(DefaultCacheManager.PROPERTY_CACHE_SIZE));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + DefaultCacheManager.PROPERTY_CACHE_SIZE + " value to integer: {}", cacheMem, nfe);
}
}
// Process the Check Max Cache value
String checkMaxCache = getConfigAttributeValue( con, DefaultCacheManager.CACHE_CHECK_MAX_SIZE_ATTRIBUTE );
if( checkMaxCache == null ) {
checkMaxCache = DefaultCacheManager.DEFAULT_CACHE_CHECK_MAX_SIZE_STRING;
}
config.put( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE, parseBoolean( checkMaxCache, true ) );
LOG.debug(DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE + ": {}", config.get(DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE));
String cacheShrinkThreshold = getConfigAttributeValue( con, DefaultCacheManager.SHRINK_THRESHOLD_ATTRIBUTE );
if( cacheShrinkThreshold == null ) {
cacheShrinkThreshold = DefaultCacheManager.DEFAULT_SHRINK_THRESHOLD_STRING;
}
try {
config.put(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY, Integer.valueOf(cacheShrinkThreshold));
LOG.debug(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + ": {}", config.get(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY));
} catch(final NumberFormatException nfe) {
LOG.warn("Cannot convert " + DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + " value to integer: {}", cacheShrinkThreshold, nfe);
}
String collectionCache = getConfigAttributeValue(con, CollectionCache.CACHE_SIZE_ATTRIBUTE);
if(collectionCache != null) {
collectionCache = collectionCache.toLowerCase();
try {
final int collectionCacheBytes;
if(collectionCache.endsWith("k")) {
collectionCacheBytes = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("kb")) {
collectionCacheBytes = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("m")) {
collectionCacheBytes = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("mb")) {
collectionCacheBytes = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("g")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("gb")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else {
collectionCacheBytes = Integer.parseInt(collectionCache);
}
config.put(CollectionCache.PROPERTY_CACHE_SIZE_BYTES, collectionCacheBytes);
if(LOG.isDebugEnabled()) {
LOG.debug("Set config {} = {}", CollectionCache.PROPERTY_CACHE_SIZE_BYTES, config.get(CollectionCache.PROPERTY_CACHE_SIZE_BYTES));
}
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + CollectionCache.PROPERTY_CACHE_SIZE_BYTES + " value to integer: {}", collectionCache, nfe);
}
}
final String pageSize = getConfigAttributeValue( con, NativeBroker.PAGE_SIZE_ATTRIBUTE );
if( pageSize != null ) {
try {
config.put( BrokerPool.PROPERTY_PAGE_SIZE, Integer.valueOf(pageSize) );
LOG.debug(BrokerPool.PROPERTY_PAGE_SIZE + ": {}", config.get(BrokerPool.PROPERTY_PAGE_SIZE));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_PAGE_SIZE + " value to integer: {}", pageSize, nfe);
}
}
//Not clear : rather looks like a buffers count
final String collCacheSize = getConfigAttributeValue( con, BrokerPool.COLLECTION_CACHE_SIZE_ATTRIBUTE );
if( collCacheSize != null ) {
try {
config.put( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE, Integer.valueOf(collCacheSize) );
LOG.debug(BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + ": {}", config.get(BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + " value to integer: {}", collCacheSize, nfe);
}
}
final String nodesBuffer = getConfigAttributeValue( con, BrokerPool.NODES_BUFFER_ATTRIBUTE );
if( nodesBuffer != null ) {
try {
config.put( BrokerPool.PROPERTY_NODES_BUFFER, Integer.valueOf(nodesBuffer) );
LOG.debug(BrokerPool.PROPERTY_NODES_BUFFER + ": {}", config.get(BrokerPool.PROPERTY_NODES_BUFFER));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_NODES_BUFFER + " value to integer: {}", nodesBuffer, nfe);
}
}
String diskSpace = getConfigAttributeValue(con, BrokerPool.DISK_SPACE_MIN_ATTRIBUTE);
if( diskSpace != null ) {
if( diskSpace.endsWith( "M" ) || diskSpace.endsWith( "m" ) ) {
diskSpace = diskSpace.substring( 0, diskSpace.length() - 1 );
}
try {
config.put(BrokerPool.DISK_SPACE_MIN_PROPERTY, Short.valueOf(diskSpace));
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.DISK_SPACE_MIN_PROPERTY + " value to integer: {}", diskSpace, nfe);
}
}
final String posixChownRestrictedStr = getConfigAttributeValue(con, DBBroker.POSIX_CHOWN_RESTRICTED_ATTRIBUTE);
final boolean posixChownRestricted;
if(posixChownRestrictedStr == null) {
posixChownRestricted = true; // default
} else {
if(Boolean.parseBoolean(posixChownRestrictedStr)) {
posixChownRestricted = true;
} else {
// configuration explicitly specifies that posix chown should NOT be restricted
posixChownRestricted = false;
}
}
config.put(DBBroker.POSIX_CHOWN_RESTRICTED_PROPERTY, posixChownRestricted);
final String preserveOnCopyStr = getConfigAttributeValue(con, DBBroker.PRESERVE_ON_COPY_ATTRIBUTE);
final DBBroker.PreserveType preserveOnCopy;
if(preserveOnCopyStr == null) {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE; // default
} else {
if(Boolean.parseBoolean(preserveOnCopyStr)) {
// configuration explicitly specifies that attributes should be preserved on copy
preserveOnCopy = DBBroker.PreserveType.PRESERVE;
} else {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE;
}
}
config.put(DBBroker.PRESERVE_ON_COPY_PROPERTY, preserveOnCopy);
final NodeList startupConf = con.getElementsByTagName(BrokerPool.CONFIGURATION_STARTUP_ELEMENT_NAME);
if(startupConf.getLength() > 0) {
configureStartup((Element)startupConf.item(0));
} else {
// Prevent NPE
final List<StartupTriggerConfig> startupTriggers = new ArrayList<>();
config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers);
}
final NodeList poolConf = con.getElementsByTagName( BrokerPool.CONFIGURATION_POOL_ELEMENT_NAME );
if( poolConf.getLength() > 0 ) {
configurePool( (Element)poolConf.item( 0 ) );
}
final NodeList queryPoolConf = con.getElementsByTagName( XQueryPool.CONFIGURATION_ELEMENT_NAME );
if( queryPoolConf.getLength() > 0 ) {
configureXQueryPool( (Element)queryPoolConf.item( 0 ) );
}
final NodeList watchConf = con.getElementsByTagName( XQueryWatchDog.CONFIGURATION_ELEMENT_NAME );
if( watchConf.getLength() > 0 ) {
configureWatchdog( (Element)watchConf.item( 0 ) );
}
final NodeList recoveries = con.getElementsByTagName( BrokerPool.CONFIGURATION_RECOVERY_ELEMENT_NAME );
if( recoveries.getLength() > 0 ) {
configureRecovery( dbHome, (Element)recoveries.item( 0 ) );
}
}
private void configureRecovery( final Optional<Path> dbHome, Element recovery ) throws DatabaseConfigurationException
{
String option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_ENABLED_ATTRIBUTE );
setProperty( BrokerPool.PROPERTY_RECOVERY_ENABLED, parseBoolean( option, true ) );
LOG.debug(BrokerPool.PROPERTY_RECOVERY_ENABLED + ": {}", config.get(BrokerPool.PROPERTY_RECOVERY_ENABLED));
option = getConfigAttributeValue( recovery, Journal.RECOVERY_SYNC_ON_COMMIT_ATTRIBUTE );
setProperty( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT, parseBoolean( option, true ) );
LOG.debug(Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT + ": {}", config.get(Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT));
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_GROUP_COMMIT_ATTRIBUTE );
setProperty( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT, parseBoolean( option, false ) );
LOG.debug(BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT + ": {}", config.get(BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT));
option = getConfigAttributeValue( recovery, Journal.RECOVERY_JOURNAL_DIR_ATTRIBUTE );
if(option != null) {
//DWES
final Path rf = ConfigurationHelper.lookup( option, dbHome );
if(!Files.isReadable(rf)) {
throw new DatabaseConfigurationException( "cannot read data directory: " + rf.toAbsolutePath());
}
setProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR, rf.toAbsolutePath());
LOG.debug(Journal.PROPERTY_RECOVERY_JOURNAL_DIR + ": {}", config.get(Journal.PROPERTY_RECOVERY_JOURNAL_DIR));
}
option = getConfigAttributeValue( recovery, Journal.RECOVERY_SIZE_LIMIT_ATTRIBUTE );
if( option != null ) {
if( option.endsWith( "M" ) || option.endsWith( "m" ) ) {
option = option.substring( 0, option.length() - 1 );
}
try {
final Integer size = Integer.valueOf( option );
setProperty( Journal.PROPERTY_RECOVERY_SIZE_LIMIT, size );
LOG.debug(Journal.PROPERTY_RECOVERY_SIZE_LIMIT + ": {}m", config.get(Journal.PROPERTY_RECOVERY_SIZE_LIMIT));
}
catch( final NumberFormatException e ) {
throw( new DatabaseConfigurationException( "size attribute in recovery section needs to be a number" ) );
}
}
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_FORCE_RESTART_ATTRIBUTE );
boolean value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART, value);
LOG.debug(BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART + ": {}", config.get(BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART));
option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_POST_RECOVERY_CHECK );
value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.PROPERTY_RECOVERY_CHECK, value);
LOG.debug(BrokerPool.PROPERTY_RECOVERY_CHECK + ": {}", config.get(BrokerPool.PROPERTY_RECOVERY_CHECK));
}
/**
* DOCUMENT ME!
*
* @param watchDog
*/
private void configureWatchdog( Element watchDog )
{
final String timeout = getConfigAttributeValue( watchDog, "query-timeout" );
if( timeout != null ) {
try {
config.put( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT, Long.valueOf(timeout) );
LOG.debug(XQueryWatchDog.PROPERTY_QUERY_TIMEOUT + ": {}", config.get(XQueryWatchDog.PROPERTY_QUERY_TIMEOUT));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxOutput = getConfigAttributeValue( watchDog, "output-size-limit" );
if( maxOutput != null ) {
try {
config.put( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT, Integer.valueOf(maxOutput) );
LOG.debug(XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT + ": {}", config.get(XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
/**
* DOCUMENT ME!
*
* @param queryPool
*/
private void configureXQueryPool( Element queryPool )
{
final String maxStackSize = getConfigAttributeValue( queryPool, XQueryPool.MAX_STACK_SIZE_ATTRIBUTE );
if( maxStackSize != null ) {
try {
config.put( XQueryPool.PROPERTY_MAX_STACK_SIZE, Integer.valueOf(maxStackSize) );
LOG.debug(XQueryPool.PROPERTY_MAX_STACK_SIZE + ": {}", config.get(XQueryPool.PROPERTY_MAX_STACK_SIZE));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxPoolSize = getConfigAttributeValue( queryPool, XQueryPool.POOL_SIZE_ATTTRIBUTE );
if( maxPoolSize != null ) {
try {
config.put( XQueryPool.PROPERTY_POOL_SIZE, Integer.valueOf(maxPoolSize) );
LOG.debug(XQueryPool.PROPERTY_POOL_SIZE + ": {}", config.get(XQueryPool.PROPERTY_POOL_SIZE));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
public static class StartupTriggerConfig {
private final String clazz;
private final Map<String, List<? extends Object>> params;
public StartupTriggerConfig(final String clazz, final Map<String, List<? extends Object>> params) {
this.clazz = clazz;
this.params = params;
}
public String getClazz() {
return clazz;
}
public Map<String, List<? extends Object>> getParams() {
return params;
}
}
private void configureStartup(final Element startup) {
// Retrieve <triggers>
final NodeList nlTriggers = startup.getElementsByTagName("triggers");
// If <triggers> exists
if(nlTriggers != null && nlTriggers.getLength() > 0) {
// Get <triggers>
final Element triggers = (Element)nlTriggers.item(0);
// Get <trigger>
final NodeList nlTrigger = triggers.getElementsByTagName("trigger");
// If <trigger> exists and there are more than 0
if(nlTrigger != null && nlTrigger.getLength() > 0) {
// Initialize trigger configuration
List<StartupTriggerConfig> startupTriggers = (List<StartupTriggerConfig>)config.get(BrokerPool.PROPERTY_STARTUP_TRIGGERS);
if(startupTriggers == null) {
startupTriggers = new ArrayList<>();
config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers);
}
// Iterate over <trigger> elements
for(int i = 0; i < nlTrigger.getLength(); i++) {
// Get <trigger> element
final Element trigger = (Element)nlTrigger.item(i);
// Get @class
final String startupTriggerClass = trigger.getAttribute("class");
boolean isStartupTrigger = false;
try {
// Verify if class is StartupTrigger
for(final Class iface : Class.forName(startupTriggerClass).getInterfaces()) {
if("org.exist.storage.StartupTrigger".equals(iface.getName())) {
isStartupTrigger = true;
break;
}
}
// if it actually is a StartupTrigger
if(isStartupTrigger) {
// Parse additional parameters
final Map<String, List<? extends Object>> params
= ParametersExtractor.extract(trigger.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME));
// Register trigger
startupTriggers.add(new StartupTriggerConfig(startupTriggerClass, params));
// Done
LOG.info("Registered StartupTrigger: {}", startupTriggerClass);
} else {
LOG.warn("StartupTrigger: {} does not implement org.exist.storage.StartupTrigger. IGNORING!", startupTriggerClass);
}
} catch(final ClassNotFoundException cnfe) {
LOG.error("Could not find StartupTrigger class: {}. {}", startupTriggerClass, cnfe.getMessage(), cnfe);
}
}
}
}
}
/**
* DOCUMENT ME!
*
* @param pool
*/
private void configurePool( Element pool )
{
final String min = getConfigAttributeValue( pool, BrokerPool.MIN_CONNECTIONS_ATTRIBUTE );
if( min != null ) {
try {
config.put( BrokerPool.PROPERTY_MIN_CONNECTIONS, Integer.valueOf(min) );
LOG.debug(BrokerPool.PROPERTY_MIN_CONNECTIONS + ": {}", config.get(BrokerPool.PROPERTY_MIN_CONNECTIONS));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String max = getConfigAttributeValue( pool, BrokerPool.MAX_CONNECTIONS_ATTRIBUTE );
if( max != null ) {
try {
config.put( BrokerPool.PROPERTY_MAX_CONNECTIONS, Integer.valueOf(max) );
LOG.debug(BrokerPool.PROPERTY_MAX_CONNECTIONS + ": {}", config.get(BrokerPool.PROPERTY_MAX_CONNECTIONS));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String sync = getConfigAttributeValue( pool, BrokerPool.SYNC_PERIOD_ATTRIBUTE );
if( sync != null ) {
try {
config.put( BrokerPool.PROPERTY_SYNC_PERIOD, Long.valueOf(sync) );
LOG.debug(BrokerPool.PROPERTY_SYNC_PERIOD + ": {}", config.get(BrokerPool.PROPERTY_SYNC_PERIOD));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String maxShutdownWait = getConfigAttributeValue( pool, BrokerPool.SHUTDOWN_DELAY_ATTRIBUTE );
if( maxShutdownWait != null ) {
try {
config.put( BrokerPool.PROPERTY_SHUTDOWN_DELAY, Long.valueOf(maxShutdownWait) );
LOG.debug(BrokerPool.PROPERTY_SHUTDOWN_DELAY + ": {}", config.get(BrokerPool.PROPERTY_SHUTDOWN_DELAY));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
}
private void configureIndexer( final Optional<Path> dbHome, Document doc, Element indexer ) throws DatabaseConfigurationException, MalformedURLException
{
final String caseSensitive = getConfigAttributeValue( indexer, NativeValueIndex.INDEX_CASE_SENSITIVE_ATTRIBUTE );
if( caseSensitive != null ) {
config.put( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE, parseBoolean( caseSensitive, false ) );
LOG.debug(NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE + ": {}", config.get(NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE));
}
int depth = 3;
final String indexDepth = getConfigAttributeValue( indexer, NativeBroker.INDEX_DEPTH_ATTRIBUTE );
if( indexDepth != null ) {
try {
depth = Integer.parseInt( indexDepth );
if( depth < 3 ) {
LOG.warn( "parameter index-depth should be >= 3 or you will experience a severe " + "performance loss for node updates (XUpdate or XQuery update extensions)" );
depth = 3;
}
config.put( NativeBroker.PROPERTY_INDEX_DEPTH, depth);
LOG.debug(NativeBroker.PROPERTY_INDEX_DEPTH + ": {}", config.get(NativeBroker.PROPERTY_INDEX_DEPTH));
}
catch( final NumberFormatException e ) {
LOG.warn( e );
}
}
final String suppressWS = getConfigAttributeValue( indexer, Indexer.SUPPRESS_WHITESPACE_ATTRIBUTE );
if( suppressWS != null ) {
config.put( Indexer.PROPERTY_SUPPRESS_WHITESPACE, suppressWS );
LOG.debug(Indexer.PROPERTY_SUPPRESS_WHITESPACE + ": {}", config.get(Indexer.PROPERTY_SUPPRESS_WHITESPACE));
}
final String suppressWSmixed = getConfigAttributeValue( indexer, Indexer.PRESERVE_WS_MIXED_CONTENT_ATTRIBUTE );
if( suppressWSmixed != null ) {
config.put( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT, parseBoolean( suppressWSmixed, false ) );
LOG.debug(Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT + ": {}", config.get(Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT));
}
// index settings
final NodeList cl = doc.getElementsByTagName( Indexer.CONFIGURATION_INDEX_ELEMENT_NAME );
if( cl.getLength() > 0 ) {
final Element elem = (Element)cl.item( 0 );
final IndexSpec spec = new IndexSpec( null, elem );
config.put( Indexer.PROPERTY_INDEXER_CONFIG, spec );
//LOG.debug(Indexer.PROPERTY_INDEXER_CONFIG + ": " + config.get(Indexer.PROPERTY_INDEXER_CONFIG));
}
// index modules
NodeList modules = indexer.getElementsByTagName( IndexManager.CONFIGURATION_ELEMENT_NAME );
if( modules.getLength() > 0 ) {
modules = ( (Element)modules.item( 0 ) ).getElementsByTagName( IndexManager.CONFIGURATION_MODULE_ELEMENT_NAME );
final IndexModuleConfig[] modConfig = new IndexModuleConfig[modules.getLength()];
for( int i = 0; i < modules.getLength(); i++ ) {
final Element elem = (Element)modules.item( i );
final String className = elem.getAttribute( IndexManager.INDEXER_MODULES_CLASS_ATTRIBUTE );
final String id = elem.getAttribute( IndexManager.INDEXER_MODULES_ID_ATTRIBUTE );
if( ( className == null ) || (className.isEmpty()) ) {
throw( new DatabaseConfigurationException( "Required attribute class is missing for module" ) );
}
if( ( id == null ) || (id.isEmpty()) ) {
throw( new DatabaseConfigurationException( "Required attribute id is missing for module" ) );
}
modConfig[i] = new IndexModuleConfig( id, className, elem );
}
config.put( IndexManager.PROPERTY_INDEXER_MODULES, modConfig );
}
}
private void configureValidation(final Optional<Path> dbHome, final Element validation) throws DatabaseConfigurationException {
// Determine validation mode
final String mode = getConfigAttributeValue(validation, XMLReaderObjectFactory.VALIDATION_MODE_ATTRIBUTE);
if (mode != null) {
config.put(XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE, mode);
if (LOG.isDebugEnabled()) {
LOG.debug(XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE + ": {}", config.get(XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE));
}
}
// Configure the Entity Resolver
final NodeList entityResolver = validation.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_ENTITY_RESOLVER_ELEMENT_NAME);
if (entityResolver.getLength() > 0) {
LOG.info("Creating xmlresolver.org OASIS Catalog resolver");
final Element elemEntityResolver = (Element) entityResolver.item(0);
final NodeList nlCatalogs = elemEntityResolver.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_CATALOG_ELEMENT_NAME);
// Determine webapps directory. SingleInstanceConfiguration cannot
// be used at this phase. Trick is to check whether dbHOME is
// pointing to a WEB-INF directory, meaning inside the war file.
final Path webappHome = dbHome.map(h -> {
if(FileUtils.fileName(h).endsWith("WEB-INF")) {
return h.getParent().toAbsolutePath();
} else {
return h.resolve("webapp").toAbsolutePath();
}
}).orElse(Paths.get("webapp").toAbsolutePath());
if (LOG.isDebugEnabled()) {
LOG.debug("Found " + nlCatalogs.getLength() + " catalog uri entries.");
LOG.debug("Using dbHome=" + dbHome);
LOG.debug("using webappHome=" + webappHome.toString());
}
// Get the Catalog URIs
final List<String> catalogUris = new ArrayList<>();
for (int i = 0; i < nlCatalogs.getLength(); i++) {
String uri = ((Element) nlCatalogs.item(i)).getAttribute("uri");
if (uri != null) {
// Substitute string, creating an uri from a local file
if (uri.indexOf("${WEBAPP_HOME}") != -1) {
uri = uri.replaceAll("\\$\\{WEBAPP_HOME\\}", webappHome.toUri().toString());
}
if (uri.indexOf("${EXIST_HOME}") != -1) {
uri = uri.replaceAll("\\$\\{EXIST_HOME\\}", dbHome.toString());
}
// Add uri to configuration
LOG.info("Adding Catalog URI: " + uri);
catalogUris.add(uri);
}
}
// Store all configured URIs
config.put(XMLReaderObjectFactory.CATALOG_URIS, catalogUris);
// Create and Store the resolver
try {
final List<Tuple2<String, Optional<InputSource>>> catalogs = catalogUris.stream().map(catalogUri -> Tuple(catalogUri, Optional.<InputSource>empty())).collect(Collectors.toList());
final Resolver resolver = ResolverFactory.newResolver(catalogs);
config.put(XMLReaderObjectFactory.CATALOG_RESOLVER, resolver);
} catch (final URISyntaxException e) {
LOG.error("Unable to parse catalog uri: " + e.getMessage(), e);
}
}
// cache
final GrammarPool gp = new GrammarPool();
config.put( XMLReaderObjectFactory.GRAMMAR_POOL, gp);
}
/**
* Gets the value of a configuration attribute
*
* The value typically is specified in the conf.xml file, but can be overridden with using a System Property
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The value of the attribute
*/
private String getConfigAttributeValue( Element element, String attributeName )
{
String value = null;
if( element != null && attributeName != null ) {
final String property = getAttributeSystemPropertyName( element, attributeName );
value = System.getProperty( property );
// If the value has not been overriden in a system property, then get it from the configuration
if( value != null ) {
LOG.warn("Configuration value overridden by system property: {}, with value: {}", property, value);
} else {
value = element.getAttribute( attributeName );
}
}
return( value );
}
/**
* Generates a suitable system property name from the given config attribute and parent element.
*
* values are of the form org.element.element.....attribute and follow the heirarchical structure of the conf.xml file.
* For example, the db-connection cacheSize property name would be org.exist.db-connection.cacheSize
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The generated system property name
*/
private String getAttributeSystemPropertyName( Element element, String attributeName )
{
final StringBuilder property = new StringBuilder( attributeName );
Node parent = element.getParentNode();
property.insert( 0, "." );
property.insert( 0, element.getLocalName() );
while( parent != null && parent instanceof Element ) {
final String parentName = ((Element)parent).getLocalName();
property.insert( 0, "." );
property.insert( 0, parentName );
parent = parent.getParentNode();
}
property.insert( 0, "org." );
return( property.toString() );
}
public Optional<Path> getConfigFilePath() {
return configFilePath;
}
public Optional<Path> getExistHome() {
return existHome;
}
public Object getProperty(final String name) {
return config.get(name);
}
public <T> T getProperty(final String name, final T defaultValue) {
return Optional.ofNullable((T)config.get(name)).orElse(defaultValue);
}
public boolean hasProperty(final String name) {
return config.containsKey(name);
}
public void setProperty(final String name, final Object obj) {
config.put(name, obj);
}
public void removeProperty(final String name) {
config.remove(name);
}
/**
* Takes the passed string and converts it to a non-null <code>Boolean</code> object. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null
*
* @return The parsed <code>Boolean</code>
*/
public static boolean parseBoolean(@Nullable final String value, final boolean defaultValue) {
return Optional.ofNullable(value)
.map(v -> v.equalsIgnoreCase("yes") || v.equalsIgnoreCase("true"))
.orElse(defaultValue);
}
/**
* Takes the passed string and converts it to a non-null <code>int</code> value. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null or empty
*
* @return The parsed <code>int</code>
*/
public static int parseInt(@Nullable final String value, final int defaultValue) {
if (value == null || value.isEmpty()) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (final NumberFormatException e) {
LOG.warn("Could not parse: {}, as an int: {}", value, e.getMessage());
return defaultValue;
}
}
public int getInteger(final String name) {
return Optional.ofNullable(getProperty(name))
.filter(v -> v instanceof Integer)
.map(v -> (int)v)
.orElse(-1);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
*/
@Override
public void error( SAXParseException exception ) throws SAXException
{
LOG.error("error occurred while reading configuration file [line: {}]:{}", exception.getLineNumber(), exception.getMessage(), exception);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/
@Override
public void fatalError( SAXParseException exception ) throws SAXException
{
LOG.error("error occurred while reading configuration file [line: {}]:{}", exception.getLineNumber(), exception.getMessage(), exception);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/
@Override
public void warning( SAXParseException exception ) throws SAXException
{
LOG.error("error occurred while reading configuration file [line: {}]:{}", exception.getLineNumber(), exception.getMessage(), exception);
}
public static final class IndexModuleConfig {
private final String id;
private final String className;
private final Element config;
public IndexModuleConfig(final String id, final String className, final Element config) {
this.id = id;
this.className = className;
this.config = config;
}
public String getId()
{
return( id );
}
public String getClassName()
{
return( className );
}
public Element getConfig()
{
return( config );
}
}
}
|
package com.google.dogecoin.wallet;
import com.google.dogecoin.core.NetworkParameters;
import com.google.dogecoin.core.Transaction;
import com.google.dogecoin.core.TransactionConfidence;
import com.google.dogecoin.core.TransactionOutput;
import com.google.dogecoin.params.RegTestParams;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.util.*;
/**
* This class implements a {@link com.google.dogecoin.wallet.CoinSelector} which attempts to get the highest priority
* possible. This means that the transaction is the most likely to get confirmed. Note that this means we may end up
* "spending" more priority than would be required to get the transaction we are creating confirmed.
*/
public class DefaultCoinSelector implements CoinSelector {
public CoinSelection select(BigInteger biTarget, LinkedList<TransactionOutput> candidates) {
HashSet<TransactionOutput> selected = new HashSet<TransactionOutput>();
// Sort the inputs by age*value so we get the highest "coindays" spent.
// TODO: Consider changing the wallets internal format to track just outputs and keep them ordered.
ArrayList<TransactionOutput> sortedOutputs = new ArrayList<TransactionOutput>(candidates);
// When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting
// them in order to improve performance.
if (!biTarget.equals(NetworkParameters.MAX_MONEY)) {
sortOutputs(sortedOutputs);
}
// Now iterate over the sorted outputs until we have got as close to the target as possible or a little
// bit over (excessive value will be change).
BigInteger biTotal = BigInteger.ZERO;
for (TransactionOutput output : sortedOutputs) {
if (biTotal.compareTo(biTarget) >= 0) break;
// Only pick chain-included transactions, or transactions that are ours and pending.
if (!shouldSelect(output.getParentTransaction())) continue;
selected.add(output);
biTotal = biTotal.add(output.getValue());
}
// Total may be lower than target here, if the given candidates were insufficient to create to requested
// transaction.
return new CoinSelection(biTotal, selected);
}
@VisibleForTesting static void sortOutputs(ArrayList<TransactionOutput> outputs) {
Collections.sort(outputs, new Comparator<TransactionOutput>() {
public int compare(TransactionOutput a, TransactionOutput b) {
int depth1 = 0;
int depth2 = 0;
TransactionConfidence conf1 = a.getParentTransaction().getConfidence();
TransactionConfidence conf2 = b.getParentTransaction().getConfidence();
if (conf1.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
depth1 = conf1.getDepthInBlocks();
if (conf2.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
depth2 = conf2.getDepthInBlocks();
BigInteger aValue = a.getValue();
BigInteger bValue = b.getValue();
BigInteger aCoinDepth = aValue.multiply(BigInteger.valueOf(depth1));
BigInteger bCoinDepth = bValue.multiply(BigInteger.valueOf(depth2));
int c1 = bCoinDepth.compareTo(aCoinDepth);
if (c1 != 0) return c1;
// The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
int c2 = bValue.compareTo(aValue);
if (c2 != 0) return c2;
// They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
BigInteger aHash = a.getParentTransaction().getHash().toBigInteger();
BigInteger bHash = b.getParentTransaction().getHash().toBigInteger();
return aHash.compareTo(bHash);
}
});
}
/** Sub-classes can override this to just customize whether transactions are usable, but keep age sorting. */
protected boolean shouldSelect(Transaction tx) {
return isSelectable(tx);
}
public static boolean isSelectable(Transaction tx) {
// Only pick chain-included transactions, or transactions that are ours and pending.
TransactionConfidence confidence = tx.getConfidence();
TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
return type.equals(TransactionConfidence.ConfidenceType.BUILDING) ||
type.equals(TransactionConfidence.ConfidenceType.PENDING) &&
confidence.getSource().equals(TransactionConfidence.Source.SELF) &&
// In regtest mode we expect to have only one peer, so we won't see transactions propagate.
// TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0
(confidence.numBroadcastPeers() > 1 ); //|| tx.getParams() == RegTestParams.get());
}
}
|
package hudson.security;
import jenkins.model.Jenkins;
import hudson.TcpSlaveAgentListener;
import com.google.common.base.Strings;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.InsufficientAuthenticationException;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.MessageFormat;
/**
* For anonymous requests to pages that require authentication,
* first respond with {@link HttpServletResponse#SC_FORBIDDEN},
* then redirect browsers automatically to the login page.
*
* <p>
* This is a compromise to handle programmatic access and
* real browsers equally well.
*
* <p>
* The page that programs see is entirely white, and it auto-redirects,
* so humans wouldn't notice it.
*
* @author Kohsuke Kawaguchi
*/
public class HudsonAuthenticationEntryPoint extends AuthenticationProcessingFilterEntryPoint {
@Override
public void commence(ServletRequest request, ServletResponse response, AuthenticationException reason) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
String requestedWith = req.getHeader("X-Requested-With");
if("XMLHttpRequest".equals(requestedWith)) {
// container authentication normally relies on session attribute to
// remember where the user came from, so concurrent AJAX requests
// often ends up sending users back to AJAX pages after successful login.
// this is not desirable, so don't redirect AJAX requests to the user.
// this header value is sent from Prototype.
rsp.sendError(SC_FORBIDDEN);
} else {
// give the opportunity to include the target URL
String uriFrom = req.getRequestURI();
if(!Strings.isNullOrEmpty(req.getQueryString())) uriFrom += "?" + req.getQueryString();
String loginForm = req.getContextPath()+getLoginFormUrl();
loginForm = MessageFormat.format(loginForm, URLEncoder.encode(uriFrom,"UTF-8"));
req.setAttribute("loginForm", loginForm);
rsp.setStatus(SC_FORBIDDEN);
rsp.setContentType("text/html;charset=UTF-8");
// advertise the CLI TCP port
TcpSlaveAgentListener tal = Jenkins.getInstance().getTcpSlaveAgentListener();
if (tal!=null) {
rsp.setIntHeader("X-Hudson-CLI-Port", tal.getPort());
rsp.setIntHeader("X-Jenkins-CLI-Port", tal.getPort());
rsp.setIntHeader("X-Jenkins-CLI2-Port", tal.getPort());
rsp.setHeader("X-Jenkins-CLI-Host", TcpSlaveAgentListener.CLI_HOST_NAME);
}
AccessDeniedException2 cause = null;
// report the diagnosis information if possible
if (reason instanceof InsufficientAuthenticationException) {
if (reason.getCause() instanceof AccessDeniedException2) {
cause = (AccessDeniedException2) reason.getCause();
cause.reportAsHeaders(rsp);
}
}
PrintWriter out;
try {
out = new PrintWriter(new OutputStreamWriter(rsp.getOutputStream()));
} catch (IllegalStateException e) {
out = rsp.getWriter();
}
out.printf(
"<html><head>" +
"<meta http-equiv='refresh' content='1;url=%1$s'/>" +
"<script>window.location.replace('%1$s');</script>" +
"</head>" +
"<body style='background-color:white; color:white;'>\n" +
"\n\n"+
"Authentication required\n"+
"<!--\n",loginForm);
if (cause!=null)
cause.report(out);
out.printf(
"
"</body></html>");
// Turn Off "Show Friendly HTTP Error Messages" Feature on the Server Side.
for (int i=0; i < 10; i++)
out.print(" ");
out.close();
}
}
}
|
package net.fortytwo.twitlogic.util.misc;
import net.fortytwo.twitlogic.TwitLogic;
import net.fortytwo.twitlogic.model.User;
import net.fortytwo.twitlogic.services.twitter.TwitterClient;
import net.fortytwo.twitlogic.services.twitter.TwitterClientException;
import net.fortytwo.twitlogic.services.twitter.errors.NotFoundException;
import net.fortytwo.twitlogic.services.twitter.errors.UnauthorizedException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Properties;
public class FriendFetcher {
public static void main(final String[] args) {
try {
new FriendFetcher().doit();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private void doit() throws Exception {
Properties props = new Properties();
props.load(new FileInputStream("/tmp/friendfetcher.properties"));
TwitLogic.setConfiguration(props);
TwitterClient client = new TwitterClient();
OutputStream os = new FileOutputStream("/tmp/following.csv");
try {
PrintStream ps = new PrintStream(os);
FileInputStream fstream = new FileInputStream("/tmp/users");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String l;
while ((l = br.readLine()) != null) {
String id = l.trim();
User user = new User(id);
try {
for (User followed : client.getFollowedUsers(user)) {
ps.println(id + "\t" + followed.getId());
}
} catch (UnauthorizedException e) {
System.err.println("warning: not authorized to fetch followers of user '" + id + "'");
} catch (NotFoundException e) {
System.err.println("user '" + id + "' not found");
} catch (TwitterClientException e) {
System.err.println("twitter client exception: " + e.getMessage());
}
}
in.close();
} finally {
os.close();
}
}
}
|
package org.lemurproject.galago.core.retrieval;
import org.lemurproject.galago.core.parse.Document;
import org.lemurproject.galago.core.retrieval.processing.ProcessingModel;
import org.lemurproject.galago.core.retrieval.query.Node;
import javax.annotation.Nonnull;
import java.io.*;
import java.util.*;
/**
* Base results class Wrapper for a list of results, and provides some utility
* functions for merging several results
*
* @author sjh
*/
public class Results implements Serializable {
public transient Retrieval retrieval;
public Node inputQuery;
public List<ScoredDocument> scoredDocuments;
public Class<? extends ProcessingModel> processingModel;
// empty construction -- a
public Results(Retrieval retrieval) {
this.retrieval = retrieval;
this.scoredDocuments = new ArrayList<>();
}
public Results(Retrieval retrieval, Node query) {
this.retrieval = retrieval;
this.inputQuery = query;
this.scoredDocuments = new ArrayList<>();
}
public Results(Retrieval retrieval, Node query, List<ScoredDocument> scoredDocuments) {
this.retrieval = retrieval;
this.inputQuery = query;
this.scoredDocuments = scoredDocuments;
}
/**
* When performing passage retrieval, it's probably convenient to have this method.
* @return a list of results, cast to ScoredPassages.
*/
@Nonnull
public List<ScoredPassage> asPassages() {
ArrayList<ScoredPassage> passages = new ArrayList<>();
for(ScoredDocument doc : scoredDocuments) {
assert(doc instanceof ScoredPassage);
passages.add((ScoredPassage) doc);
}
return passages;
}
/** Return the set of all retrieved document names. */
@Nonnull
public Set<String> resultSet() {
HashSet<String> names = new HashSet<>();
for (ScoredDocument sdoc : scoredDocuments) {
names.add(sdoc.documentName);
}
return names;
}
/**
* Treat this retrieval as a feature in another model; i.e. turn this ranked list into a map of (DocId -> Score).
* @return Map of {@link ScoredDocument#documentName} to {@link ScoredDocument#score}
*/
@Nonnull
public Map<String,Double> asDocumentFeatures() {
HashMap<String, Double> scores = new HashMap<>(scoredDocuments.size());
for (ScoredDocument sdoc : scoredDocuments) {
scores.put(sdoc.documentName, sdoc.score);
}
return scores;
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o instanceof Results) {
Results other = (Results) o;
return this.scoredDocuments.equals(other.scoredDocuments);
}
return false;
}
/**
* Takes all the elements in this ranked list of results, and pulls the Document for them.
* @param what the document-components object, tells whether you want text, terms, or metadata.
* @return a mapping of Document identifier to Document objects
* @throws IOException if the corpus doesn't exist or is corrupted somehow.
*/
@Nonnull
public Map<String, Document> pullDocuments(@Nonnull Document.DocumentComponents what) throws IOException {
return retrieval.getDocuments(new ArrayList<>(this.resultSet()), what);
}
public void printToTrecrun(PrintStream trecrun, String qid, String system) {
try {
printToTrecrun(new PrintWriter(new OutputStreamWriter(trecrun, "UTF-8")), qid, system);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public void printToTrecrun(PrintWriter trecrun, String qid, String system) {
for (ScoredDocument scoredDocument : this.scoredDocuments) {
trecrun.println(scoredDocument.toTRECformat(qid, system));
}
trecrun.flush();
}
}
|
package org.mockito.internal.matchers;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.Test;
import org.mockitoutil.TestBase;
@SuppressWarnings("unchecked")
public class LocalizedMatcherTest extends TestBase {
@Test
public void shouldMatchTypesWhenActualMatcherHasCorrectType() throws Exception {
//when
ContainsExtraTypeInformation equals10 = new Equals(10);
LocalizedMatcher m = new LocalizedMatcher((Matcher) equals10);
//then
assertTrue(m.typeMatches(10));
assertFalse(m.typeMatches(10L));
}
@Test
public void shouldNotMatchTypesWhenActualMatcherDoesNotHaveCorrectType() throws Exception {
//when
LocalizedMatcher m = new LocalizedMatcher(Any.ANY);
//then
assertFalse(m.typeMatches(10));
}
@Test
public void shouldDescribeWithTypeInfoWhenActualMatcherHasCorrectType() throws Exception {
//when
ContainsExtraTypeInformation equals10 = new Equals(10);
LocalizedMatcher m = new LocalizedMatcher((Matcher) equals10);
//then
//TODO: find usages of StringDescription and use static method
assertEquals("(Integer) 10", StringDescription.toString(m.withExtraTypeInfo()));
}
@Test
public void shouldNotDescribeWithTypeInfoWhenActualMatcherDoesNotHaveCorrectType() throws Exception {
//when
LocalizedMatcher m = new LocalizedMatcher(Any.ANY);
//then
assertSame(m, m.withExtraTypeInfo());
}
}
|
package pl.gda.pg.student.project.client.states;
import pl.gda.pg.student.project.client.objects.Player;
import pl.gda.pg.student.project.libgdxcommon.input.InputProcessorAdapter;
import pl.gda.pg.student.project.libgdxcommon.input.KeyHandler;
public class PlayInputHandler extends InputProcessorAdapter
{
private Player playerObject;
public PlayInputHandler(Player playerObject)
{
this.playerObject = playerObject;
}
public class WKeyHandler implements KeyHandler
{
@Override
public void handle()
{
playerObject.moveUp();
}
}
public class SKeyHandler implements KeyHandler
{
@Override
public void handle()
{
playerObject.moveDown();
}
}
public class AKeyHandler implements KeyHandler
{
@Override
public void handle()
{
playerObject.moveLeft();
}
}
public class DKeyHandler implements KeyHandler
{
@Override
public void handle()
{
playerObject.moveRight();
}
}
}
|
package com.gentics.mesh.test;
import static com.gentics.mesh.util.MeshAssert.assertSuccess;
import static com.gentics.mesh.util.MeshAssert.failingLatch;
import static com.gentics.mesh.util.MeshAssert.latchFor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import com.gentics.mesh.Mesh;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.core.AbstractWebVerticle;
import com.gentics.mesh.core.data.SchemaContainer;
import com.gentics.mesh.core.data.service.I18NUtil;
import com.gentics.mesh.core.rest.common.GenericMessageResponse;
import com.gentics.mesh.core.rest.group.GroupCreateRequest;
import com.gentics.mesh.core.rest.group.GroupResponse;
import com.gentics.mesh.core.rest.group.GroupUpdateRequest;
import com.gentics.mesh.core.rest.node.NodeCreateRequest;
import com.gentics.mesh.core.rest.node.NodeResponse;
import com.gentics.mesh.core.rest.node.NodeUpdateRequest;
import com.gentics.mesh.core.rest.project.ProjectCreateRequest;
import com.gentics.mesh.core.rest.project.ProjectResponse;
import com.gentics.mesh.core.rest.project.ProjectUpdateRequest;
import com.gentics.mesh.core.rest.role.RoleCreateRequest;
import com.gentics.mesh.core.rest.role.RoleResponse;
import com.gentics.mesh.core.rest.role.RoleUpdateRequest;
import com.gentics.mesh.core.rest.schema.SchemaCreateRequest;
import com.gentics.mesh.core.rest.schema.SchemaResponse;
import com.gentics.mesh.core.rest.schema.SchemaUpdateRequest;
import com.gentics.mesh.core.rest.tag.TagCreateRequest;
import com.gentics.mesh.core.rest.tag.TagFamilyCreateRequest;
import com.gentics.mesh.core.rest.tag.TagFamilyReference;
import com.gentics.mesh.core.rest.tag.TagFamilyResponse;
import com.gentics.mesh.core.rest.tag.TagFamilyUpdateRequest;
import com.gentics.mesh.core.rest.tag.TagFieldContainer;
import com.gentics.mesh.core.rest.tag.TagResponse;
import com.gentics.mesh.core.rest.tag.TagUpdateRequest;
import com.gentics.mesh.core.rest.user.UserCreateRequest;
import com.gentics.mesh.core.rest.user.UserResponse;
import com.gentics.mesh.core.rest.user.UserUpdateRequest;
import com.gentics.mesh.demo.DemoDataProvider;
import com.gentics.mesh.etc.RouterStorage;
import com.gentics.mesh.graphdb.NoTrx;
import com.gentics.mesh.rest.MeshRestClient;
import com.gentics.mesh.rest.MeshRestClientHttpException;
import com.gentics.mesh.search.impl.DummySearchProvider;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.impl.EventLoopContext;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.json.JsonObject;
public abstract class AbstractRestVerticleTest extends AbstractDBTest {
protected Vertx vertx;
private int port;
private MeshRestClient client;
@Autowired
private RouterStorage routerStorage;
@Autowired
protected DummySearchProvider searchProvider;
protected NoTrx trx;
@Before
public void setupVerticleTest() throws Exception {
setupData();
port = com.gentics.mesh.test.TestUtil.getRandomPort();
vertx = Mesh.vertx();
routerStorage.addProjectRouter(DemoDataProvider.PROJECT_NAME);
JsonObject config = new JsonObject();
config.put("port", port);
EventLoopContext context = ((VertxInternal) vertx).createEventLoopContext("test", config, Thread.currentThread().getContextClassLoader());
CountDownLatch latch = new CountDownLatch(getVertices().size());
// Inject spring config and start each verticle
for (AbstractWebVerticle verticle : getVertices()) {
verticle.setSpringConfig(springConfig);
verticle.init(vertx, context);
Future<Void> future = Future.future();
verticle.start(future);
future.setHandler(rh -> {
latch.countDown();
});
}
failingLatch(latch);
client = new MeshRestClient("localhost", getPort(), vertx);
trx = db.noTrx();
client.setLogin(user().getUsername(), getUserInfo().getPassword());
resetClientSchemaStorage();
}
@After
public void cleanup() throws Exception {
if (trx != null) {
trx.close();
}
searchProvider.reset();
BootstrapInitializer.clearReferences();
for (AbstractWebVerticle verticle : getVertices()) {
verticle.stop();
}
databaseService.getDatabase().clear();
}
protected void resetClientSchemaStorage() throws IOException {
getClient().getClientSchemaStorage().clear();
for (SchemaContainer container : schemaContainers().values()) {
getClient().getClientSchemaStorage().addSchema(container.getSchema());
}
}
public abstract List<AbstractWebVerticle> getVertices();
@After
public void tearDown() throws Exception {
if (client != null) {
client.close();
}
}
public int getPort() {
return port;
}
public MeshRestClient getClient() {
return client;
}
// User
protected UserResponse createUser(String username) {
UserCreateRequest request = new UserCreateRequest();
request.setUsername(username);
request.setPassword("test1234");
request.setGroupUuid(group().getUuid());
Future<UserResponse> future = getClient().createUser(request);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected UserResponse readUser(String uuid) {
Future<UserResponse> future = getClient().findUserByUuid(uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected UserResponse updateUser(String uuid, String newUserName) {
UserUpdateRequest userUpdateRequest = new UserUpdateRequest();
userUpdateRequest.setUsername(newUserName);
Future<UserResponse> future = getClient().updateUser(uuid, userUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteUser(String uuid) {
Future<GenericMessageResponse> future = getClient().deleteUser(uuid);
latchFor(future);
assertSuccess(future);
}
// Group
protected GroupResponse createGroup(String groupName) {
GroupCreateRequest request = new GroupCreateRequest();
request.setName(groupName);
Future<GroupResponse> future = getClient().createGroup(request);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected GroupResponse readGroup(String uuid) {
Future<GroupResponse> future = getClient().findGroupByUuid(uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected GroupResponse updateGroup(String uuid, String newGroupName) {
GroupUpdateRequest groupUpdateRequest = new GroupUpdateRequest();
groupUpdateRequest.setName(newGroupName);
Future<GroupResponse> future = getClient().updateGroup(uuid, groupUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteGroup(String uuid) {
Future<GenericMessageResponse> future = getClient().deleteGroup(uuid);
latchFor(future);
assertSuccess(future);
}
// Role
protected RoleResponse createRole(String roleName, String groupUuid) {
RoleCreateRequest roleCreateRequest = new RoleCreateRequest();
roleCreateRequest.setName(roleName);
roleCreateRequest.setGroupUuid(groupUuid);
Future<RoleResponse> future = getClient().createRole(roleCreateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected RoleResponse readRole(String uuid) {
Future<RoleResponse> future = getClient().findRoleByUuid(uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteRole(String uuid) {
Future<GenericMessageResponse> future = getClient().deleteRole(uuid);
latchFor(future);
assertSuccess(future);
}
protected RoleResponse updateRole(String uuid, String newRoleName) {
RoleUpdateRequest request = new RoleUpdateRequest();
request.setName(newRoleName);
Future<RoleResponse> future = getClient().updateRole(uuid, request);
latchFor(future);
assertSuccess(future);
return future.result();
}
// Tag
protected TagResponse createTag(String projectName, String tagName, String tagFamilyName) {
TagCreateRequest tagCreateRequest = new TagCreateRequest();
tagCreateRequest.setFields(new TagFieldContainer().setName(tagName));
tagCreateRequest.setTagFamilyReference(new TagFamilyReference().setName(tagFamilyName));
Future<TagResponse> future = getClient().createTag(projectName, tagCreateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected TagResponse readTag(String projectName, String uuid) {
Future<TagResponse> future = getClient().findTagByUuid(projectName, uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected TagResponse updateTag(String projectName, String uuid, String newTagName) {
TagUpdateRequest tagUpdateRequest = new TagUpdateRequest();
tagUpdateRequest.setFields(new TagFieldContainer().setName(newTagName));
Future<TagResponse> future = getClient().updateTag(projectName, uuid, tagUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteTag(String projectName, String uuid) {
Future<GenericMessageResponse> future = getClient().deleteTag(projectName, uuid);
latchFor(future);
assertSuccess(future);
}
// Node
protected NodeResponse createNode(String projectName, String nameField) {
NodeCreateRequest request = new NodeCreateRequest();
Future<NodeResponse> future = getClient().createNode(projectName, request);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected NodeResponse readNode(String projectName, String uuid) {
Future<NodeResponse> future = getClient().findNodeByUuid(projectName, uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteNode(String projectName, String uuid) {
Future<GenericMessageResponse> future = getClient().deleteNode(projectName, uuid);
latchFor(future);
assertSuccess(future);
}
protected NodeResponse updateNode(String projectName, String uuid, String nameFieldValue) {
NodeUpdateRequest nodeUpdateRequest = new NodeUpdateRequest();
Future<NodeResponse> future = getClient().updateNode(projectName, uuid, nodeUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
// TagFamily
protected TagFamilyResponse createTagFamily(String projectName, String tagFamilyName) {
TagFamilyCreateRequest tagFamilyCreateRequest = new TagFamilyCreateRequest();
tagFamilyCreateRequest.setName(tagFamilyName);
Future<TagFamilyResponse> future = getClient().createTagFamily(projectName, tagFamilyCreateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected TagFamilyResponse readTagFamily(String projectName, String uuid) {
Future<TagFamilyResponse> future = getClient().findTagFamilyByUuid(projectName, uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected TagFamilyResponse updateTagFamily(String projectName, String uuid, String newTagFamilyName) {
TagFamilyUpdateRequest tagFamilyUpdateRequest = new TagFamilyUpdateRequest();
tagFamilyUpdateRequest.setName(newTagFamilyName);
Future<TagFamilyResponse> future = getClient().updateTagFamily(projectName, uuid, tagFamilyUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteTagFamily(String projectName, String uuid) {
Future<GenericMessageResponse> future = getClient().deleteTagFamily(projectName, uuid);
latchFor(future);
assertSuccess(future);
}
// Project
protected ProjectResponse createProject(String projectName) {
ProjectCreateRequest projectCreateRequest = new ProjectCreateRequest();
projectCreateRequest.setName(projectName);
Future<ProjectResponse> future = getClient().createProject(projectCreateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected ProjectResponse readProject(String uuid) {
Future<ProjectResponse> future = getClient().findProjectByUuid(uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected ProjectResponse updateProject(String uuid, String projectName) {
ProjectUpdateRequest projectUpdateRequest = new ProjectUpdateRequest();
projectUpdateRequest.setName(projectName);
Future<ProjectResponse> future = getClient().updateProject(uuid, projectUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteProject(String uuid) {
Future<GenericMessageResponse> future = getClient().deleteProject(uuid);
latchFor(future);
assertSuccess(future);
}
// Schema
protected SchemaResponse createSchema(String schemaName) {
SchemaCreateRequest schemaCreateRequest = new SchemaCreateRequest();
schemaCreateRequest.setName(schemaName);
schemaCreateRequest.setDisplayField("name");
schemaCreateRequest.setDescription("Descriptive text");
Future<SchemaResponse> future = getClient().createSchema(schemaCreateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected SchemaResponse readSchema(String uuid) {
Future<SchemaResponse> future = getClient().findSchemaByUuid(uuid);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected SchemaResponse updateSchema(String uuid, String schemaName) {
SchemaUpdateRequest schemaUpdateRequest = new SchemaUpdateRequest();
schemaUpdateRequest.setName(schemaName);
Future<SchemaResponse> future = getClient().updateSchema(uuid, schemaUpdateRequest);
latchFor(future);
assertSuccess(future);
return future.result();
}
protected void deleteSchema(String uuid) {
Future<GenericMessageResponse> future = getClient().deleteSchema(uuid);
latchFor(future);
assertSuccess(future);
}
// Microschema
public void assertEqualsSanitizedJson(String msg, String expectedJson, String unsanitizedResponseJson) {
String sanitizedJson = unsanitizedResponseJson.replaceAll("uuid\":\"[^\"]*\"", "uuid\":\"uuid-value\"");
assertEquals(msg, expectedJson, sanitizedJson);
}
protected void expectMessageResponse(String i18nKey, Future<GenericMessageResponse> responseFuture, String... i18nParams) {
assertTrue("The given future has not yet completed.", responseFuture.isComplete());
Locale en = Locale.ENGLISH;
String message = I18NUtil.get(en, i18nKey, i18nParams);
assertEquals("The response message does not match.", message, responseFuture.result().getMessage());
}
protected void expectMessage(Future<?> future, HttpResponseStatus status, String message) {
assertTrue("We expected the future to have failed but it succeeded.", future.failed());
assertNotNull(future.cause());
if (future.cause() instanceof MeshRestClientHttpException) {
MeshRestClientHttpException exception = ((MeshRestClientHttpException) future.cause());
assertEquals(status.code(), exception.getStatusCode());
assertEquals(status.reasonPhrase(), exception.getMessage());
assertNotNull(exception.getResponseMessage());
assertEquals(message, exception.getResponseMessage().getMessage());
} else {
future.cause().printStackTrace();
fail("Unhandled exception");
}
}
protected void expectException(Future<?> future, HttpResponseStatus status, String bodyMessageI18nKey, String... i18nParams) {
Locale en = Locale.ENGLISH;
String message = I18NUtil.get(en, bodyMessageI18nKey, i18nParams);
expectMessage(future, status, message);
}
}
|
package org.opennms.core.test.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.NodeDetail;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.opennms.core.test.MockLogAppender;
import org.opennms.core.xml.CastorUtils;
import org.opennms.core.xml.JaxbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.XMLFilter;
@RunWith(Parameterized.class)
abstract public class XmlTest<T> {
private static final Logger LOG = LoggerFactory.getLogger(XmlTest.class);
private T m_sampleObject;
private Object m_sampleXml;
private String m_schemaFile;
public XmlTest(final T sampleObject, final Object sampleXml, final String schemaFile) {
m_sampleObject = sampleObject;
m_sampleXml = sampleXml;
m_schemaFile = schemaFile;
}
@Before
public void setUp() {
MockLogAppender.setupLogging(true);
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
XMLUnit.setNormalize(true);
}
protected T getSampleObject() {
return m_sampleObject;
}
protected String getSampleXml() throws IOException {
if (m_sampleXml instanceof File) {
return IOUtils.toString(((File)m_sampleXml).toURI());
} else if (m_sampleXml instanceof URI) {
return IOUtils.toString((URI)m_sampleXml);
} else if (m_sampleXml instanceof URL) {
return IOUtils.toString((URL)m_sampleXml);
} else if (m_sampleXml instanceof InputStream) {
return IOUtils.toString((InputStream)m_sampleXml);
} else {
return m_sampleXml.toString();
}
}
protected ByteArrayInputStream getSampleXmlInputStream() throws IOException {
return new ByteArrayInputStream(getSampleXml().getBytes());
}
protected String getSchemaFile() {
return m_schemaFile;
}
@SuppressWarnings("unchecked")
private Class<T> getSampleClass() {
return (Class<T>) getSampleObject().getClass();
}
protected boolean ignoreNamespace(final String namespace) {
return true;
}
protected boolean ignorePrefix(final String prefix) {
return true;
}
protected boolean ignoreDifference(final Difference d) {
return false;
}
protected void validateXmlString(final String xml) throws Exception {
if (getSchemaFile() == null) {
LOG.warn("skipping validation, schema file not set");
return;
}
final SchemaFactory schemaFactory = SchemaFactory.newInstance("http:
final File schemaFile = new File(getSchemaFile());
LOG.debug("Validating using schema file: {}", schemaFile);
final Schema schema = schemaFactory.newSchema(schemaFile);
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setValidating(true);
saxParserFactory.setNamespaceAware(true);
saxParserFactory.setSchema(schema);
assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());
final Validator validator = schema.newValidator();
final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
final Source source = new StreamSource(inputStream);
validator.validate(source);
}
protected String marshalToXmlWithCastor() {
LOG.debug("Reference Object: {}", getSampleObject());
final StringWriter writer = new StringWriter();
CastorUtils.marshalWithTranslatedExceptions(getSampleObject(), writer);
final String xml = writer.toString();
LOG.debug("Castor XML: {}", xml);
return xml;
}
protected String marshalToXmlWithJaxb() {
LOG.debug("Reference Object: {}", getSampleObject());
final StringWriter writer = new StringWriter();
JaxbUtils.marshal(getSampleObject(), writer);
final String xml = writer.toString();
LOG.debug("JAXB XML: {}", xml);
return xml;
}
@Test
public void marshalCastorAndCompareToXml() throws Exception {
final String xml = marshalToXmlWithCastor();
_assertXmlEquals(getSampleXml(), xml);
}
@Test
public void marshalJaxbAndCompareToXml() throws Exception {
final String xml = marshalToXmlWithJaxb();
_assertXmlEquals(getSampleXml(), xml);
}
@Test
public void unmarshalXmlAndCompareToCastor() throws Exception {
final T obj = CastorUtils.unmarshal(getSampleClass(), getSampleXmlInputStream());
LOG.debug("Sample object: {}\n\nCastor object: {}", getSampleObject(), obj);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void unmarshalJaxbMarshalJaxb() throws Exception {
final T obj = JaxbUtils.unmarshal(getSampleClass(), new InputSource(getSampleXmlInputStream()), null);
final String remarshaled = JaxbUtils.marshal(obj);
_assertXmlEquals(getSampleXml(), remarshaled);
}
@Test
public void marshalJaxbUnmarshalJaxb() throws Exception {
final String xml = marshalToXmlWithJaxb();
final T obj = JaxbUtils.unmarshal(getSampleClass(), xml);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void unmarshalCastorMarshalCastor() throws Exception {
final T obj = CastorUtils.unmarshal(getSampleClass(), getSampleXmlInputStream());
final StringWriter writer = new StringWriter();
CastorUtils.marshalWithTranslatedExceptions(obj, writer);
_assertXmlEquals(getSampleXml(), writer.toString());
}
@Test
public void marshalCastorUnmarshalCastor() throws Exception {
final String xml = marshalToXmlWithCastor();
final ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
final T obj = CastorUtils.unmarshal(getSampleClass(), is, false);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void unmarshalXmlAndCompareToJaxb() throws Exception {
LOG.debug("xml: {}", getSampleXml());
final T obj = JaxbUtils.unmarshal(getSampleClass(), new InputSource(getSampleXmlInputStream()), null);
LOG.debug("Sample object: {}\n\nJAXB object: {}", getSampleObject(), obj);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void marshalCastorUnmarshalJaxb() throws Exception {
final String xml = marshalToXmlWithCastor();
final T obj = JaxbUtils.unmarshal(getSampleClass(), xml);
LOG.debug("Generated Object: {}", obj);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void marshalJaxbUnmarshalCastor() throws Exception {
final String xml = marshalToXmlWithJaxb();
final T obj = CastorUtils.unmarshal(getSampleClass(), new ByteArrayInputStream(xml.getBytes()));
LOG.debug("Generated Object: {}", obj);
assertDepthEquals(getSampleObject(), obj);
}
@Test
public void validateCastorObjectAgainstSchema() throws Exception {
org.exolab.castor.xml.Unmarshaller unmarshaller = CastorUtils.getUnmarshaller(getSampleClass());
unmarshaller.setValidation(true);
@SuppressWarnings("unchecked")
T obj = (T) unmarshaller.unmarshal(new InputSource(getSampleXmlInputStream()));
assertNotNull(obj);
}
@Test
public void validateJaxbXmlAgainstSchema() throws Exception {
final String schemaFile = getSchemaFile();
if (schemaFile == null) {
LOG.warn("Skipping validation.");
return;
}
LOG.debug("Validating against XSD: {}", schemaFile);
javax.xml.bind.Unmarshaller unmarshaller = JaxbUtils.getUnmarshallerFor(getSampleClass(), null, true);
final SchemaFactory factory = SchemaFactory.newInstance("http:
final Schema schema = factory.newSchema(new StreamSource(schemaFile));
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(final ValidationEvent event) {
LOG.warn("Received validation event: {}", event, event.getLinkedException());
return false;
}
});
try {
final InputSource inputSource = new InputSource(getSampleXmlInputStream());
final XMLFilter filter = JaxbUtils.getXMLFilterForClass(getSampleClass());
final SAXSource source = new SAXSource(filter, inputSource);
@SuppressWarnings("unchecked")
T obj = (T) unmarshaller.unmarshal(source);
assertNotNull(obj);
} finally {
unmarshaller.setSchema(null);
}
}
public static void assertXmlEquals(final String expectedXml, final String actualXml) {
// ugly hack alert!
final XmlTest<Object> test = new XmlTest<Object>(null, null, null) {
};
test._assertXmlEquals(expectedXml, actualXml);
}
protected void _assertXmlEquals(final String expectedXml, final String actualXml) {
final List<Difference> differences = getDifferences(expectedXml, actualXml);
if (differences.size() > 0) {
LOG.debug("XML:\n\n{}\n\n...does not match XML:\n\n{}", expectedXml, actualXml);
}
assertEquals("number of XMLUnit differences between the expected xml and the actual xml should be 0", 0, differences.size());
}
public static void assertXpathDoesNotMatch(final String xml, final String expression) throws XPathExpressionException {
assertXpathDoesNotMatch(null, xml, expression);
}
public static void assertXpathDoesNotMatch(final String description, final String xml, final String expression) throws XPathExpressionException {
final NodeList nodes = xpathGetNodesMatching(xml, expression);
assertTrue(description == null? ("Must get at least one node back from the query '" + expression + "'") : description, nodes == null || nodes.getLength() == 0);
}
public static void assertXpathMatches(final String xml, final String expression) throws XPathExpressionException {
assertXpathMatches(null, xml, expression);
}
public static void assertXpathMatches(final String description, final String xml, final String expression) throws XPathExpressionException {
final NodeList nodes = xpathGetNodesMatching(xml, expression);
assertTrue(description == null? ("Must get at least one node back from the query '" + expression + "'") : description, nodes != null && nodes.getLength() != 0);
}
protected List<Difference> getDifferences(final String xmlA, final String xmlB) {
DetailedDiff myDiff;
try {
myDiff = new DetailedDiff(XMLUnit.compareXML(xmlA, xmlB));
} catch (final Exception e) {
throw new RuntimeException(e);
}
final List<Difference> retDifferences = new ArrayList<Difference>();
@SuppressWarnings("unchecked")
final List<Difference> allDifferences = myDiff.getAllDifferences();
if (allDifferences.size() > 0) {
DIFFERENCES: for (final Difference d : allDifferences) {
final NodeDetail controlNodeDetail = d.getControlNodeDetail();
final String control = controlNodeDetail.getValue();
final NodeDetail testNodeDetail = d.getTestNodeDetail();
final String test = testNodeDetail.getValue();
if (d.getDescription().equals("namespace URI")) {
if (control != null && !"null".equals(control)) {
if (ignoreNamespace(control.toLowerCase())) {
LOG.trace("Ignoring {}: {}", d.getDescription(), d);
continue DIFFERENCES;
}
}
if (test != null && !"null".equals(test)) {
if (ignoreNamespace(test.toLowerCase())) {
LOG.trace("Ignoring {}: {}", d.getDescription(), d);
continue DIFFERENCES;
}
}
} else if (d.getDescription().equals("namespace prefix")) {
if (control != null && !"null".equals(control)) {
if (ignorePrefix(control.toLowerCase())) {
LOG.trace("Ignoring {}: {}", d.getDescription(), d);
continue DIFFERENCES;
}
}
if (test != null && !"null".equals(test)) {
if (ignorePrefix(test.toLowerCase())) {
LOG.trace("Ignoring {}: {}", d.getDescription(), d);
continue DIFFERENCES;
}
}
} else if (d.getDescription().equals("xsi:schemaLocation attribute")) {
LOG.debug("Schema location '{}' does not match. Ignoring.", controlNodeDetail.getValue() == null? testNodeDetail.getValue() : controlNodeDetail.getValue());
continue DIFFERENCES;
}
if (ignoreDifference(d)) {
LOG.debug("ignoreDifference matched. Ignoring difference: {}: {}", d.getDescription(), d);
continue DIFFERENCES;
} else {
LOG.warn("Found difference: {}: {}", d.getDescription(), d);
retDifferences.add(d);
}
}
}
return retDifferences;
}
protected static NodeList xpathGetNodesMatching(final String xml, final String expression) throws XPathExpressionException {
final XPath query = XPathFactory.newInstance().newXPath();
StringReader sr = null;
InputSource is = null;
NodeList nodes = null;
try {
sr = new StringReader(xml);
is = new InputSource(sr);
nodes = (NodeList)query.evaluate(expression, is, XPathConstants.NODESET);
} finally {
sr.close();
IOUtils.closeQuietly(sr);
}
return nodes;
}
public static void assertDepthEquals(final Object expected, Object actual) {
assertDepthEquals(0, "", expected, actual);
}
private static void assertDepthEquals(final int depth, final String propertyName, final Object expected, Object actual) {
if (expected == null && actual == null) {
return;
} else if (expected == null) {
fail("expected " + propertyName + " was null but actual was not!");
} else if (actual == null) {
fail("actual " + propertyName + " was null but expected was not!");
}
final String assertionMessage = propertyName == null? ("Top-level objects (" + expected.getClass().getName() + ") do not match.") : ("Properties " + propertyName + " do not match.");
if (expected.getClass().getName().startsWith("java") || actual.getClass().getName().startsWith("java")) {
// java primitives, just do assertEquals
if (expected instanceof Object[] || actual instanceof Object[]) {
assertTrue(assertionMessage, Arrays.equals((Object[])expected, (Object[])actual));
} else {
assertEquals(assertionMessage, expected, actual);
}
return;
}
final BeanWrapper expectedWrapper = new BeanWrapperImpl(expected);
final BeanWrapper actualWrapper = new BeanWrapperImpl(actual);
final Set<String> properties = new TreeSet<String>();
for (final PropertyDescriptor descriptor : expectedWrapper.getPropertyDescriptors()) {
properties.add(descriptor.getName());
}
for (final PropertyDescriptor descriptor : actualWrapper.getPropertyDescriptors()) {
properties.add(descriptor.getName());
}
properties.remove("class");
for (final String property : properties) {
final PropertyDescriptor expectedDescriptor = expectedWrapper.getPropertyDescriptor(property);
final PropertyDescriptor actualDescriptor = actualWrapper.getPropertyDescriptor(property);
if (expectedDescriptor != null && actualDescriptor != null) {
// both have descriptors, so walk the sub-objects
Object expectedValue = null;
Object actualValue = null;
try {
expectedValue = expectedWrapper.getPropertyValue(property);
} catch (final Exception e) {
}
try {
actualValue = actualWrapper.getPropertyValue(property);
} catch (final Exception e) {
}
assertDepthEquals(depth + 1, property, expectedValue, actualValue);
} else if (expectedDescriptor != null) {
fail("Should have '" + property + "' property on actual object, but there was none!");
} else if (actualDescriptor != null) {
fail("Should have '" + property + "' property on expected object, but there was none!");
}
}
if (expected instanceof Object[] || actual instanceof Object[]) {
final Object[] expectedArray = (Object[])expected;
final Object[] actualArray = (Object[])actual;
assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
} else {
assertEquals(assertionMessage, expected, actual);
}
}
}
|
package org.treetank.access;
import static com.google.common.base.Objects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.treetank.access.BucketReadTrx.nodeBucketOffset;
import java.io.File;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.treetank.access.conf.ConstructorProps;
import org.treetank.api.IBucketWriteTrx;
import org.treetank.api.IMetaEntry;
import org.treetank.api.INode;
import org.treetank.api.ISession;
import org.treetank.bucket.IConstants;
import org.treetank.bucket.IndirectBucket;
import org.treetank.bucket.MetaBucket;
import org.treetank.bucket.NodeBucket;
import org.treetank.bucket.NodeBucket.DeletedNode;
import org.treetank.bucket.RevisionRootBucket;
import org.treetank.bucket.UberBucket;
import org.treetank.bucket.interfaces.IReferenceBucket;
import org.treetank.exception.TTException;
import org.treetank.exception.TTIOException;
import org.treetank.io.BackendWriterProxy;
import org.treetank.io.IBackendWriter;
import org.treetank.io.LogKey;
import org.treetank.io.LogValue;
/**
* <h1>BucketWriteTrx</h1>
*
* <p>
* See {@link BucketReadTrx}.
* </p>
*/
public final class BucketWriteTrx implements IBucketWriteTrx {
/** Bucket writer to serialize. */
private final BackendWriterProxy mBucketWriter;
/** Reference to the actual uberBucket. */
private UberBucket mNewUber;
/** Reference to the actual revRoot. */
private RevisionRootBucket mNewRoot;
/** Last reference to the actual nameBucket. */
private MetaBucket mNewMeta;
/** Delegate for read access. */
private BucketReadTrx mDelegate;
/** Executor for tracing commit in progress. */
private final ExecutorService mCommitInProgress;
/**
* Standard constructor.
*
*
* @param pSession
* {@link ISession} reference
* @param pUberBucket
* root of resource
* @param pWriter
* writer where this transaction should write to
* @param pRepresentRev
* revision represent
* @throws TTIOException
* if IO Error
*/
protected BucketWriteTrx(final ISession pSession, final UberBucket pUberBucket,
final IBackendWriter pWriter, final long pRepresentRev) throws TTException {
mBucketWriter =
new BackendWriterProxy(pWriter, new File(pSession.getConfig().mProperties
.getProperty(org.treetank.access.conf.ConstructorProps.RESOURCEPATH)),
pSession.getConfig().mNodeFac, pSession.getConfig().mMetaFac);
final long revkey =
BucketReadTrx.dereferenceLeafOfTree(pWriter,
pUberBucket.getReferenceKeys()[IReferenceBucket.GUARANTEED_INDIRECT_OFFSET], pRepresentRev);
final RevisionRootBucket revBucket = (RevisionRootBucket)pWriter.read(revkey);
final MetaBucket metaBucket =
(MetaBucket)pWriter.read(revBucket.getReferenceKeys()[RevisionRootBucket.META_REFERENCE_OFFSET]);
mCommitInProgress = Executors.newSingleThreadExecutor();
mDelegate = new BucketReadTrx(pSession, pUberBucket, revBucket, metaBucket, pWriter);
setUpTransaction(pUberBucket, revBucket, metaBucket, pSession, pRepresentRev, mBucketWriter);
}
/**
* {@inheritDoc}
*/
public long setNode(final INode pNode) throws TTException {
checkState(!mDelegate.isClosed(), "Transaction already closed");
// Allocate node key and increment node count.
final long nodeKey = pNode.getNodeKey();
final long seqBucketKey = nodeKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[3];
final int nodeBucketOffset = nodeBucketOffset(nodeKey);
final LogValue container = prepareNodeBucket(nodeKey);
final NodeBucket modified = ((NodeBucket)container.getModified());
final NodeBucket complete = ((NodeBucket)container.getComplete());
modified.setNode(nodeBucketOffset, pNode);
complete.setNode(nodeBucketOffset, pNode);
mBucketWriter.put(new LogKey(false, IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT.length, seqBucketKey),
container);
return nodeKey;
}
/**
* {@inheritDoc}
*/
@Override
public void removeNode(final INode pNode) throws TTException {
checkState(!mDelegate.isClosed(), "Transaction already closed");
checkNotNull(pNode);
final long nodeBucketKey = pNode.getNodeKey() >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[3];
LogValue container = prepareNodeBucket(pNode.getNodeKey());
final INode delNode = new DeletedNode(pNode.getNodeKey());
((NodeBucket)container.getComplete()).setNode(nodeBucketOffset(pNode.getNodeKey()), delNode);
((NodeBucket)container.getModified()).setNode(nodeBucketOffset(pNode.getNodeKey()), delNode);
mBucketWriter.put(
new LogKey(false, IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT.length, nodeBucketKey), container);
}
/**
* {@inheritDoc}
*/
public INode getNode(final long pNodeKey) throws TTIOException {
checkState(!mDelegate.isClosed(), "Transaction already closed");
// Calculate bucket and node part for given nodeKey.
final long nodeBucketKey = pNodeKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[3];
final int nodeBucketOffset = nodeBucketOffset(pNodeKey);
final LogKey key =
new LogKey(false, IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT.length, nodeBucketKey);
LogValue container = mBucketWriter.get(key);
INode item = null;
// Bucket was modified...
if (container.getModified() != null) {
// ..check if the real node was touched and set it or..
if (((NodeBucket)container.getModified()).getNode(nodeBucketOffset) == null) {
item = ((NodeBucket)container.getComplete()).getNode(nodeBucketOffset);
}// ..take the node from the complete status of the page.
else {
item = ((NodeBucket)container.getModified()).getNode(nodeBucketOffset);
}
checkNotNull(item, "Item must be set!");
item = mDelegate.checkItemIfDeleted(item);
}// ...bucket was modified within a former version,...
else {
// check the former version as..
container = mBucketWriter.getFormer(key);
// ..modified element within this version or...
if (container.getModified() != null) {
// ..check if the real node was touched and set it or..
if (((NodeBucket)container.getModified()).getNode(nodeBucketOffset) == null) {
item = ((NodeBucket)container.getComplete()).getNode(nodeBucketOffset);
}// ..take the node from the complete status of the page.
else {
item = ((NodeBucket)container.getComplete()).getNode(nodeBucketOffset);
}
checkNotNull(item, "Item must be set!");
item = mDelegate.checkItemIfDeleted(item);
}// bucket was modified long long before, read it normally.
else {
item = mDelegate.getNode(pNodeKey);
}
}
return item;
}
/**
*
* {@inheritDoc}
*
* @throws ExecutionException
* @throws InterruptedException
*/
@Override
public void commit() throws TTException {
checkState(!mDelegate.isClosed(), "Transaction already closed");
mDelegate.mSession.waitForRunningCommit();
final UberBucket uber = UberBucket.copy(mNewUber);
final MetaBucket meta = MetaBucket.copy(mNewMeta);
final RevisionRootBucket rev = RevisionRootBucket.copy(mNewRoot);
final Future<Void> commitInProgress = mBucketWriter.commit(uber, meta, rev);
mDelegate.mSession.setRunningCommit(mCommitInProgress.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
// serializing of new UberPage including its Subtree is concluded.
commitInProgress.get();
((Session)mDelegate.mSession).setLastCommittedUberBucket(uber);
mDelegate = new BucketReadTrx(mDelegate.mSession, uber, rev, meta, mBucketWriter);
mBucketWriter.closeFormerLog();
return null;
}
}));
mDelegate.mSession.waitForRunningCommit();
setUpTransaction(uber, rev, meta, mDelegate.mSession, uber.getRevisionNumber(), mBucketWriter);
}
public void clearLog() throws TTIOException {
mBucketWriter.close();
}
/**
* {@inheritDoc}
*/
@Override
public boolean close() throws TTIOException {
mCommitInProgress.shutdown();
if (!mDelegate.isClosed()) {
mDelegate.close();
try {
// Try to close the log.
// It may already be closed if a commit
// was the last operation.
mBucketWriter.close();
} catch (IllegalStateException e) {
// Do nothing
}
mDelegate.mSession.deregisterBucketTrx(this);
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public long incrementNodeKey() {
checkState(!mDelegate.isClosed(), "Transaction already closed");
return mNewRoot.incrementMaxNodeKey();
}
/**
* {@inheritDoc}
*/
@Override
public long getRevision() throws TTIOException {
checkState(!mDelegate.isClosed(), "Transaction already closed");
return mNewRoot.getRevision();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return mDelegate.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public MetaBucket getMetaBucket() {
checkState(!mDelegate.isClosed(), "Transaction already closed");
return mNewMeta;
}
private LogValue prepareNodeBucket(final long pNodeKey) throws TTException {
final long seqNodeBucketKey = pNodeKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[3];
final LogKey key =
new LogKey(false, IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT.length, seqNodeBucketKey);
// See if on nodeBucketLevel, there are any buckets.
LogValue container = mBucketWriter.get(key);
// if not,...
if (container.getModified() == null) {
// ..start preparing a new container to be logged
final LogKey indirectKey = preparePathToLeaf(false, mNewRoot, pNodeKey);
final LogValue indirectContainer = mBucketWriter.get(indirectKey);
final int nodeOffset = nodeBucketOffset(seqNodeBucketKey);
final long bucketKey =
((IndirectBucket)indirectContainer.getModified()).getReferenceKeys()[nodeOffset];
final long newBucketKey = mNewUber.incrementBucketCounter();
// if there is not any bucket already existing...
if (bucketKey != 0) {
// ...just denote the number of elements necessary to restore (only for visibility reasons).
final int revToRestore =
Integer.parseInt(mDelegate.mSession.getConfig().mProperties
.getProperty(ConstructorProps.NUMBERTORESTORE));
final LogValue formerModified = mBucketWriter.getFormer(key);
NodeBucket[] buckets;
// Look, if a former log is currently in process to be written...
if (formerModified.getModified() != null) {
final NodeBucket currentlyInProgress = (NodeBucket)formerModified.getModified();
// ..and combine them with the former buckets to get the entire status
final NodeBucket[] formerBuckets = mDelegate.getSnapshotBuckets(seqNodeBucketKey, true);
buckets = new NodeBucket[formerBuckets.length + 1];
buckets[0] = currentlyInProgress;
System.arraycopy(formerBuckets, 0, buckets, 1, formerBuckets.length);
}// if the bucket is not currently in process,..
else {
// ...just read from the persistent storage
buckets = mDelegate.getSnapshotBuckets(seqNodeBucketKey, false);
}
// check that the number of buckets are valid and return the entire bucket.
checkState(buckets.length > 0);
container =
mDelegate.mSession.getConfig().mRevision.combineBucketsForModification(revToRestore,
newBucketKey, buckets, mNewRoot.getRevision() % revToRestore == 0);
}// ...if no bucket is existing, create an entirely new one.
else {
final NodeBucket newBucket = new NodeBucket(newBucketKey, IConstants.NULL_NODE);
container = new LogValue(newBucket, newBucket);
}
((IndirectBucket)indirectContainer.getModified()).setReferenceKey(nodeOffset, newBucketKey);
mBucketWriter.put(indirectKey, indirectContainer);
mBucketWriter.put(key, container);
}
return container;
}
/**
* Getting a {@link LogKey} containing the last IndirectBucket with the reference to any new/modified
* bucket.
*
* @param pIsRootLevel
* is this dereferencing walk based on the the search after a RevRoot or a NodeBucket. Needed
* because of the same keys in both subtrees.
* @param pBucket
* where to start the tree-walk: either from an UberBucket (related to new
* RevisionRootBuckets) or from a RevisionRootBucket (related to new NodeBuckets).
* @param pElementKey
* key to be dereferenced
* @return the key the container representing the last level
* @throws TTException
*/
private LogKey preparePathToLeaf(final boolean pIsRootLevel, final IReferenceBucket pBucket,
final long pElementKey) throws TTException {
// computing the ordernumbers within all level. The ordernumbers are the position in the sequence of
// all buckets within the same level.
// ranges are for level 0: 0-127; level 1: 0-16383; level 2: 0-2097151; level 3: 0-268435455; ;level
// 4: 0-34359738367
long seqBucketKey = -1;
// since the revision points to a bucket, the sequence-key bases on the last indirect-layer directly
// within the search after a revision,...
if (pIsRootLevel) {
seqBucketKey = pElementKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[3];
} // ...whereas one layer above is used for the nodes based on the offsets pointing to nodes
// instead of buckets.
else {
seqBucketKey = pElementKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[2];
}
long[] orderNumber = new long[IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT.length];
for (int level = 0; level < orderNumber.length; level++) {
orderNumber[level] = seqBucketKey >> IConstants.INP_LEVEL_BUCKET_COUNT_EXPONENT[level];
}
IReferenceBucket bucket = null;
IReferenceBucket parentBucket = pBucket;
LogKey key = null;
LogKey parentKey = new LogKey(pIsRootLevel, -1, 0);
// Iterate through all levels...
for (int level = 0; level < orderNumber.length; level++) {
// ...see if the actual bucket requested is already in the log
key = new LogKey(pIsRootLevel, level, orderNumber[level]);
LogValue container = mBucketWriter.get(key);
// if the bucket is not existing,..
if (container.getModified() == null) {
// ..create a new bucket
final long newKey = mNewUber.incrementBucketCounter();
bucket = new IndirectBucket(newKey);
// compute the offset of the new bucket
int offset = nodeBucketOffset(orderNumber[level]);
// if there existed the same bucket in former versions in a former log or
container = mBucketWriter.getFormer(key);
IReferenceBucket oldBucket = null;
if (container.getModified() != null) {
oldBucket = (IReferenceBucket)container.getModified();
}
// over the former log or the offset within
// the parent...
else if (parentBucket.getReferenceKeys()[offset] != 0) {
oldBucket = (IReferenceBucket)mBucketWriter.read(parentBucket.getReferenceKeys()[offset]);
}
// ..copy all references to the new log.
if (oldBucket != null) {
for (int i = 0; i < oldBucket.getReferenceKeys().length; i++) {
bucket.setReferenceKey(i, oldBucket.getReferenceKeys()[i]);
}
}
// Set the newKey on the computed offset...
parentBucket.setReferenceKey(offset, newKey);
// .. and put the parent-reference to the log...
container = new LogValue(parentBucket, parentBucket);
// ..if the parent is not referenced as UberBucket or RevisionRootBucket within the Wtx
// itself...
// if (level > 0) {
mBucketWriter.put(parentKey, container);
// ..but set the reference of the current bucket in every case.
container = new LogValue(bucket, bucket);
mBucketWriter.put(key, container);
} // if the bucket is already in the log, get it simply from the log.
else {
bucket = (IReferenceBucket)container.getModified();
}
// finally, set the new bucketkey for the next level
parentKey = key;
parentBucket = bucket;
}
// Return reference to leaf of indirect tree.
return key;
}
private void setUpTransaction(final UberBucket pUberOld, final RevisionRootBucket pRootToRepresent,
final MetaBucket pMetaOld, final ISession pSession, final long pRepresentRev,
final BackendWriterProxy pWriter) throws TTException {
mNewUber =
new UberBucket(pUberOld.getBucketCounter() + 1, pUberOld.getRevisionNumber() + 1, pUberOld
.getBucketCounter() + 1);
mNewUber.setReferenceKey(IReferenceBucket.GUARANTEED_INDIRECT_OFFSET,
pUberOld.getReferenceKeys()[IReferenceBucket.GUARANTEED_INDIRECT_OFFSET]);
// Prepare indirect tree to hold reference to prepared revision root
// nodeBucketReference.
final LogKey indirectKey = preparePathToLeaf(true, mNewUber, mNewUber.getRevisionNumber());
final LogValue indirectContainer = mBucketWriter.get(indirectKey);
final int offset = nodeBucketOffset(mNewUber.getRevisionNumber());
// Get previous revision root bucket and using this data to initialize a fresh revision root including
// the pointers.
mNewRoot =
new RevisionRootBucket(mNewUber.incrementBucketCounter(), pRepresentRev + 1, pRootToRepresent
.getMaxNodeKey());
mNewRoot.setReferenceKey(IReferenceBucket.GUARANTEED_INDIRECT_OFFSET, pRootToRepresent
.getReferenceKeys()[IReferenceBucket.GUARANTEED_INDIRECT_OFFSET]);
// setting the new revRoot to the correct offset
((IndirectBucket)indirectContainer.getModified()).setReferenceKey(offset, mNewRoot.getBucketKey());
mBucketWriter.put(indirectKey, indirectContainer);
// Setting up a new metabucket and link it to the new root
Map<IMetaEntry, IMetaEntry> oldMap = pMetaOld.getMetaMap();
mNewMeta = new MetaBucket(mNewUber.incrementBucketCounter());
for (IMetaEntry key : oldMap.keySet()) {
mNewMeta.setEntry(key, oldMap.get(key));
}
mNewRoot.setReferenceKey(RevisionRootBucket.META_REFERENCE_OFFSET, mNewMeta.getBucketKey());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return toStringHelper(this).add("mDelegate", mDelegate).add("mBucketWriterProxy", mBucketWriter).add(
"mRootBucket", mNewRoot).add("mDelegate", mDelegate).toString();
}
}
|
package net.trajano.ms.examplegw;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;
public class Gateway extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(final String[] args) {
Vertx.vertx().deployVerticle(new Gateway());
}
@Override
public void start() throws Exception {
final Router router = Router.router(vertx);
final HttpClient client = vertx.createHttpClient(new HttpClientOptions());
router.route("/hello").handler(event -> {
final HttpServerResponse response = event.response();
response.putHeader("content-type", "text/plain");
response.end("Hello World!");
});
router.routeWithRegex("/v1/.*").handler(event -> {
final HttpServerRequest req = event.request();
final String uri = req.uri().substring("/v1".length());
System.out.println("Proxying request: " + uri);
final HttpClientRequest c_req = client.request(req.method(), 8080, "localhost", uri, c_res -> {
System.out.println("Proxying response: " + c_res.statusCode());
req.response().setChunked(true);
req.response().setStatusCode(c_res.statusCode());
req.response().headers().setAll(c_res.headers());
c_res.handler(data -> {
System.out.println("Proxying response body inside: " + data.toString("ISO-8859-1"));
req.response().write(data);
});
c_res.endHandler((v) -> req.response().end());
});
c_req.setChunked(true);
c_req.headers().setAll(req.headers());
req.handler(data -> {
System.out.println("Proxying request body " + data.toString("ISO-8859-1"));
c_req.write(data);
});
req.endHandler((v) -> c_req.end());
});
vertx.createHttpServer()
.requestHandler(req -> {
router.accept(req);
})
.listen(8180);
}
}
|
package ru.stqa.pft.sandbox;
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
|
package org.ossnipes.snipes.console;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Console
{
public static int DEFAULT_PORT = 9001;
public Console(String[] args)
{
for (String s : args)
{
if (s.equalsIgnoreCase("--debug") || s.equalsIgnoreCase("-d"))
{
DEBUG = true;
}
}
debug("Finished parsing command line arguments.");
_cm = new ConsoleManager(new Scanner(System.in));
String server = _cm.getConsoleLine("Please enter the bot's IP/host: ");
if (server == null || server.isEmpty())
{
System.err.println("Unable to get server name from STDIN.");
System.exit(1);
}
String serverHost = null;
int port = DEFAULT_PORT;
String[] serverSplit = server.split(":");
if (serverSplit.length > 2 || serverSplit.length == 0)
{
System.err.println("Ill formatted server name.");
System.exit(2);
}
else if (serverSplit.length == 1)
{
serverHost = serverSplit[0];
}
else if (serverSplit.length == 2)
{
serverHost = serverSplit[0];
try
{
port = Integer.parseInt(serverSplit[1]);
} catch (NumberFormatException e)
{
System.err.println("Ill formatted port.");
System.exit(3);
}
}
try {
_sm = new SocketManager(new Socket(serverHost, port));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverHost);
System.exit(4);
} catch (IOException e) {
System.err.println("Unknown IOException while connecting to NoIRCMan server. Message: " + e.getMessage() + ".");
System.exit(5);
}
String s = null;
try {
debug("Calling recv() to wait for HELLO packet.");
s = _sm.recv();
debug("Line received. Line: " + s);
} catch (IOException e) {
debug("Could not receive line");
System.err.println("Unable to receive line from NoIRCMan server.");
System.exit(6);
}
if (s == null)
{
debug("Null line received from server.");
System.err.println("Unable to receive line from NoIRCMan server.");
System.exit(6);
}
if (s.equalsIgnoreCase("HELLO"))
{
String user = _cm.getConsoleLine("Please enter your NoIRCMan username: ");
String pass = _cm.getConsoleLine("Please enter your NoIRCMan password [default blank]: ");
if (user == null)
{
System.err.println("Unable to get username from STDIN.");
System.exit(1);
}
if (pass == null)
{
System.err.println("Unable to get password from STDIN.");
System.exit(1);
}
if (pass.isEmpty())
{
pass = "-";
}
_sm.sendln("HELLO");
_sm.sendln(user);
_sm.sendln(pass);
try {
String response = _sm.recv();
if (response.equalsIgnoreCase("GOODBYE"))
{
System.err.println("Incorrect username or password.");
System.exit(7);
}
else if (response.equalsIgnoreCase("WELCOME"))
{
System.out.println("Username and password were correct. You may now begin typing commands.");
}
else
{
System.err.println("Incorrect protocol response.");
System.exit(8);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
System.err.println("Did not receive expected HELLO command from NoIRCMan server. Received command: " + s);
}
startConsoleLoop();
}
private void startConsoleLoop() {
boolean running = true;
while (running)
{
String line = _cm.getConsoleLine(">>> ");
String[] lineSplit = line.split(" ");
try
{
if (line.equalsIgnoreCase("hw"))
{
_sm.sendln("SAYHELLO");
processCommand(_sm.recv());
}
else if (line.equalsIgnoreCase("exit"))
{
System.exit(0);
}
else if (lineSplit[0].equalsIgnoreCase("PROTORAW"))
{
if (lineSplit.length < 2)
{
System.err.println("Incorrect syntax for PROTORAW command. Use like: PROTORAW <raw protocol command>");
}
if (lineSplit[1].isEmpty())
{
System.err.println("Cannot send an empty line.");
}
String s = line.substring(line.indexOf(' ') + 1);
debug("Sending raw command " + s);
_sm.sendln(s);
// Account for network lag.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Oh well...
}
}
else if (lineSplit[0].equalsIgnoreCase("recv"))
{
if (lineSplit.length > 2)
{
System.err.println("Incorrect syntax for recv command. Use like: recv [optional number of lines]");
}
else if (lineSplit.length == 1)
{
System.out.println(_sm.recv());
}
else
{
try
{
int num = Integer.parseInt(lineSplit[1]);
if (num > 10)
{
String s;
while ((s = _cm.getConsoleLine("Are you sure you want to receive " + num + " lines? This will block the program until " + num +
" lines are received [Y/N]: ")).equalsIgnoreCase("Y") || !s.equalsIgnoreCase("N"));
if (s.equalsIgnoreCase("N"))
{
return;
}
}
int i = 0;
while (i <= num)
{
System.out.println(_sm.recv());
}
} catch (NumberFormatException e)
{
System.err.println(lineSplit[1] + " is not a valid integer.");
}
}
}
} catch (IOException e)
{
System.err.println("Error while receiving line from the server.");
}
}
}
private void processCommand(String recv) throws IOException
{
if (recv == null)
{
System.err.println("Server closed connection unexpectedly.");
}
else if (recv.equalsIgnoreCase("PRNT"))
{
System.out.println(_sm.recv());
}
}
public static void main(String args[])
{
new Console(args);
}
public void debug(String line)
{
if (DEBUG)
{
_l.log(Level.INFO, line);
}
}
private Logger _l = Logger.getLogger(this.getClass().getCanonicalName());
private ConsoleManager _cm;
private SocketManager _sm;
private boolean DEBUG = false;
}
|
package com.yydcdut.sdlv;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
public class SlideAndDragListView<T> extends DragListView<T> implements WrapperAdapter.OnAdapterSlideListenerProxy,
WrapperAdapter.OnAdapterMenuClickListenerProxy, Handler.Callback {
/* Handler Message */
private static final int MSG_WHAT_LONG_CLICK = 1;
/* Handler message */
private static final long CLICK_LONG_TRIGGER_TIME = 1000;
/* onTouch */
private static final int STATE_NOTHING = -1;
private static final int STATE_DOWN = 0;
private static final int STATE_LONG_CLICK = 1;
private static final int STATE_SCROLL = 2;//SCROLL
private static final int STATE_LONG_CLICK_FINISH = 3;
private static final int STATE_MORE_FINGERS = 4;
private int mState = STATE_NOTHING;
private static final int RETURN_SCROLL_BACK_OWN = 1;
private static final int RETURN_SCROLL_BACK_OTHER = 2;
private static final int RETURN_SCROLL_BACK_CLICK_MENU_BUTTON = 3;//itemmenuButton
private static final int RETURN_SCROLL_BACK_NOTHING = 0;
private Vibrator mVibrator;
/* handler */
private Handler mHandler;
/* itemClick */
private boolean mIsWannaTriggerClick = true;
private int mXDown;
private int mYDown;
/* Menu */
private Menu mMenu;
/* WrapperAdapter */
private WrapperAdapter mWrapperAdapter;
private int mShortestDistance = 25;
private OnSlideListener mOnSlideListener;
private OnMenuItemClickListener mOnMenuItemClickListener;
private OnListItemLongClickListener mOnListItemLongClickListener;
private OnListItemClickListener mOnListItemClickListener;
private OnItemDeleteListener mOnItemDeleteListener;
public SlideAndDragListView(Context context) {
this(context, null);
}
public SlideAndDragListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlideAndDragListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
mHandler = new Handler(this);
// mShortestDistance = ViewConfiguration.get(context).getScaledDoubleTapSlop();
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_WHAT_LONG_CLICK:
if (mState == STATE_LONG_CLICK) {//msgstateLong Click
//long click
mState = STATE_LONG_CLICK_FINISH;
int position = msg.arg1;
//view
View view = getChildAt(position - getFirstVisiblePosition());
if (mOnListItemLongClickListener != null) {
mVibrator.vibrate(100);
mOnListItemLongClickListener.onListItemLongClick(view, position);
}
boolean canDrag = scrollBackByDrag(position);
if (canDrag) {
setDragPosition(position);
}
}
break;
}
return true;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mXDown = (int) ev.getX();
mYDown = (int) ev.getY();
//state
mState = STATE_DOWN;
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_2_DOWN:
case MotionEvent.ACTION_POINTER_3_DOWN:
removeLongClickMessage();
mState = STATE_MORE_FINGERS;
return true;
case MotionEvent.ACTION_MOVE:
if (fingerNotMove(ev) && mState != STATE_SCROLL) {
sendLongClickMessage(pointToPosition(mXDown, mYDown));
mState = STATE_LONG_CLICK;
} else if (fingerLeftAndRightMove(ev)) {
removeLongClickMessage();
mState = STATE_SCROLL;
//wrapperAdapter
int position = pointToPosition(mXDown, mYDown);
if (position != AdapterView.INVALID_POSITION) {
mWrapperAdapter.setSlideItemPosition(position);
}
return super.dispatchTouchEvent(ev);
}
break;
case MotionEvent.ACTION_UP:
if (mState == STATE_DOWN || mState == STATE_LONG_CLICK) {
int position = pointToPosition(mXDown, mYDown);
//ScrollBackonListItemClick
int scrollBackState = scrollBack(position, ev.getX());
if (scrollBackState == RETURN_SCROLL_BACK_NOTHING) {
if (mOnListItemClickListener != null && mIsWannaTriggerClick) {
View v = getChildAt(position - getFirstVisiblePosition());
mOnListItemClickListener.onListItemClick(v, position);
}
}
}
removeLongClickMessage();
mState = STATE_NOTHING;
break;
case MotionEvent.ACTION_POINTER_3_UP:
case MotionEvent.ACTION_POINTER_2_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL:
mState = STATE_NOTHING;
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
/**
* item
*
* @param position
* @param x
* @return
*/
private int scrollBack(int position, float x) {
if (mWrapperAdapter.getSlideItemPosition() == position) {
boolean isScrollBack = mWrapperAdapter.returnSlideItemPosition(x);
if (isScrollBack) {
return RETURN_SCROLL_BACK_OWN;
} else {
return RETURN_SCROLL_BACK_CLICK_MENU_BUTTON;
}
} else if (mWrapperAdapter.getSlideItemPosition() != -1) {
mWrapperAdapter.returnSlideItemPosition();
return RETURN_SCROLL_BACK_OTHER;
}
return RETURN_SCROLL_BACK_NOTHING;
}
private boolean scrollBackByDrag(int position) {
if (mWrapperAdapter.getSlideItemPosition() == position) {
return false;
} else if (mWrapperAdapter.getSlideItemPosition() != -1) {
mWrapperAdapter.returnSlideItemPosition();
return true;
}
return true;
}
/**
* removemessage
*/
private void removeLongClickMessage() {
if (mHandler.hasMessages(MSG_WHAT_LONG_CLICK)) {
mHandler.removeMessages(MSG_WHAT_LONG_CLICK);
}
}
/**
* sendMessage
*/
private void sendLongClickMessage(int position) {
if (!mHandler.hasMessages(MSG_WHAT_LONG_CLICK)) {
Message message = new Message();
message.what = MSG_WHAT_LONG_CLICK;
message.arg1 = position;
mHandler.sendMessageDelayed(message, CLICK_LONG_TRIGGER_TIME);
}
}
/**
* 50
*
* @param ev
* @return
*/
private boolean fingerNotMove(MotionEvent ev) {
return (mXDown - ev.getX() < mShortestDistance && mXDown - ev.getX() > -mShortestDistance &&
mYDown - ev.getY() < mShortestDistance && mYDown - ev.getY() > -mShortestDistance);
}
/**
* 5050
*
* @param ev
* @return
*/
private boolean fingerLeftAndRightMove(MotionEvent ev) {
return ((ev.getX() - mXDown > mShortestDistance || ev.getX() - mXDown < -mShortestDistance) &&
ev.getY() - mYDown < mShortestDistance && ev.getY() - mYDown > -mShortestDistance);
}
/**
* Menu
*
* @param menu
*/
public void setMenu(Menu menu) {
mMenu = menu;
}
@Override
public void setAdapter(final ListAdapter adapter) {
if (mMenu == null) {
throw new IllegalArgumentException("Menu");
}
mWrapperAdapter = new WrapperAdapter(getContext(), this, adapter, mMenu) {
@Override
public void onScrollStateChangedProxy(AbsListView view, int scrollState) {
if (scrollState == WrapperAdapter.SCROLL_STATE_IDLE) {
mIsWannaTriggerClick = true;
} else {
mIsWannaTriggerClick = false;
}
}
@Override
public void onScrollProxy(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void onItemDelete(View view, int position) {
if (mOnItemDeleteListener != null) {
mOnItemDeleteListener.onItemDelete(view, position);
}
}
};
mWrapperAdapter.setOnAdapterSlideListenerProxy(this);
mWrapperAdapter.setOnAdapterMenuClickListenerProxy(this);
setRawAdapter(adapter);
super.setAdapter(mWrapperAdapter);
}
@Override
public void addHeaderView(View v, Object data, boolean isSelectable) {
v.setTag(WrapperAdapter.TAG_HEADER_FOOTER, WrapperAdapter.TAG_HEADER);
super.addHeaderView(v, data, isSelectable);
}
@Override
public void addHeaderView(View v) {
v.setTag(WrapperAdapter.TAG_HEADER_FOOTER, WrapperAdapter.TAG_HEADER);
super.addHeaderView(v);
}
@Override
public void addFooterView(View v, Object data, boolean isSelectable) {
v.setTag(WrapperAdapter.TAG_HEADER_FOOTER, WrapperAdapter.TAG_FOOTER);
super.addFooterView(v, data, isSelectable);
}
@Override
public void addFooterView(View v) {
v.setTag(WrapperAdapter.TAG_HEADER_FOOTER, WrapperAdapter.TAG_FOOTER);
super.addFooterView(v);
}
/**
* item
*
* @param listener
*/
public void setOnSlideListener(OnSlideListener listener) {
mOnSlideListener = listener;
}
/**
* item
*/
public interface OnSlideListener {
/**
*
*
* @param view
* @param parentView
* @param position
*/
void onSlideOpen(View view, View parentView, int position, int direction);
/**
*
*
* @param view
* @param parentView
* @param position
*/
void onSlideClose(View view, View parentView, int position, int direction);
}
@Override
public void onSlideOpen(View view, int position, int direction) {
if (mOnSlideListener != null) {
mOnSlideListener.onSlideOpen(view, this, position, direction);
}
}
@Override
public void onSlideClose(View view, int position, int direction) {
if (mOnSlideListener != null) {
mOnSlideListener.onSlideClose(view, this, position, direction);
}
}
/**
* itembutton
*
* @param onMenuItemClickListener
*/
public void setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) {
mOnMenuItemClickListener = onMenuItemClickListener;
}
/**
* itembutton
*/
public interface OnMenuItemClickListener {
/**
*
*
* @param v
* @param itemPosition item
* @param buttonPosition button
* @param direction
* @return Menu
*/
int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction);
}
@Override
public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
if (mOnMenuItemClickListener != null) {
return mOnMenuItemClickListener.onMenuItemClick(v, itemPosition, buttonPosition, direction);
}
return Menu.ITEM_NOTHING;
}
@Deprecated
@Override
public void setOnItemClickListener(OnItemClickListener listener) {
}
/**
*
*
* @param listener
*/
public void setOnListItemClickListener(OnListItemClickListener listener) {
mOnListItemClickListener = listener;
}
public interface OnListItemClickListener {
void onListItemClick(View v, int position);
}
@Deprecated
@Override
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
}
/**
*
*
* @param listener
*/
public void setOnListItemLongClickListener(OnListItemLongClickListener listener) {
mOnListItemLongClickListener = listener;
}
public interface OnListItemLongClickListener {
void onListItemLongClick(View view, int position);
}
public void setOnItemDeleteListener(OnItemDeleteListener onItemDeleteListener) {
mOnItemDeleteListener = onItemDeleteListener;
}
public interface OnItemDeleteListener {
void onItemDelete(View view, int position);
}
}
|
package org.projog.core.function.math;
import static org.projog.core.term.TermUtils.toInt;
import org.projog.core.Calculatable;
import org.projog.core.KnowledgeBase;
import org.projog.core.term.IntegerNumber;
import org.projog.core.term.Term;
public class IntegerDivide implements Calculatable {
@Override
public IntegerNumber calculate(KnowledgeBase kb, Term[] args) {
final int dividend = toInt(args[0]);
final int divisor = toInt(args[1]);
return new IntegerNumber(dividend / divisor);
}
}
|
package de.lmu.ifi.dbs.elki.result.textwriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.data.FeatureVector;
import de.lmu.ifi.dbs.elki.data.HierarchicalClassLabel;
import de.lmu.ifi.dbs.elki.data.LabelList;
import de.lmu.ifi.dbs.elki.data.SimpleClassLabel;
import de.lmu.ifi.dbs.elki.data.model.Model;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.datasource.bundle.SingleObjectBundle;
import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.result.AnnotationResult;
import de.lmu.ifi.dbs.elki.result.CollectionResult;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.IterableResult;
import de.lmu.ifi.dbs.elki.result.OrderingResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.result.SettingsResult;
import de.lmu.ifi.dbs.elki.result.textwriter.naming.NamingScheme;
import de.lmu.ifi.dbs.elki.result.textwriter.naming.SimpleEnumeratingScheme;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterDoubleDoublePair;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectArray;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectComment;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectInline;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterPair;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTextWriteable;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTriple;
import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterVector;
import de.lmu.ifi.dbs.elki.utilities.HandlerList;
import de.lmu.ifi.dbs.elki.utilities.exceptions.UnableToComplyException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.SerializedParameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter;
import de.lmu.ifi.dbs.elki.utilities.pairs.DoubleDoublePair;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import de.lmu.ifi.dbs.elki.utilities.pairs.Triple;
/**
* Class to write a result to human-readable text output
*
* @author Erich Schubert
*
* @apiviz.landmark
* @apiviz.uses TextWriterStream oneway - - writesTo
* @apiviz.composedOf TextWriterWriterInterface
* @apiviz.has NamingScheme
*/
public class TextWriter {
/**
* Logger
*/
private static final Logging logger = Logging.getLogger(TextWriter.class);
/**
* Extension for txt-files.
*/
public static final String FILE_EXTENSION = ".txt";
/**
* Hash map for supported classes in writer.
*/
public final static HandlerList<TextWriterWriterInterface<?>> writers = new HandlerList<TextWriterWriterInterface<?>>();
/**
* Add some default handlers
*/
static {
TextWriterObjectInline trivialwriter = new TextWriterObjectInline();
writers.insertHandler(Object.class, new TextWriterObjectComment());
writers.insertHandler(Pair.class, new TextWriterPair());
writers.insertHandler(DoubleDoublePair.class, new TextWriterDoubleDoublePair());
writers.insertHandler(Triple.class, new TextWriterTriple());
writers.insertHandler(FeatureVector.class, trivialwriter);
// these object can be serialized inline with toString()
writers.insertHandler(String.class, trivialwriter);
writers.insertHandler(Double.class, trivialwriter);
writers.insertHandler(Integer.class, trivialwriter);
writers.insertHandler(String[].class, new TextWriterObjectArray<String>());
writers.insertHandler(Double[].class, new TextWriterObjectArray<Double>());
writers.insertHandler(Integer[].class, new TextWriterObjectArray<Integer>());
writers.insertHandler(BitSet.class, trivialwriter);
writers.insertHandler(Vector.class, new TextWriterVector());
writers.insertHandler(Distance.class, trivialwriter);
writers.insertHandler(SimpleClassLabel.class, trivialwriter);
writers.insertHandler(HierarchicalClassLabel.class, trivialwriter);
writers.insertHandler(LabelList.class, trivialwriter);
writers.insertHandler(DBID.class, trivialwriter);
// Objects that have an own writeToText method.
writers.insertHandler(TextWriteable.class, new TextWriterTextWriteable());
}
/**
* For producing unique filenames.
*/
protected Map<String, Object> filenames = new HashMap<String, Object>();
/**
* Try to find a unique file name.
*
* @param result Result we print
* @param filenamepre File name prefix to use
* @return
*/
protected String getFilename(Object result, String filenamepre) {
if(filenamepre == null || filenamepre.length() == 0) {
filenamepre = "result";
}
int i = 0;
while(true) {
String filename;
if(i > 0) {
filename = filenamepre + "-" + i;
}
else {
filename = filenamepre;
}
Object existing = filenames.get(filename);
if(existing == null || existing == result) {
filenames.put(filename, result);
return filename;
}
i++;
}
}
/**
* Writes a header providing information concerning the underlying database
* and the specified parameter-settings.
*
* @param out the print stream where to write
* @param sr the settings to be written into the header
*/
protected void printSettings(TextWriterStream out, List<SettingsResult> sr) {
out.commentPrintSeparator();
out.commentPrintLn("Settings:");
if(sr != null) {
for(SettingsResult settings : sr) {
Object last = null;
for(Pair<Object, Parameter<?, ?>> setting : settings.getSettings()) {
if(setting.first != last && setting.first != null) {
if(last != null) {
out.commentPrintLn("");
}
String name;
try {
if(setting.first instanceof Class) {
name = ((Class<?>) setting.first).getName();
}
else {
name = setting.first.getClass().getName();
}
if(ClassParameter.class.isInstance(setting.first)) {
name = ((ClassParameter<?>) setting.first).getValue().getName();
}
}
catch(NullPointerException e) {
name = "[null]";
}
out.commentPrintLn(name);
last = setting.first;
}
String name = setting.second.getOptionID().getName();
String value = "[unset]";
try {
if(setting.second.isDefined()) {
value = setting.second.getValueAsString();
}
}
catch(NullPointerException e) {
value = "[null]";
}
out.commentPrintLn(SerializedParameterization.OPTION_PREFIX + name + " " + value);
}
}
}
out.commentPrintSeparator();
out.flush();
}
/**
* Stream output.
*
* @param db Database object
* @param r Result class
* @param streamOpener output stream manager
* @throws UnableToComplyException when no usable results were found
* @throws IOException on IO error
*/
public void output(Database db, Result r, StreamFactory streamOpener) throws UnableToComplyException, IOException {
List<AnnotationResult<?>> ra = null;
List<OrderingResult> ro = null;
List<Clustering<? extends Model>> rc = null;
List<IterableResult<?>> ri = null;
List<SettingsResult> rs = null;
HashSet<Result> otherres = null;
Collection<DBIDs> groups = null;
ra = ResultUtil.getAnnotationResults(r);
ro = ResultUtil.getOrderingResults(r);
rc = ResultUtil.getClusteringResults(r);
ri = ResultUtil.getIterableResults(r);
rs = ResultUtil.getSettingsResults(r);
// collect other results
if(r instanceof HierarchicalResult) {
final List<Result> resultList = ResultUtil.filterResults((HierarchicalResult) r, Result.class);
otherres = new HashSet<Result>(resultList);
otherres.removeAll(ra);
otherres.removeAll(ro);
otherres.removeAll(rc);
otherres.removeAll(ri);
otherres.removeAll(rs);
otherres.remove(db);
Iterator<Result> it = otherres.iterator();
while(it.hasNext()) {
if(it.next() instanceof HierarchicalResult) {
it.remove();
}
}
}
if(ra == null && ro == null && rc == null && ri == null) {
throw new UnableToComplyException("No printable result found.");
}
NamingScheme naming = null;
// Process groups or all data in a flat manner?
if(rc != null && rc.size() > 0) {
groups = new ArrayList<DBIDs>();
for(Cluster<?> c : rc.get(0).getAllClusters()) {
groups.add(c.getIDs());
}
// force an update of cluster names.
naming = new SimpleEnumeratingScheme(rc.get(0));
}
else {
// only 'magically' create a group if we don't have iterators either.
// if(ri == null || ri.size() == 0) {
groups = new ArrayList<DBIDs>();
groups.add(db.getDBIDs());
}
if(ri != null && ri.size() > 0) {
// TODO: associations are not passed to ri results.
for(IterableResult<?> rii : ri) {
writeIterableResult(db, streamOpener, rii, rs);
}
}
if(groups != null && groups.size() > 0) {
for(DBIDs group : groups) {
writeGroupResult(db, streamOpener, group, ra, naming, rs);
}
}
if(ro != null && ro.size() > 0) {
for(OrderingResult ror : ro) {
writeOrderingResult(db, streamOpener, ror, ra, rs);
}
}
if(otherres != null && otherres.size() > 0) {
for(Result otherr : otherres) {
writeOtherResult(db, streamOpener, otherr, rs);
}
}
}
private void printObject(TextWriterStream out, Database db, final DBID objID, List<AnnotationResult<?>> ra) throws UnableToComplyException, IOException {
SingleObjectBundle bundle = db.getBundle(objID);
// Write database element itself.
for(int i = 0; i < bundle.metaLength(); i++) {
Object obj = bundle.data(i);
TextWriterWriterInterface<?> owriter = out.getWriterFor(obj);
if(owriter == null) {
throw new UnableToComplyException("No handler for database object itself: " + obj.getClass().getSimpleName());
}
String lbl = null;
// TODO: ugly compatibility hack...
if(TypeUtil.DBID.isAssignableFromType(bundle.meta(i))) {
lbl = "ID";
}
owriter.writeObject(out, lbl, obj);
}
// print the annotations
if(ra != null) {
for(AnnotationResult<?> a : ra) {
String label = a.getAssociationID().getLabel();
Object value = a.getValueFor(objID);
if(value == null) {
continue;
}
TextWriterWriterInterface<?> writer = out.getWriterFor(value);
if(writer == null) {
// Ignore
continue;
}
writer.writeObject(out, label, value);
}
}
out.flush();
out.flush();
}
private void writeOtherResult(Database db, StreamFactory streamOpener, Result r, List<SettingsResult> rs) throws UnableToComplyException, IOException {
PrintStream outStream = streamOpener.openStream(getFilename(r, r.getShortName()));
TextWriterStream out = new TextWriterStream(outStream, writers);
TextWriterWriterInterface<?> owriter = out.getWriterFor(r);
if(owriter == null) {
throw new UnableToComplyException("No handler for result class: " + r.getClass().getSimpleName());
}
// Write settings preamble
printSettings(out, rs);
// Write data
owriter.writeObject(out, null, r);
out.flush();
}
private void writeGroupResult(Database db, StreamFactory streamOpener, DBIDs group, List<AnnotationResult<?>> ra, NamingScheme naming, List<SettingsResult> sr) throws FileNotFoundException, UnableToComplyException, IOException {
String filename = null;
// for clusters, use naming.
if(group instanceof Cluster) {
if(naming != null) {
filename = filenameFromLabel(naming.getNameFor((Cluster<?>) group));
}
}
PrintStream outStream = streamOpener.openStream(getFilename(group, filename));
TextWriterStream out = new TextWriterStream(outStream, writers);
printSettings(out, sr);
// print group information...
if(group instanceof TextWriteable) {
TextWriterWriterInterface<?> writer = out.getWriterFor(group);
out.commentPrintLn("Group class: " + group.getClass().getCanonicalName());
if(writer != null) {
writer.writeObject(out, null, group);
out.commentPrintSeparator();
out.flush();
}
}
// print ids.
DBIDs ids = group;
Iterator<DBID> iter = ids.iterator();
while(iter.hasNext()) {
printObject(out, db, iter.next(), ra);
}
out.commentPrintSeparator();
out.flush();
}
private void writeIterableResult(Database db, StreamFactory streamOpener, IterableResult<?> ri, List<SettingsResult> sr) throws UnableToComplyException, IOException {
PrintStream outStream = streamOpener.openStream(getFilename(ri, ri.getShortName()));
TextWriterStream out = new TextWriterStream(outStream, writers);
printSettings(out, sr);
// hack to print collectionResult header information
if(ri instanceof CollectionResult<?>) {
final Collection<String> hdr = ((CollectionResult<?>) ri).getHeader();
if(hdr != null) {
for(String header : hdr) {
out.commentPrintLn(header);
}
out.flush();
}
}
Iterator<?> i = ri.iterator();
while(i.hasNext()) {
Object o = i.next();
TextWriterWriterInterface<?> writer = out.getWriterFor(o);
if(writer != null) {
writer.writeObject(out, null, o);
}
out.flush();
}
out.commentPrintSeparator();
out.flush();
}
private void writeOrderingResult(Database db, StreamFactory streamOpener, OrderingResult or, List<AnnotationResult<?>> ra, List<SettingsResult> sr) throws IOException, UnableToComplyException {
PrintStream outStream = streamOpener.openStream(getFilename(or, or.getShortName()));
TextWriterStream out = new TextWriterStream(outStream, writers);
printSettings(out, sr);
Iterator<DBID> i = or.iter(db.getDBIDs());
while(i.hasNext()) {
printObject(out, db, i.next(), ra);
}
out.commentPrintSeparator();
out.flush();
}
/**
* Derive a file name from the cluster label.
*
* @param label cluster label
* @return cleaned label suitable for file names.
*/
private String filenameFromLabel(String label) {
return label.toLowerCase().replaceAll("[^a-zA-Z0-9_.\\[\\]-]", "_");
}
}
|
package de.tub.citydb.modules.kml.controller;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.transform.stream.StreamResult;
import net.opengis.kml._2.BalloonStyleType;
import net.opengis.kml._2.DocumentType;
import net.opengis.kml._2.FolderType;
import net.opengis.kml._2.KmlType;
import net.opengis.kml._2.LatLonAltBoxType;
import net.opengis.kml._2.LineStringType;
import net.opengis.kml._2.LineStyleType;
import net.opengis.kml._2.LinkType;
import net.opengis.kml._2.LodType;
import net.opengis.kml._2.LookAtType;
import net.opengis.kml._2.NetworkLinkType;
import net.opengis.kml._2.ObjectFactory;
import net.opengis.kml._2.PairType;
import net.opengis.kml._2.PlacemarkType;
import net.opengis.kml._2.PolyStyleType;
import net.opengis.kml._2.RegionType;
import net.opengis.kml._2.StyleMapType;
import net.opengis.kml._2.StyleStateEnumType;
import net.opengis.kml._2.StyleType;
import net.opengis.kml._2.ViewRefreshModeEnumType;
import oracle.ord.im.OrdImage;
import org.citygml4j.factory.CityGMLFactory;
import org.citygml4j.model.citygml.CityGMLClass;
import org.citygml4j.util.xml.SAXEventBuffer;
import org.citygml4j.util.xml.SAXWriter;
import org.xml.sax.SAXException;
import de.tub.citydb.api.concurrent.SingleWorkerPool;
import de.tub.citydb.api.concurrent.WorkerPool;
import de.tub.citydb.api.database.DatabaseSrs;
import de.tub.citydb.api.event.Event;
import de.tub.citydb.api.event.EventDispatcher;
import de.tub.citydb.api.event.EventHandler;
import de.tub.citydb.api.gui.BoundingBox;
import de.tub.citydb.api.gui.BoundingBoxCorner;
import de.tub.citydb.config.Config;
import de.tub.citydb.config.internal.Internal;
import de.tub.citydb.config.project.database.Database;
import de.tub.citydb.config.project.database.Database.PredefinedSrsName;
import de.tub.citydb.config.project.database.Workspace;
import de.tub.citydb.config.project.filter.FeatureClass;
import de.tub.citydb.config.project.filter.TiledBoundingBox;
import de.tub.citydb.config.project.filter.Tiling;
import de.tub.citydb.config.project.filter.TilingMode;
import de.tub.citydb.config.project.kmlExporter.Balloon;
import de.tub.citydb.config.project.kmlExporter.BalloonContentMode;
import de.tub.citydb.config.project.kmlExporter.DisplayForm;
import de.tub.citydb.database.DatabaseConnectionPool;
import de.tub.citydb.database.TypeAttributeValueEnum;
import de.tub.citydb.log.Logger;
import de.tub.citydb.modules.common.concurrent.IOWriterWorkerFactory;
import de.tub.citydb.modules.common.event.CounterEvent;
import de.tub.citydb.modules.common.event.CounterType;
import de.tub.citydb.modules.common.event.EventType;
import de.tub.citydb.modules.common.event.InterruptEvent;
import de.tub.citydb.modules.common.event.StatusDialogMessage;
import de.tub.citydb.modules.common.event.StatusDialogTitle;
import de.tub.citydb.modules.common.filter.ExportFilter;
import de.tub.citydb.modules.common.filter.FilterMode;
import de.tub.citydb.modules.kml.concurrent.KmlExportWorkerFactory;
import de.tub.citydb.modules.kml.database.BalloonTemplateHandlerImpl;
import de.tub.citydb.modules.kml.database.Building;
import de.tub.citydb.modules.kml.database.CityFurniture;
import de.tub.citydb.modules.kml.database.CityObjectGroup;
import de.tub.citydb.modules.kml.database.ColladaBundle;
import de.tub.citydb.modules.kml.database.GenericCityObject;
import de.tub.citydb.modules.kml.database.KmlSplitter;
import de.tub.citydb.modules.kml.database.KmlSplittingResult;
import de.tub.citydb.modules.kml.database.LandUse;
import de.tub.citydb.modules.kml.database.PlantCover;
import de.tub.citydb.modules.kml.database.SolitaryVegetationObject;
import de.tub.citydb.modules.kml.database.WaterBody;
import de.tub.citydb.modules.kml.util.CityObject4JSON;
import de.tub.citydb.modules.kml.util.KMLHeaderWriter;
import de.tub.citydb.util.database.DBUtil;
public class KmlExporter implements EventHandler {
private final JAXBContext jaxbKmlContext;
private final JAXBContext jaxbColladaContext;
private final DatabaseConnectionPool dbPool;
private final Config config;
private final EventDispatcher eventDispatcher;
private CityGMLFactory cityGMLFactory;
private ObjectFactory kmlFactory;
private WorkerPool<KmlSplittingResult> kmlWorkerPool;
private SingleWorkerPool<SAXEventBuffer> ioWriterPool;
private KmlSplitter kmlSplitter;
private volatile boolean shouldRun = true;
private AtomicBoolean isInterrupted = new AtomicBoolean(false);
private static final double BORDER_GAP = 0.000001;
private static final String ENCODING = "UTF-8";
private static final Charset CHARSET = Charset.forName(ENCODING);
private final DatabaseSrs WGS84_2D = Database.PREDEFINED_SRS.get(PredefinedSrsName.WGS84_2D);
private BoundingBox tileMatrix;
private BoundingBox wgs84TileMatrix;
private double wgs84DeltaLongitude;
private double wgs84DeltaLatitude;
private static int rows;
private static int columns;
private String path;
private String filename;
private EnumMap<CityGMLClass, Long>featureCounterMap = new EnumMap<CityGMLClass, Long>(CityGMLClass.class);
private long geometryCounter;
private static HashMap<String, CityObject4JSON> alreadyExported;
public KmlExporter (JAXBContext jaxbKmlContext,
JAXBContext jaxbColladaContext,
DatabaseConnectionPool dbPool,
Config config,
EventDispatcher eventDispatcher) {
this.jaxbKmlContext = jaxbKmlContext;
this.jaxbColladaContext = jaxbColladaContext;
this.dbPool = dbPool;
this.config = config;
this.eventDispatcher = eventDispatcher;
kmlFactory = new ObjectFactory();
cityGMLFactory = new CityGMLFactory();
}
public void cleanup() {
eventDispatcher.removeEventHandler(this);
}
public boolean doProcess() {
geometryCounter = 0;
// get config shortcuts
de.tub.citydb.config.project.system.System system = config.getProject().getKmlExporter().getSystem();
// worker pool settings
int minThreads = system.getThreadPool().getDefaultPool().getMinThreads();
int maxThreads = system.getThreadPool().getDefaultPool().getMaxThreads();
// adding listener
eventDispatcher.addEventHandler(EventType.COUNTER, this);
eventDispatcher.addEventHandler(EventType.GEOMETRY_COUNTER, this);
eventDispatcher.addEventHandler(EventType.INTERRUPT, this);
// checking workspace...
Workspace workspace = config.getProject().getDatabase().getWorkspaces().getKmlExportWorkspace();
if (!workspace.getName().toUpperCase().equals("LIVE")) {
boolean workspaceExists = dbPool.existsWorkspace(workspace);
String name = "'" + workspace.getName().trim() + "'";
String timestamp = workspace.getTimestamp().trim();
if (timestamp.trim().length() > 0)
name += " at timestamp " + timestamp;
if (!workspaceExists) {
Logger.getInstance().error("Database workspace " + name + " is not available.");
return false;
} else
Logger.getInstance().info("Switching to database workspace " + name + '.');
}
// check whether spatial indexes are enabled
Logger.getInstance().info("Checking for spatial indexes on geometry columns of involved tables...");
try {
if (!DBUtil.isIndexed("CITYOBJECT", "ENVELOPE") ||
!DBUtil.isIndexed("SURFACE_GEOMETRY", "GEOMETRY")) {
Logger.getInstance().error("Spatial indexes are not activated.");
Logger.getInstance().error("Please use the database tab to activate the spatial indexes.");
return false;
}
}
catch (SQLException e) {
Logger.getInstance().error("Failed to retrieve status of spatial indexes: " + e.getMessage());
return false;
}
String selectedTheme = config.getProject().getKmlExporter().getAppearanceTheme();
if (!selectedTheme.equals(de.tub.citydb.config.project.kmlExporter.KmlExporter.THEME_NONE)) {
try {
for (DisplayForm displayForm : config.getProject().getKmlExporter().getBuildingDisplayForms()) {
if (displayForm.getForm() == DisplayForm.COLLADA && displayForm.isActive()) {
if (!DBUtil.getAppearanceThemeList(workspace).contains(selectedTheme)) {
Logger.getInstance().error("Database does not contain appearance theme \"" + selectedTheme + "\"");
return false;
}
}
}
}
catch (SQLException e) {
Logger.getInstance().error("Generic DB error: " + e.getMessage());
return false;
}
}
boolean balloonCheck = checkBalloonSettings(CityGMLClass.BUILDING);
balloonCheck = checkBalloonSettings(CityGMLClass.WATER_BODY) && balloonCheck;
balloonCheck = checkBalloonSettings(CityGMLClass.LAND_USE) && balloonCheck;
balloonCheck = checkBalloonSettings(CityGMLClass.SOLITARY_VEGETATION_OBJECT) && balloonCheck;
balloonCheck = checkBalloonSettings(CityGMLClass.CITY_FURNITURE) && balloonCheck;
balloonCheck = checkBalloonSettings(CityGMLClass.GENERIC_CITY_OBJECT) && balloonCheck;
balloonCheck = checkBalloonSettings(CityGMLClass.CITY_OBJECT_GROUP) && balloonCheck;
if (!balloonCheck) return false;
// getting export filter
ExportFilter exportFilter = new ExportFilter(config, FilterMode.KML_EXPORT);
boolean isBBoxActive = config.getProject().getKmlExporter().getFilter().getComplexFilter().getTiledBoundingBox().getActive().booleanValue();
// bounding box config
Tiling tiling = config.getProject().getKmlExporter().getFilter().getComplexFilter().getTiledBoundingBox().getTiling();
// create a saxWriter instance
// define indent for xml output and namespace mappings
SAXWriter saxWriter = new SAXWriter();
saxWriter.setIndentString(" ");
saxWriter.setHeaderComment("Written by " + this.getClass().getPackage().getImplementationTitle() + ", version \"" +
this.getClass().getPackage().getImplementationVersion() + '"',
this.getClass().getPackage().getImplementationVendor());
saxWriter.setDefaultNamespace("http:
saxWriter.setPrefix("gx", "http:
saxWriter.setPrefix("atom", "http:
saxWriter.setPrefix("xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");
Properties props = new Properties();
props.put(Marshaller.JAXB_FRAGMENT, new Boolean(true));
path = config.getInternal().getExportFileName().trim();
if (path.lastIndexOf(File.separator) == -1) {
if (path.lastIndexOf(".") == -1) {
filename = path;
}
else {
filename = path.substring(0, path.lastIndexOf("."));
}
path = ".";
}
else {
if (path.lastIndexOf(".") == -1) {
filename = path.substring(path.lastIndexOf(File.separator) + 1);
}
else {
filename = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf("."));
}
path = path.substring(0, path.lastIndexOf(File.separator));
}
if (isBBoxActive && tiling.getMode() != TilingMode.NO_TILING) {
try {
int activeDisplayFormsAmount =
de.tub.citydb.config.project.kmlExporter.KmlExporter.getActiveDisplayFormsAmount(config.getProject().getKmlExporter().getBuildingDisplayForms());
Logger.getInstance().info(String.valueOf(rows * columns * activeDisplayFormsAmount) +
" (" + rows + "x" + columns + "x" + activeDisplayFormsAmount +
") tiles will be generated.");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
else {
rows = 1;
columns = 1;
}
for (DisplayForm displayForm : config.getProject().getKmlExporter().getBuildingDisplayForms()) {
if (!displayForm.isActive()) continue;
alreadyExported = new HashMap<String, CityObject4JSON>();
for (int i = 0; shouldRun && i < rows; i++) {
for (int j = 0; shouldRun && j < columns; j++) {
ConcurrentLinkedQueue<ColladaBundle> buildingQueue = null;
if (displayForm.getForm() >= DisplayForm.COLLADA ||
config.getProject().getKmlExporter().getBuildingBalloon().isBalloonContentInSeparateFile()) {
buildingQueue = new ConcurrentLinkedQueue<ColladaBundle>();
}
File file = null;
OutputStreamWriter fileWriter = null;
ZipOutputStream zipOut = null;
try {
String fileExtension = config.getProject().getKmlExporter().isExportAsKmz() ? ".kmz" : ".kml";
if (isBBoxActive && tiling.getMode() != TilingMode.NO_TILING) {
exportFilter.getBoundingBoxFilter().setActiveTile(i, j);
file = new File(path + File.separator + filename + "_Tile_"
+ i + "_" + j + "_" + displayForm.getName() + fileExtension);
}
else {
file = new File(path + File.separator + filename + "_" + displayForm.getName() + fileExtension);
}
eventDispatcher.triggerEvent(new StatusDialogTitle(file.getName(), this));
// open file for writing
try {
if (config.getProject().getKmlExporter().isExportAsKmz()) {
zipOut = new ZipOutputStream(new FileOutputStream(file));
ZipEntry zipEntry = new ZipEntry("doc.kml");
zipOut.putNextEntry(zipEntry);
fileWriter = new OutputStreamWriter(zipOut, CHARSET);
}
else {
fileWriter = new OutputStreamWriter(new FileOutputStream(file), CHARSET);
}
// set output for SAXWriter
saxWriter.setOutput(new StreamResult(fileWriter), ENCODING);
} catch (IOException ioE) {
Logger.getInstance().error("Failed to open file '" + file.getName() + "' for writing: " + ioE.getMessage());
return false;
}
// create worker pools
// here we have an open issue: queue sizes are fix...
ioWriterPool = new SingleWorkerPool<SAXEventBuffer>(
new IOWriterWorkerFactory(saxWriter),
100,
true);
kmlWorkerPool = new WorkerPool<KmlSplittingResult>(
minThreads,
maxThreads,
new KmlExportWorkerFactory(
jaxbKmlContext,
jaxbColladaContext,
dbPool,
ioWriterPool,
kmlFactory,
cityGMLFactory,
buildingQueue,
config,
eventDispatcher),
300,
false);
// prestart pool workers
ioWriterPool.prestartCoreWorkers();
kmlWorkerPool.prestartCoreWorkers();
// create file header
KMLHeaderWriter kmlHeader = new KMLHeaderWriter(saxWriter);
// ok, preparations done. inform user...
Logger.getInstance().info("Exporting to file: " + file.getAbsolutePath());
// create kml root element
KmlType kmlType = kmlFactory.createKmlType();
JAXBElement<KmlType> kml = kmlFactory.createKml(kmlType);
DocumentType document = kmlFactory.createDocumentType();
if (isBBoxActive && tiling.getMode() != TilingMode.NO_TILING) {
document.setName(filename + "_Tile_" + i + "_" + j + "_" + displayForm.getName());
}
else {
document.setName(filename + "_" + displayForm.getName());
}
document.setOpen(false);
kmlType.setAbstractFeatureGroup(kmlFactory.createDocument(document));
try {
kmlHeader.setRootElement(kml, jaxbKmlContext, props);
kmlHeader.startRootElement();
// make sure header has been written
saxWriter.flush();
if (!config.getProject().getKmlExporter().isOneFilePerObject() ||
config.getProject().getKmlExporter().getFilter().isSetSimpleFilter()) {
addStyle(displayForm);
}
if (isBBoxActive && tiling.getMode() != TilingMode.NO_TILING) {
addBorder(i, j);
}
} catch (JAXBException jaxBE) {
Logger.getInstance().error("I/O error: " + jaxBE.getMessage());
return false;
} catch (SAXException saxE) {
Logger.getInstance().error("I/O error: " + saxE.getMessage());
return false;
}
// get database splitter and start query
kmlSplitter = null;
try {
kmlSplitter = new KmlSplitter(
dbPool,
kmlWorkerPool,
exportFilter,
displayForm,
config);
if (shouldRun)
kmlSplitter.startQuery();
} catch (SQLException sqlE) {
Logger.getInstance().error("SQL error: " + sqlE.getMessage());
return false;
}
try {
if (shouldRun)
kmlWorkerPool.shutdownAndWait();
ioWriterPool.shutdownAndWait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
// write footer element
try {
kmlHeader.endRootElement();
} catch (SAXException saxE) {
Logger.getInstance().error("XML error: " + saxE.getMessage());
return false;
}
eventDispatcher.triggerEvent(new StatusDialogMessage(Internal.I18N.getString("kmlExport.dialog.writingToFile"), this));
// flush sax writer and close file
try {
saxWriter.flush();
if (config.getProject().getKmlExporter().isExportAsKmz()) {
zipOut.closeEntry();
// ZipOutputStream must be accessed sequentially and is not thread-safe
if (buildingQueue != null) {
ColladaBundle colladaBundle = buildingQueue.poll();
while (colladaBundle != null) {
if (colladaBundle.getColladaAsString() != null) {
// File.separator would be wrong here, it MUST be "/"
ZipEntry zipEntry = new ZipEntry(colladaBundle.getBuildingId() + "/"
+ colladaBundle.getBuildingId() + ".dae");
zipOut.putNextEntry(zipEntry);
zipOut.write(colladaBundle.getColladaAsString().getBytes(CHARSET));
zipOut.closeEntry();
}
if (colladaBundle.getExternalBalloonFileContent() != null) {
ZipEntry zipEntry = new ZipEntry(BalloonTemplateHandlerImpl.balloonDirectoryName + "/" + colladaBundle.getBuildingId() + ".html");
zipOut.putNextEntry(zipEntry);
zipOut.write(colladaBundle.getExternalBalloonFileContent().getBytes(CHARSET));
zipOut.closeEntry();
}
if (colladaBundle.getTexOrdImages() != null) {
Set<String> keySet = colladaBundle.getTexOrdImages().keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String imageFilename = iterator.next();
OrdImage texOrdImage = colladaBundle.getTexOrdImages().get(imageFilename);
if (texOrdImage.getContentLength() < 1) continue;
// byte[] ordImageBytes = texOrdImage.getDataInByteArray();
byte[] ordImageBytes = texOrdImage.getBlobContent().getBytes(1, (int)texOrdImage.getBlobContent().length());
ZipEntry zipEntry = imageFilename.startsWith("..") ?
new ZipEntry(imageFilename.substring(3)): // skip .. and File.separator
new ZipEntry(colladaBundle.getBuildingId() + "/" + imageFilename);
try {
zipOut.putNextEntry(zipEntry);
// zipOut.write(ordImageBytes, 0, bytes_read);
zipOut.write(ordImageBytes, 0, ordImageBytes.length);
zipOut.closeEntry();
}
catch (ZipException ze) {} // ignore repeated images
}
}
if (colladaBundle.getTexImages() != null) {
Set<String> keySet = colladaBundle.getTexImages().keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String imageFilename = iterator.next();
BufferedImage texImage = colladaBundle.getTexImages().get(imageFilename);
String imageType = imageFilename.substring(imageFilename.lastIndexOf('.') + 1);
ZipEntry zipEntry = imageFilename.startsWith("..") ?
new ZipEntry(imageFilename.substring(3)): // skip .. and File.separator
new ZipEntry(colladaBundle.getBuildingId() + "/" + imageFilename);
try {
zipOut.putNextEntry(zipEntry);
ImageIO.write(texImage, imageType, zipOut);
zipOut.closeEntry();
}
catch (ZipException ze) {} // ignore repeated images
}
}
colladaBundle = buildingQueue.poll();
}
}
zipOut.close();
}
fileWriter.close();
}
catch (Exception ioe) {
Logger.getInstance().error("I/O error: " + ioe.getMessage());
try {
fileWriter.close();
}
catch (Exception e) {}
return false;
}
eventDispatcher.triggerEvent(new StatusDialogMessage(" ", this));
// finally join eventDispatcher
try {
eventDispatcher.flushEvents();
} catch (InterruptedException iE) {
Logger.getInstance().error("Internal error: " + iE.getMessage());
return false;
}
// set null
ioWriterPool = null;
kmlWorkerPool = null;
kmlSplitter = null;
}
/*
catch (FileNotFoundException fnfe) {
Logger.getInstance().error("Path \"" + path + "\" not found.");
return false;
}
*/
finally {}
}
}
}
if (isBBoxActive) {
try {
eventDispatcher.triggerEvent(new StatusDialogTitle(filename + ".kml", this));
eventDispatcher.triggerEvent(new StatusDialogMessage(Internal.I18N.getString("kmlExport.dialog.writingMainFile"), this));
generateMasterFile();
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
if (config.getProject().getKmlExporter().isWriteJSONFile()) {
try {
Logger.getInstance().info("Writing file: " + filename + ".json");
File jsonFile = new File(path + File.separator + filename + ".json");
FileOutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write("{\n".getBytes(CHARSET));
Iterator<String> iterator = alreadyExported.keySet().iterator();
while (iterator.hasNext()) {
String gmlId = iterator.next();
outputStream.write(("\t\"" + gmlId + "\": {").toString().getBytes(CHARSET));
outputStream.write(alreadyExported.get(gmlId).toString().getBytes(CHARSET));
if (iterator.hasNext()) {
outputStream.write(",\n".getBytes(CHARSET));
}
}
outputStream.write("\n}\n".getBytes(CHARSET));
outputStream.close();
}
catch (IOException ioe) {
Logger.getInstance().error("I/O error: " + ioe.getMessage());
// ioe.printStackTrace();
}
}
eventDispatcher.triggerEvent(new StatusDialogMessage(Internal.I18N.getString("export.dialog.finish.msg"), this));
/*
Logger.getInstance().info("Exported CityGML features:");
int appearances = 0;
for (DisplayForm displayForm : config.getProject().getKmlExporter().getDisplayLevels()) {
if (displayForm.isActive() && DisplayForm.COLLADA == displayForm.getLevel()) {
appearances = de.tub.citydb.config.project.kmlExporter.KmlExporter.THEME_NONE.equals(selectedTheme)? 0 : 1;
break;
}
}
*/
// show exported features
if (!featureCounterMap.isEmpty()) {
Logger.getInstance().info("Exported CityGML features:");
for (CityGMLClass type : featureCounterMap.keySet())
Logger.getInstance().info(type + ": " + featureCounterMap.get(type));
}
Logger.getInstance().info("Processed geometry objects: " + geometryCounter);
return shouldRun;
}
public int calculateRowsColumnsAndDelta() throws SQLException {
TiledBoundingBox bbox = config.getProject().getKmlExporter().getFilter().getComplexFilter().getTiledBoundingBox();
TilingMode tilingMode = bbox.getTiling().getMode();
double autoTileSideLength = config.getProject().getKmlExporter().getAutoTileSideLength();
tileMatrix = new BoundingBox(new BoundingBoxCorner(bbox.getLowerLeftCorner().getX(), bbox.getLowerLeftCorner().getY()),
new BoundingBoxCorner(bbox.getUpperRightCorner().getX(), bbox.getUpperRightCorner().getY()));
DatabaseSrs dbSrs = dbPool.getActiveConnectionMetaData().getReferenceSystem();
if (bbox.getSrs() == null) {
throw new SQLException("Unknown BoundingBox srs");
}
if (bbox.getSrs().getSrid() != 0 && bbox.getSrs().getSrid() != dbSrs.getSrid()) {
wgs84TileMatrix = DBUtil.transformBBox(tileMatrix, bbox.getSrs(), WGS84_2D);
tileMatrix = DBUtil.transformBBox(tileMatrix, bbox.getSrs(), dbSrs);
}
else {
wgs84TileMatrix = DBUtil.transformBBox(tileMatrix, dbSrs, WGS84_2D);
}
if (tilingMode == TilingMode.NO_TILING) {
rows = 1;
columns = 1;
}
else if (tilingMode == TilingMode.AUTOMATIC) {
// approximate
rows = (int)((tileMatrix.getUpperRightCorner().getY() - tileMatrix.getLowerLeftCorner().getY()) / autoTileSideLength) + 1;
columns = (int)((tileMatrix.getUpperRightCorner().getX() - tileMatrix.getLowerLeftCorner().getX()) / autoTileSideLength) + 1;
bbox.getTiling().setRows(rows);
bbox.getTiling().setColumns(columns);
}
else {
rows = bbox.getTiling().getRows();
columns = bbox.getTiling().getColumns();
}
// must be done like this to avoid non-matching tile limits
wgs84DeltaLatitude = (wgs84TileMatrix.getUpperRightCorner().getY() - wgs84TileMatrix.getLowerLeftCorner().getY()) / rows;
wgs84DeltaLongitude = (wgs84TileMatrix.getUpperRightCorner().getX() - wgs84TileMatrix.getLowerLeftCorner().getX()) / columns;
return rows*columns;
}
private void generateMasterFile() throws FileNotFoundException,
SQLException,
JAXBException,
DatatypeConfigurationException {
// create a saxWriter instance
// define indent for xml output and namespace mappings
SAXWriter saxWriter = new SAXWriter();
saxWriter.setIndentString(" ");
saxWriter.setHeaderComment("Written by " + this.getClass().getPackage().getImplementationTitle() + ", version \"" +
this.getClass().getPackage().getImplementationVersion() + '"',
this.getClass().getPackage().getImplementationVendor());
saxWriter.setDefaultNamespace("http:
saxWriter.setPrefix("gx", "http:
saxWriter.setPrefix("atom", "http:
saxWriter.setPrefix("xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");
Marshaller marshaller = jaxbKmlContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
Properties props = new Properties();
props.put(Marshaller.JAXB_FRAGMENT, new Boolean(true));
// props.put(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
// props.put(Marshaller.JAXB_ENCODING, ENCODING);
TilingMode tilingMode = config.getProject().getKmlExporter().getFilter().getComplexFilter().getTiledBoundingBox().getTiling().getMode();
try {
File mainFile = new File(path + File.separator + filename + ".kml");
FileOutputStream outputStream = new FileOutputStream(mainFile);
saxWriter.setOutput(new StreamResult(outputStream), ENCODING);
ioWriterPool = new SingleWorkerPool<SAXEventBuffer>(
new IOWriterWorkerFactory(saxWriter),
100,
true);
ioWriterPool.prestartCoreWorkers();
// create file header
KMLHeaderWriter kmlHeader = new KMLHeaderWriter(saxWriter);
// create kml root element
KmlType kmlType = kmlFactory.createKmlType();
JAXBElement<KmlType> kml = kmlFactory.createKml(kmlType);
DocumentType document = kmlFactory.createDocumentType();
document.setOpen(true);
document.setName(filename);
LookAtType lookAtType = kmlFactory.createLookAtType();
lookAtType.setLongitude((wgs84TileMatrix.getUpperRightCorner().getX() + wgs84TileMatrix.getLowerLeftCorner().getX())/2);
lookAtType.setLatitude((wgs84TileMatrix.getLowerLeftCorner().getY() + (wgs84TileMatrix.getUpperRightCorner().getY() - wgs84TileMatrix.getLowerLeftCorner().getY())/3));
lookAtType.setAltitude(0.0);
lookAtType.setHeading(0.0);
lookAtType.setTilt(60.0);
lookAtType.setRange(970.0);
document.setAbstractViewGroup(kmlFactory.createLookAt(lookAtType));
kmlType.setAbstractFeatureGroup(kmlFactory.createDocument(document));
try {
kmlHeader.setRootElement(kml, jaxbKmlContext, props);
kmlHeader.startRootElement();
if (config.getProject().getKmlExporter().isOneFilePerObject()) {
for (DisplayForm displayForm : config.getProject().getKmlExporter().getBuildingDisplayForms()) {
addStyle(displayForm);
}
}
// make sure header has been written
saxWriter.flush();
}
catch (SAXException saxE) {
Logger.getInstance().error("I/O error: " + saxE.getMessage());
}
if (config.getProject().getKmlExporter().isShowBoundingBox()) {
SAXEventBuffer tmp = new SAXEventBuffer();
StyleType frameStyleType = kmlFactory.createStyleType();
frameStyleType.setId("frameStyle");
LineStyleType frameLineStyleType = kmlFactory.createLineStyleType();
frameLineStyleType.setWidth(4.0);
frameStyleType.setLineStyle(frameLineStyleType);
marshaller.marshal(kmlFactory.createStyle(frameStyleType), tmp);
PlacemarkType placemarkType = kmlFactory.createPlacemarkType();
placemarkType.setName("Bounding box border");
placemarkType.setStyleUrl("#" + frameStyleType.getId());
LineStringType lineStringType = kmlFactory.createLineStringType();
lineStringType.setTessellate(true);
lineStringType.getCoordinates().add("" + (wgs84TileMatrix.getLowerLeftCorner().getX() - BORDER_GAP) + "," + (wgs84TileMatrix.getLowerLeftCorner().getY() - BORDER_GAP * .5));
lineStringType.getCoordinates().add(" " + (wgs84TileMatrix.getLowerLeftCorner().getX() - BORDER_GAP) + "," + (wgs84TileMatrix.getUpperRightCorner().getY() + BORDER_GAP * .5));
lineStringType.getCoordinates().add(" " + (wgs84TileMatrix.getUpperRightCorner().getX() + BORDER_GAP) + "," + (wgs84TileMatrix.getUpperRightCorner().getY() + BORDER_GAP * .5));
lineStringType.getCoordinates().add(" " + (wgs84TileMatrix.getUpperRightCorner().getX() + BORDER_GAP) + "," + (wgs84TileMatrix.getLowerLeftCorner().getY() - BORDER_GAP * .5));
lineStringType.getCoordinates().add(" " + (wgs84TileMatrix.getLowerLeftCorner().getX() - BORDER_GAP) + "," + (wgs84TileMatrix.getLowerLeftCorner().getY() - BORDER_GAP * .5));
placemarkType.setAbstractGeometryGroup(kmlFactory.createLineString(lineStringType));
marshaller.marshal(kmlFactory.createPlacemark(placemarkType), tmp);
ioWriterPool.addWork(tmp);
}
int upperLevelVisibility = -1;
for (int i = DisplayForm.COLLADA; i >= DisplayForm.FOOTPRINT; i
DisplayForm df = new DisplayForm(i, -1, -1);
int indexOfDf = config.getProject().getKmlExporter().getBuildingDisplayForms().indexOf(df);
df = config.getProject().getKmlExporter().getBuildingDisplayForms().get(indexOfDf);
if (df.isActive()) {
df.setVisibleUpTo(upperLevelVisibility);
upperLevelVisibility = df.getVisibleFrom();
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
// must be done like this to avoid non-matching tile limits
double wgs84TileSouthLimit = wgs84TileMatrix.getLowerLeftCorner().getY() + (i * wgs84DeltaLatitude);
double wgs84TileNorthLimit = wgs84TileMatrix.getLowerLeftCorner().getY() + ((i+1) * wgs84DeltaLatitude);
double wgs84TileWestLimit = wgs84TileMatrix.getLowerLeftCorner().getX() + (j * wgs84DeltaLongitude);
double wgs84TileEastLimit = wgs84TileMatrix.getLowerLeftCorner().getX() + ((j+1) * wgs84DeltaLongitude);
// tileName should not contain special characters,
// since it will be used as filename for all displayForm files
String tileName = filename;
if (tilingMode != TilingMode.NO_TILING) {
tileName = tileName + "_Tile_" + i + "_" + j;
}
FolderType folderType = kmlFactory.createFolderType();
folderType.setName(tileName);
for (DisplayForm displayForm : config.getProject().getKmlExporter().getBuildingDisplayForms()) {
if (!displayForm.isActive()) continue;
String fileExtension = config.getProject().getKmlExporter().isExportAsKmz() ? ".kmz" : ".kml";
String tilenameForDisplayForm = tileName + "_" + displayForm.getName() + fileExtension;
NetworkLinkType networkLinkType = kmlFactory.createNetworkLinkType();
networkLinkType.setName("Display as " + displayForm.getName());
RegionType regionType = kmlFactory.createRegionType();
LatLonAltBoxType latLonAltBoxType = kmlFactory.createLatLonAltBoxType();
latLonAltBoxType.setNorth(wgs84TileNorthLimit);
latLonAltBoxType.setSouth(wgs84TileSouthLimit);
latLonAltBoxType.setEast(wgs84TileEastLimit);
latLonAltBoxType.setWest(wgs84TileWestLimit);
LodType lodType = kmlFactory.createLodType();
lodType.setMinLodPixels((double)displayForm.getVisibleFrom());
lodType.setMaxLodPixels((double)displayForm.getVisibleUpTo());
regionType.setLatLonAltBox(latLonAltBoxType);
regionType.setLod(lodType);
LinkType linkType = kmlFactory.createLinkType();
linkType.setHref(tilenameForDisplayForm);
linkType.setViewRefreshMode(ViewRefreshModeEnumType.fromValue(config.getProject().getKmlExporter().getViewRefreshMode()));
linkType.setViewFormat("");
if (linkType.getViewRefreshMode() == ViewRefreshModeEnumType.ON_STOP) {
linkType.setViewRefreshTime(config.getProject().getKmlExporter().getViewRefreshTime());
}
// confusion between atom:link and kml:Link in ogckml22.xsd
networkLinkType.getRest().add(kmlFactory.createLink(linkType));
networkLinkType.setRegion(regionType);
folderType.getAbstractFeatureGroup().add(kmlFactory.createNetworkLink(networkLinkType));
}
SAXEventBuffer tmp = new SAXEventBuffer();
marshaller.marshal(kmlFactory.createFolder(folderType), tmp);
ioWriterPool.addWork(tmp);
}
}
try {
ioWriterPool.shutdownAndWait();
kmlHeader.endRootElement();
saxWriter.flush();
} catch (SAXException saxE) {
Logger.getInstance().error("I/O error: " + saxE.getMessage());
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
outputStream.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void addStyle(DisplayForm currentDisplayForm) throws JAXBException {
if (!currentDisplayForm.isActive()) return;
FeatureClass featureFilter = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass();
if (featureFilter.isSetVegetation()) {
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getVegetationDisplayForms(),
SolitaryVegetationObject.STYLE_BASIS_NAME);
}
if (featureFilter.isSetCityObjectGroup()) {
addStyle(config.getProject().getKmlExporter().getCityObjectGroupDisplayForms().get(0), // hard-coded for groups
config.getProject().getKmlExporter().getCityObjectGroupDisplayForms(),
CityObjectGroup.STYLE_BASIS_NAME);
}
if (featureFilter.isSetCityFurniture()) {
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getCityFurnitureDisplayForms(),
CityFurniture.STYLE_BASIS_NAME);
}
if (featureFilter.isSetGenericCityObject()) {
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getGenericCityObjectDisplayForms(),
GenericCityObject.STYLE_BASIS_NAME);
}
if (featureFilter.isSetLandUse()) {
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getLandUseDisplayForms(),
LandUse.STYLE_BASIS_NAME);
}
if (featureFilter.isSetWaterBody()) {
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getWaterBodyDisplayForms(),
WaterBody.STYLE_BASIS_NAME);
}
if (featureFilter.isSetBuilding()) { // must be last
addStyle(currentDisplayForm,
config.getProject().getKmlExporter().getBuildingDisplayForms(),
Building.STYLE_BASIS_NAME);
}
}
private void addStyle(DisplayForm currentDisplayForm,
List<DisplayForm> displayFormsForObjectType,
String styleBasisName) throws JAXBException {
SAXEventBuffer saxBuffer = new SAXEventBuffer();
Marshaller marshaller = jaxbKmlContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
BalloonStyleType balloonStyle = new BalloonStyleType();
balloonStyle.setText("$[description]");
switch (currentDisplayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
int indexOfDf = displayFormsForObjectType.indexOf(currentDisplayForm);
String fillColor = Integer.toHexString(DisplayForm.DEFAULT_FILL_COLOR);
String lineColor = Integer.toHexString(DisplayForm.DEFAULT_LINE_COLOR);
String hlFillColor = Integer.toHexString(DisplayForm.DEFAULT_FILL_HIGHLIGHTED_COLOR);
String hlLineColor = Integer.toHexString(DisplayForm.DEFAULT_LINE_HIGHLIGHTED_COLOR);
if (indexOfDf != -1) {
currentDisplayForm = displayFormsForObjectType.get(indexOfDf);
if (currentDisplayForm.isSetRgba0()) {
fillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba0()));
}
if (currentDisplayForm.isSetRgba1()) {
lineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba1()));
}
if (currentDisplayForm.isSetRgba4()) {
hlFillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba4()));
}
if (currentDisplayForm.isSetRgba5()) {
hlLineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba5()));
}
}
LineStyleType lineStyleFootprintNormal = kmlFactory.createLineStyleType();
lineStyleFootprintNormal.setColor(hexStringToByteArray(lineColor));
lineStyleFootprintNormal.setWidth(1.5);
PolyStyleType polyStyleFootprintNormal = kmlFactory.createPolyStyleType();
polyStyleFootprintNormal.setColor(hexStringToByteArray(fillColor));
StyleType styleFootprintNormal = kmlFactory.createStyleType();
styleFootprintNormal.setId(styleBasisName + currentDisplayForm.getName() + "Normal");
styleFootprintNormal.setLineStyle(lineStyleFootprintNormal);
styleFootprintNormal.setPolyStyle(polyStyleFootprintNormal);
styleFootprintNormal.setBalloonStyle(balloonStyle);
marshaller.marshal(kmlFactory.createStyle(styleFootprintNormal), saxBuffer);
if (currentDisplayForm.isHighlightingEnabled()) {
LineStyleType lineStyleFootprintHighlight = kmlFactory.createLineStyleType();
lineStyleFootprintHighlight.setColor(hexStringToByteArray(hlLineColor));
lineStyleFootprintHighlight.setWidth(1.5);
PolyStyleType polyStyleFootprintHighlight = kmlFactory.createPolyStyleType();
polyStyleFootprintHighlight.setColor(hexStringToByteArray(hlFillColor));
StyleType styleFootprintHighlight = kmlFactory.createStyleType();
styleFootprintHighlight.setId(styleBasisName + currentDisplayForm.getName() + "Highlight");
styleFootprintHighlight.setLineStyle(lineStyleFootprintHighlight);
styleFootprintHighlight.setPolyStyle(polyStyleFootprintHighlight);
styleFootprintHighlight.setBalloonStyle(balloonStyle);
PairType pairFootprintNormal = kmlFactory.createPairType();
pairFootprintNormal.setKey(StyleStateEnumType.NORMAL);
pairFootprintNormal.setStyleUrl("#" + styleFootprintNormal.getId());
PairType pairFootprintHighlight = kmlFactory.createPairType();
pairFootprintHighlight.setKey(StyleStateEnumType.HIGHLIGHT);
pairFootprintHighlight.setStyleUrl("#" + styleFootprintHighlight.getId());
StyleMapType styleMapFootprint = kmlFactory.createStyleMapType();
styleMapFootprint.setId(styleBasisName + currentDisplayForm.getName() + "Style");
styleMapFootprint.getPair().add(pairFootprintNormal);
styleMapFootprint.getPair().add(pairFootprintHighlight);
marshaller.marshal(kmlFactory.createStyle(styleFootprintHighlight), saxBuffer);
marshaller.marshal(kmlFactory.createStyleMap(styleMapFootprint), saxBuffer);
}
ioWriterPool.addWork(saxBuffer);
break;
case DisplayForm.GEOMETRY:
boolean isBuilding = Building.STYLE_BASIS_NAME.equals(styleBasisName); // buildings are most complex
indexOfDf = displayFormsForObjectType.indexOf(currentDisplayForm);
String wallFillColor = Integer.toHexString(DisplayForm.DEFAULT_WALL_FILL_COLOR);
String wallLineColor = Integer.toHexString(DisplayForm.DEFAULT_WALL_LINE_COLOR);
String roofFillColor = Integer.toHexString(DisplayForm.DEFAULT_ROOF_FILL_COLOR);
String roofLineColor = Integer.toHexString(DisplayForm.DEFAULT_ROOF_LINE_COLOR);
if (indexOfDf != -1) {
currentDisplayForm = displayFormsForObjectType.get(indexOfDf);
if (currentDisplayForm.isSetRgba0()) {
wallFillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba0()));
}
if (currentDisplayForm.isSetRgba1()) {
wallLineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba1()));
}
if (currentDisplayForm.isSetRgba2()) {
roofFillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba2()));
}
if (currentDisplayForm.isSetRgba3()) {
roofLineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba3()));
}
}
LineStyleType lineStyleWallNormal = kmlFactory.createLineStyleType();
lineStyleWallNormal.setColor(hexStringToByteArray(wallLineColor));
PolyStyleType polyStyleWallNormal = kmlFactory.createPolyStyleType();
polyStyleWallNormal.setColor(hexStringToByteArray(wallFillColor));
StyleType styleWallNormal = kmlFactory.createStyleType();
styleWallNormal.setLineStyle(lineStyleWallNormal);
styleWallNormal.setPolyStyle(polyStyleWallNormal);
styleWallNormal.setBalloonStyle(balloonStyle);
if (isBuilding)
styleWallNormal.setId(TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.WALL_SURFACE).toString() + "Normal");
else
styleWallNormal.setId(styleBasisName + currentDisplayForm.getName() + "Normal");
marshaller.marshal(kmlFactory.createStyle(styleWallNormal), saxBuffer);
if (isBuilding) {
PolyStyleType polyStyleGroundSurface = kmlFactory.createPolyStyleType();
polyStyleGroundSurface.setColor(hexStringToByteArray("ff00aa00"));
StyleType styleGroundSurface = kmlFactory.createStyleType();
styleGroundSurface.setId(TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.GROUND_SURFACE).toString() + "Style");
styleGroundSurface.setPolyStyle(polyStyleGroundSurface);
styleGroundSurface.setBalloonStyle(balloonStyle);
marshaller.marshal(kmlFactory.createStyle(styleGroundSurface), saxBuffer);
LineStyleType lineStyleRoofNormal = kmlFactory.createLineStyleType();
lineStyleRoofNormal.setColor(hexStringToByteArray(roofLineColor));
PolyStyleType polyStyleRoofNormal = kmlFactory.createPolyStyleType();
polyStyleRoofNormal.setColor(hexStringToByteArray(roofFillColor));
StyleType styleRoofNormal = kmlFactory.createStyleType();
styleRoofNormal.setId(TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.ROOF_SURFACE).toString() + "Normal");
styleRoofNormal.setLineStyle(lineStyleRoofNormal);
styleRoofNormal.setPolyStyle(polyStyleRoofNormal);
styleRoofNormal.setBalloonStyle(balloonStyle);
marshaller.marshal(kmlFactory.createStyle(styleRoofNormal), saxBuffer);
}
if (currentDisplayForm.isHighlightingEnabled()) {
String invisibleColor = Integer.toHexString(DisplayForm.INVISIBLE_COLOR);
String highlightFillColor = Integer.toHexString(DisplayForm.DEFAULT_FILL_HIGHLIGHTED_COLOR);
String highlightLineColor = Integer.toHexString(DisplayForm.DEFAULT_LINE_HIGHLIGHTED_COLOR);
/*
if (indexOfDf != -1) {
currentDisplayForm = displayFormsForObjectType.get(indexOfDf);
*/
if (currentDisplayForm.isSetRgba4()) {
highlightFillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba4()));
invisibleColor = "01" + highlightFillColor.substring(2);
}
if (currentDisplayForm.isSetRgba5()) {
highlightLineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba5()));
}
LineStyleType lineStyleGeometryInvisible = kmlFactory.createLineStyleType();
lineStyleGeometryInvisible.setColor(hexStringToByteArray(invisibleColor));
PolyStyleType polyStyleGeometryInvisible = kmlFactory.createPolyStyleType();
polyStyleGeometryInvisible.setColor(hexStringToByteArray(invisibleColor));
StyleType styleGeometryInvisible = kmlFactory.createStyleType();
styleGeometryInvisible.setId(styleBasisName + currentDisplayForm.getName() + "StyleInvisible");
styleGeometryInvisible.setLineStyle(lineStyleGeometryInvisible);
styleGeometryInvisible.setPolyStyle(polyStyleGeometryInvisible);
styleGeometryInvisible.setBalloonStyle(balloonStyle);
LineStyleType lineStyleGeometryHighlight = kmlFactory.createLineStyleType();
lineStyleGeometryHighlight.setColor(hexStringToByteArray(highlightLineColor));
PolyStyleType polyStyleGeometryHighlight = kmlFactory.createPolyStyleType();
polyStyleGeometryHighlight.setColor(hexStringToByteArray(highlightFillColor));
StyleType styleGeometryHighlight = kmlFactory.createStyleType();
styleGeometryHighlight.setId(styleBasisName + currentDisplayForm.getName() + "StyleHighlight");
styleGeometryHighlight.setLineStyle(lineStyleGeometryHighlight);
styleGeometryHighlight.setPolyStyle(polyStyleGeometryHighlight);
styleGeometryHighlight.setBalloonStyle(balloonStyle);
PairType pairGeometryNormal = kmlFactory.createPairType();
pairGeometryNormal.setKey(StyleStateEnumType.NORMAL);
pairGeometryNormal.setStyleUrl("#" + styleGeometryInvisible.getId());
PairType pairGeometryHighlight = kmlFactory.createPairType();
pairGeometryHighlight.setKey(StyleStateEnumType.HIGHLIGHT);
pairGeometryHighlight.setStyleUrl("#" + styleGeometryHighlight.getId());
StyleMapType styleMapGeometry = kmlFactory.createStyleMapType();
styleMapGeometry.setId(styleBasisName + currentDisplayForm.getName() +"Style");
styleMapGeometry.getPair().add(pairGeometryNormal);
styleMapGeometry.getPair().add(pairGeometryHighlight);
marshaller.marshal(kmlFactory.createStyle(styleGeometryInvisible), saxBuffer);
marshaller.marshal(kmlFactory.createStyle(styleGeometryHighlight), saxBuffer);
marshaller.marshal(kmlFactory.createStyleMap(styleMapGeometry), saxBuffer);
}
ioWriterPool.addWork(saxBuffer);
break;
case DisplayForm.COLLADA:
indexOfDf = displayFormsForObjectType.indexOf(currentDisplayForm);
if (indexOfDf != -1) {
currentDisplayForm = displayFormsForObjectType.get(indexOfDf);
if (currentDisplayForm.isHighlightingEnabled()) {
String invisibleColor = Integer.toHexString(DisplayForm.INVISIBLE_COLOR);
String highlightFillColor = Integer.toHexString(DisplayForm.DEFAULT_FILL_HIGHLIGHTED_COLOR);
String highlightLineColor = Integer.toHexString(DisplayForm.DEFAULT_LINE_HIGHLIGHTED_COLOR);
if (currentDisplayForm.isSetRgba4()) {
highlightFillColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba4()));
invisibleColor = "01" + highlightFillColor.substring(2);
}
if (currentDisplayForm.isSetRgba5()) {
highlightLineColor = DisplayForm.formatColorStringForKML(Integer.toHexString(currentDisplayForm.getRgba5()));
}
LineStyleType lineStyleColladaInvisible = kmlFactory.createLineStyleType();
lineStyleColladaInvisible.setColor(hexStringToByteArray(invisibleColor));
PolyStyleType polyStyleColladaInvisible = kmlFactory.createPolyStyleType();
polyStyleColladaInvisible.setColor(hexStringToByteArray(invisibleColor));
StyleType styleColladaInvisible = kmlFactory.createStyleType();
styleColladaInvisible.setId(styleBasisName + currentDisplayForm.getName() + "StyleInvisible");
styleColladaInvisible.setLineStyle(lineStyleColladaInvisible);
styleColladaInvisible.setPolyStyle(polyStyleColladaInvisible);
styleColladaInvisible.setBalloonStyle(balloonStyle);
LineStyleType lineStyleColladaHighlight = kmlFactory.createLineStyleType();
lineStyleColladaHighlight.setColor(hexStringToByteArray(highlightLineColor));
PolyStyleType polyStyleColladaHighlight = kmlFactory.createPolyStyleType();
polyStyleColladaHighlight.setColor(hexStringToByteArray(highlightFillColor));
StyleType styleColladaHighlight = kmlFactory.createStyleType();
styleColladaHighlight.setId(styleBasisName + currentDisplayForm.getName() + "StyleHighlight");
styleColladaHighlight.setLineStyle(lineStyleColladaHighlight);
styleColladaHighlight.setPolyStyle(polyStyleColladaHighlight);
styleColladaHighlight.setBalloonStyle(balloonStyle);
PairType pairColladaNormal = kmlFactory.createPairType();
pairColladaNormal.setKey(StyleStateEnumType.NORMAL);
pairColladaNormal.setStyleUrl("#" + styleColladaInvisible.getId());
PairType pairColladaHighlight = kmlFactory.createPairType();
pairColladaHighlight.setKey(StyleStateEnumType.HIGHLIGHT);
pairColladaHighlight.setStyleUrl("#" + styleColladaHighlight.getId());
StyleMapType styleMapCollada = kmlFactory.createStyleMapType();
styleMapCollada.setId(styleBasisName + currentDisplayForm.getName() +"Style");
styleMapCollada.getPair().add(pairColladaNormal);
styleMapCollada.getPair().add(pairColladaHighlight);
marshaller.marshal(kmlFactory.createStyle(styleColladaInvisible), saxBuffer);
marshaller.marshal(kmlFactory.createStyle(styleColladaHighlight), saxBuffer);
marshaller.marshal(kmlFactory.createStyleMap(styleMapCollada), saxBuffer);
ioWriterPool.addWork(saxBuffer);
}
}
break;
default:
// no style
break;
}
}
private void addBorder(int i, int j) throws JAXBException {
SAXEventBuffer saxBuffer = new SAXEventBuffer();
Marshaller marshaller = jaxbKmlContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
if (config.getProject().getKmlExporter().getFilter().isSetComplexFilter() &&
config.getProject().getKmlExporter().isShowTileBorders()) {
saxBuffer = new SAXEventBuffer();
// must be done like this to avoid non-matching tile limits
double wgs84TileSouthLimit = wgs84TileMatrix.getLowerLeftCorner().getY() + (i * wgs84DeltaLatitude);
double wgs84TileNorthLimit = wgs84TileMatrix.getLowerLeftCorner().getY() + ((i+1) * wgs84DeltaLatitude);
double wgs84TileWestLimit = wgs84TileMatrix.getLowerLeftCorner().getX() + (j * wgs84DeltaLongitude);
double wgs84TileEastLimit = wgs84TileMatrix.getLowerLeftCorner().getX() + ((j+1) * wgs84DeltaLongitude);
PlacemarkType placemark = kmlFactory.createPlacemarkType();
placemark.setName("Tile border");
LineStringType lineString = kmlFactory.createLineStringType();
lineString.setTessellate(true);
lineString.getCoordinates().add(String.valueOf(wgs84TileWestLimit) + "," + wgs84TileSouthLimit);
lineString.getCoordinates().add(String.valueOf(wgs84TileWestLimit) + "," + wgs84TileNorthLimit);
lineString.getCoordinates().add(String.valueOf(wgs84TileEastLimit) + "," + wgs84TileNorthLimit);
lineString.getCoordinates().add(String.valueOf(wgs84TileEastLimit) + "," + wgs84TileSouthLimit);
lineString.getCoordinates().add(String.valueOf(wgs84TileWestLimit) + "," + wgs84TileSouthLimit);
placemark.setAbstractGeometryGroup(kmlFactory.createLineString(lineString));
marshaller.marshal(kmlFactory.createPlacemark(placemark), saxBuffer);
ioWriterPool.addWork(saxBuffer);
}
}
private byte[] hexStringToByteArray(String hex) {
// padding if needed
if (hex.length()/2 != (hex.length()+1)/2) {
hex = "0" + hex;
}
byte[] bytes = new byte[hex.length()/2];
try {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
}
} catch ( Exception e ) {
e.printStackTrace();
return null;
}
return bytes;
}
private boolean checkBalloonSettings (CityGMLClass cityObjectType) {
Balloon balloonSettings = null;
boolean settingsMustBeChecked = false;
switch (cityObjectType) {
case BUILDING:
balloonSettings = config.getProject().getKmlExporter().getBuildingBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetBuilding();
break;
case WATER_BODY:
balloonSettings = config.getProject().getKmlExporter().getWaterBodyBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetWaterBody();
break;
case LAND_USE:
balloonSettings = config.getProject().getKmlExporter().getLandUseBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetLandUse();
break;
case SOLITARY_VEGETATION_OBJECT:
balloonSettings = config.getProject().getKmlExporter().getVegetationBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetVegetation();
break;
case CITY_FURNITURE:
balloonSettings = config.getProject().getKmlExporter().getCityFurnitureBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetCityFurniture();
break;
case GENERIC_CITY_OBJECT:
balloonSettings = config.getProject().getKmlExporter().getGenericCityObjectBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetGenericCityObject();
break;
case CITY_OBJECT_GROUP:
balloonSettings = config.getProject().getKmlExporter().getCityObjectGroupBalloon();
settingsMustBeChecked = config.getProject().getKmlExporter().getFilter().getComplexFilter().getFeatureClass().isSetCityObjectGroup();
break;
default:
return false;
}
if (settingsMustBeChecked &&
balloonSettings.isIncludeDescription() &&
balloonSettings.getBalloonContentMode() != BalloonContentMode.GEN_ATTRIB) {
String balloonTemplateFilename = balloonSettings.getBalloonContentTemplateFile();
if (balloonTemplateFilename != null && balloonTemplateFilename.length() > 0) {
File ballonTemplateFile = new File(balloonTemplateFilename);
if (!ballonTemplateFile.exists()) {
Logger.getInstance().error("Balloon template file \"" + balloonTemplateFilename + "\" not found.");
return false;
}
}
}
return true;
}
@Override
public void handleEvent(Event e) throws Exception {
if (e.getEventType() == EventType.COUNTER &&
((CounterEvent)e).getType() == CounterType.TOPLEVEL_FEATURE) {
CityGMLClass type = null;
Object kmlExportObject = e.getSource();
if (kmlExportObject instanceof Building) {
type = CityGMLClass.BUILDING;
}
else if (kmlExportObject instanceof WaterBody) {
type = CityGMLClass.WATER_BODY;
}
else if (kmlExportObject instanceof LandUse) {
type = CityGMLClass.LAND_USE;
}
else if (kmlExportObject instanceof CityObjectGroup) {
type = CityGMLClass.CITY_OBJECT_GROUP;
}
else if (kmlExportObject instanceof SolitaryVegetationObject) {
type = CityGMLClass.SOLITARY_VEGETATION_OBJECT;
}
else if (kmlExportObject instanceof PlantCover) {
type = CityGMLClass.PLANT_COVER;
}
else if (kmlExportObject instanceof GenericCityObject) {
type = CityGMLClass.GENERIC_CITY_OBJECT;
}
else if (kmlExportObject instanceof CityFurniture) {
type = CityGMLClass.CITY_FURNITURE;
}
else
return;
Long counter = featureCounterMap.get(type);
Long update = ((CounterEvent)e).getCounter();
if (counter == null)
featureCounterMap.put(type, update);
else
featureCounterMap.put(type, counter + update);
}
else if (e.getEventType() == EventType.GEOMETRY_COUNTER) {
geometryCounter++;
}
else if (e.getEventType() == EventType.INTERRUPT) {
if (isInterrupted.compareAndSet(false, true)) {
shouldRun = false;
String log = ((InterruptEvent)e).getLogMessage();
if (log != null)
Logger.getInstance().log(((InterruptEvent)e).getLogLevelType(), log);
if (kmlSplitter != null)
kmlSplitter.shutdown();
if (kmlWorkerPool != null) {
kmlWorkerPool.shutdownNow();
}
}
}
}
public static HashMap<String, CityObject4JSON> getAlreadyExported() {
return alreadyExported;
}
}
|
package org.teiid.query.metadata;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.ModelMetaData.Message.Severity;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.api.exception.query.QueryResolverException;
import org.teiid.core.TeiidException;
import org.teiid.core.types.DataTypeManager;
import org.teiid.language.SQLConstants;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.metadata.*;
import org.teiid.metadata.FunctionMethod.Determinism;
import org.teiid.query.QueryPlugin;
import org.teiid.query.function.metadata.FunctionMetadataValidator;
import org.teiid.query.mapping.relational.QueryNode;
import org.teiid.query.parser.QueryParser;
import org.teiid.query.report.ActivityReport;
import org.teiid.query.report.ReportItem;
import org.teiid.query.resolver.QueryResolver;
import org.teiid.query.resolver.util.ResolverUtil;
import org.teiid.query.resolver.util.ResolverVisitor;
import org.teiid.query.sql.lang.Command;
import org.teiid.query.sql.lang.QueryCommand;
import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
import org.teiid.query.sql.symbol.Expression;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.symbol.Symbol;
import org.teiid.query.sql.visitor.EvaluatableVisitor;
import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
import org.teiid.query.validator.Validator;
import org.teiid.query.validator.ValidatorFailure;
import org.teiid.query.validator.ValidatorReport;
import org.teiid.translator.TranslatorException;
public class MetadataValidator {
private Map<String, Datatype> typeMap;
interface MetadataRule {
void execute(VDBMetaData vdb, MetadataStore vdbStore, ValidatorReport report, MetadataValidator metadataValidator);
}
public MetadataValidator(Map<String, Datatype> typeMap) {
this.typeMap = typeMap;
}
public MetadataValidator() {
this.typeMap = SystemMetadata.getInstance().getRuntimeTypeMap();
}
public ValidatorReport validate(VDBMetaData vdb, MetadataStore store) {
ValidatorReport report = new ValidatorReport();
if (store != null && !store.getSchemaList().isEmpty()) {
new SourceModelArtifacts().execute(vdb, store, report, this);
new CrossSchemaResolver().execute(vdb, store, report, this);
new ResolveQueryPlans().execute(vdb, store, report, this);
new MinimalMetadata().execute(vdb, store, report, this);
}
return report;
}
// At minimum the model must have table/view, procedure or function
static class MinimalMetadata implements MetadataRule {
@Override
public void execute(VDBMetaData vdb, MetadataStore store, ValidatorReport report, MetadataValidator metadataValidator) {
for (Schema schema:store.getSchemaList()) {
if (vdb.getImportedModels().contains(schema.getName())) {
continue;
}
ModelMetaData model = vdb.getModel(schema.getName());
if (schema.getTables().isEmpty()
&& schema.getProcedures().isEmpty()
&& schema.getFunctions().isEmpty()) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31070, model.getName()));
}
for (Table t:schema.getTables().values()) {
if (t.getColumns() == null || t.getColumns().size() == 0) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31071, t.getFullName()));
}
}
// procedure validation is handled in parsing routines.
if (!schema.getFunctions().isEmpty()) {
ActivityReport<ReportItem> funcReport = new ActivityReport<ReportItem>("Translator metadata load " + model.getName()); //$NON-NLS-1$
FunctionMetadataValidator.validateFunctionMethods(schema.getFunctions().values(),report);
if(report.hasItems()) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31073, funcReport));
}
}
}
}
}
// do not allow foreign tables, source functions in view model and vice versa
static class SourceModelArtifacts implements MetadataRule {
@Override
public void execute(VDBMetaData vdb, MetadataStore store, ValidatorReport report, MetadataValidator metadataValidator) {
for (Schema schema:store.getSchemaList()) {
if (vdb.getImportedModels().contains(schema.getName())) {
continue;
}
ModelMetaData model = vdb.getModel(schema.getName());
for (Table t:schema.getTables().values()) {
if (t.isPhysical() && !model.isSource()) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31075, t.getFullName(), model.getName()));
}
}
Set<String> names = new HashSet<String>();
for (Procedure p:schema.getProcedures().values()) {
boolean hasReturn = false;
names.clear();
for (ProcedureParameter param : p.getParameters()) {
if (param.isVarArg() && param != p.getParameters().get(p.getParameters().size() -1)) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31112, p.getFullName()));
}
if (param.getType() == ProcedureParameter.Type.ReturnValue) {
if (hasReturn) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31107, p.getFullName()));
}
hasReturn = true;
}
if (!names.add(param.getName())) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31106, p.getFullName(), param.getFullName()));
}
}
if (!p.isVirtual() && !model.isSource()) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31077, p.getFullName(), model.getName()));
}
}
for (FunctionMethod func:schema.getFunctions().values()) {
for (FunctionParameter param : func.getInputParameters()) {
if (param.isVarArg() && param != func.getInputParameters().get(func.getInputParameterCount() -1)) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31112, func.getFullName()));
}
}
if (func.getPushdown().equals(FunctionMethod.PushDown.MUST_PUSHDOWN) && !model.isSource()) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31078, func.getFullName(), model.getName()));
}
}
}
}
}
// Resolves metadata query plans to make sure they are accurate
static class ResolveQueryPlans implements MetadataRule {
@Override
public void execute(VDBMetaData vdb, MetadataStore store, ValidatorReport report, MetadataValidator metadataValidator) {
QueryMetadataInterface metadata = vdb.getAttachment(QueryMetadataInterface.class);
metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
for (Schema schema:store.getSchemaList()) {
if (vdb.getImportedModels().contains(schema.getName())) {
continue;
}
ModelMetaData model = vdb.getModel(schema.getName());
MetadataFactory mf = new MetadataFactory(vdb.getName(), vdb.getVersion(), metadataValidator.typeMap, model) {
protected void setUUID(AbstractMetadataRecord record) {
if (count >= 0) {
count = Integer.MIN_VALUE;
}
super.setUUID(record);
}
};
mf.setBuiltinDataTypes(store.getDatatypes());
for (AbstractMetadataRecord record : schema.getResolvingOrder()) {
if (record instanceof Table) {
Table t = (Table)record;
// no need to verify the transformation of the xml mapping document,
// as this is very specific and designer already validates it.
if (t.getTableType() == Table.Type.Document
|| t.getTableType() == Table.Type.XmlMappingClass
|| t.getTableType() == Table.Type.XmlStagingTable) {
continue;
}
if (t.isVirtual()) {
if (t.getSelectTransformation() == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31079, t.getFullName(), model.getName()));
}
else {
metadataValidator.validate(vdb, model, t, report, metadata, mf);
}
}
} else if (record instanceof Procedure) {
Procedure p = (Procedure)record;
if (p.isVirtual() && !p.isFunction()) {
if (p.getQueryPlan() == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31081, p.getFullName(), model.getName()));
}
else {
metadataValidator.validate(vdb, model, p, report, metadata, mf);
}
}
}
}
}
}
}
public void log(ValidatorReport report, ModelMetaData model, String msg) {
log(report, model, Severity.ERROR, msg);
}
public void log(ValidatorReport report, ModelMetaData model, Severity severity, String msg) {
model.addRuntimeMessage(severity, msg);
int messageLevel = MessageLevel.WARNING;
if (severity == Severity.ERROR) {
report.handleValidationError(msg);
} else {
messageLevel = MessageLevel.INFO;
report.handleValidationWarning(msg);
}
LogManager.log(messageLevel, LogConstants.CTX_QUERY_RESOLVER, msg);
}
private void validate(VDBMetaData vdb, ModelMetaData model, AbstractMetadataRecord record, ValidatorReport report, QueryMetadataInterface metadata, MetadataFactory mf) {
ValidatorReport resolverReport = null;
try {
if (record instanceof Procedure) {
Procedure p = (Procedure)record;
Command command = QueryParser.getQueryParser().parseProcedure(p.getQueryPlan(), false);
QueryResolver.resolveCommand(command, new GroupSymbol(p.getFullName()), Command.TYPE_STORED_PROCEDURE, metadata);
resolverReport = Validator.validate(command, metadata);
} else if (record instanceof Table) {
Table t = (Table)record;
GroupSymbol symbol = new GroupSymbol(t.getFullName());
ResolverUtil.resolveGroup(symbol, metadata);
if (t.isVirtual() && (t.getColumns() == null || t.getColumns().isEmpty())) {
QueryCommand command = (QueryCommand)QueryParser.getQueryParser().parseCommand(t.getSelectTransformation());
QueryResolver.resolveCommand(command, metadata);
resolverReport = Validator.validate(command, metadata);
if(!resolverReport.hasItems()) {
List<Expression> symbols = command.getProjectedSymbols();
for (Expression column:symbols) {
try {
addColumn(Symbol.getShortName(column), column.getType(), t, mf);
} catch (TranslatorException e) {
log(report, model, e.getMessage());
}
}
}
}
if (t.isMaterialized() && t.getMaterializedTable() == null) {
List<KeyRecord> fbis = t.getFunctionBasedIndexes();
List<GroupSymbol> groups = Arrays.asList(symbol);
if (fbis != null && !fbis.isEmpty()) {
for (KeyRecord fbi : fbis) {
for (int j = 0; j < fbi.getColumns().size(); j++) {
Column c = fbi.getColumns().get(j);
if (c.getParent() != fbi) {
continue;
}
String exprString = c.getNameInSource();
try {
Expression ex = QueryParser.getQueryParser().parseExpression(exprString);
ResolverVisitor.resolveLanguageObject(ex, groups, metadata);
if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ex).isEmpty()) {
log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31114, exprString, fbi.getFullName()));
}
EvaluatableVisitor ev = new EvaluatableVisitor();
PreOrPostOrderNavigator.doVisit(ex, ev, PreOrPostOrderNavigator.PRE_ORDER);
if (ev.getDeterminismLevel().compareTo(Determinism.VDB_DETERMINISTIC) < 0) {
log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31115, exprString, fbi.getFullName()));
}
} catch (QueryResolverException e) {
log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31116, exprString, fbi.getFullName(), e.getMessage()));
}
}
}
}
}
// this seems to parse, resolve and validate.
QueryResolver.resolveView(symbol, new QueryNode(t.getSelectTransformation()), SQLConstants.Reserved.SELECT, metadata);
}
if(resolverReport != null && resolverReport.hasItems()) {
for (ValidatorFailure v:resolverReport.getItems()) {
log(report, model, v.getStatus() == ValidatorFailure.Status.ERROR?Severity.ERROR:Severity.WARNING, v.getMessage());
}
}
} catch (TeiidException e) {
log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31080, record.getFullName(), e.getFullMessage()));
}
}
private Column addColumn(String name, Class<?> type, Table table, MetadataFactory mf) throws TranslatorException {
if (type == null) {
throw new TranslatorException(QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31086, name, table.getFullName()));
}
Column column = mf.addColumn(name, DataTypeManager.getDataTypeName(type), table);
column.setUpdatable(table.supportsUpdate());
return column;
}
// this class resolves the artifacts that are dependent upon objects from other schemas
// materialization sources, fk and data types (coming soon..)
static class CrossSchemaResolver implements MetadataRule {
private boolean keyMatches(List<String> names, KeyRecord record) {
if (names.size() != record.getColumns().size()) {
return false;
}
for (int i = 0; i < names.size(); i++) {
if (!names.get(i).equals(record.getColumns().get(i).getName())) {
return false;
}
}
return true;
}
@Override
public void execute(VDBMetaData vdb, MetadataStore store, ValidatorReport report, MetadataValidator metadataValidator) {
for (Schema schema:store.getSchemaList()) {
if (vdb.getImportedModels().contains(schema.getName())) {
continue;
}
ModelMetaData model = vdb.getModel(schema.getName());
for (Table t:schema.getTables().values()) {
if (t.isVirtual()) {
if (t.isMaterialized() && t.getMaterializedTable() != null && t.getMaterializedTable().getParent() == null) {
String matTableName = t.getMaterializedTable().getName();
int index = matTableName.indexOf(Table.NAME_DELIM_CHAR);
if (index == -1) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31088, matTableName, t.getFullName()));
}
else {
String schemaName = matTableName.substring(0, index);
Schema matSchema = store.getSchema(schemaName);
if (matSchema == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31089, schemaName, matTableName, t.getFullName()));
}
else {
Table matTable = matSchema.getTable(matTableName.substring(index+1));
if (matTable == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31090, matTableName.substring(index+1), schemaName, t.getFullName()));
}
else {
t.setMaterializedTable(matTable);
}
}
}
}
}
List<ForeignKey> fks = t.getForeignKeys();
if (fks == null || fks.isEmpty()) {
continue;
}
for (ForeignKey fk:fks) {
if (fk.getPrimaryKey() != null) {
continue;
}
String referenceTableName = fk.getReferenceTableName();
if (referenceTableName == null){
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31091, t.getFullName()));
continue;
}
Table referenceTable = null;
String referenceSchemaName = schema.getName();
int index = referenceTableName.indexOf(Table.NAME_DELIM_CHAR);
if (index == -1) {
referenceTable = schema.getTable(referenceTableName);
}
else {
referenceSchemaName = referenceTableName.substring(0, index);
Schema referenceSchema = store.getSchema(referenceSchemaName);
if (referenceSchema == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31093, referenceSchemaName, t.getFullName()));
continue;
}
referenceTable = referenceSchema.getTable(referenceTableName.substring(index+1));
}
if (referenceTable == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31092, t.getFullName(), referenceTableName.substring(index+1), referenceSchemaName));
continue;
}
KeyRecord uniqueKey = null;
if (fk.getReferenceColumns() == null || fk.getReferenceColumns().isEmpty()) {
if (referenceTable.getPrimaryKey() == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31094, t.getFullName(), referenceTableName.substring(index+1), referenceSchemaName));
}
else {
uniqueKey = referenceTable.getPrimaryKey();
}
} else {
for (KeyRecord record : referenceTable.getUniqueKeys()) {
if (keyMatches(fk.getReferenceColumns(), record)) {
uniqueKey = record;
break;
}
}
if (uniqueKey == null && referenceTable.getPrimaryKey() != null && keyMatches(fk.getReferenceColumns(), referenceTable.getPrimaryKey())) {
uniqueKey = referenceTable.getPrimaryKey();
}
}
if (uniqueKey == null) {
metadataValidator.log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31095, t.getFullName(), referenceTableName.substring(index+1), referenceSchemaName, fk.getReferenceColumns()));
}
else {
fk.setPrimaryKey(uniqueKey);
fk.setUniqueKeyID(uniqueKey.getUUID());
}
}
}
}
}
}
}
|
package dr.app.beauti.options;
import dr.app.beauti.components.continuous.ContinuousSubstModelType;
import dr.app.beauti.components.discrete.DiscreteSubstModelType;
import dr.app.beauti.types.*;
import dr.evolution.datatype.AminoAcids;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Microsatellite;
import dr.evolution.datatype.Nucleotides;
import dr.evomodel.substmodel.AminoAcidModelType;
import dr.evomodel.substmodel.NucModelType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public class PartitionSubstitutionModel extends PartitionOptions {
// Instance variables
public static final String[] GTR_RATE_NAMES = {"ac", "ag", "at", "cg", "gt"};
private static final String[] GTR_TRANSITIONS = {"A-C", "A-G", "A-T", "C-G", "G-T"};
private NucModelType nucSubstitutionModel = NucModelType.HKY;
private AminoAcidModelType aaSubstitutionModel = AminoAcidModelType.BLOSUM_62;
private BinaryModelType binarySubstitutionModel = BinaryModelType.BIN_SIMPLE;
private DiscreteSubstModelType discreteSubstType = DiscreteSubstModelType.SYM_SUBST;
private ContinuousSubstModelType continuousSubstModelType = ContinuousSubstModelType.HOMOGENOUS;
private final int continuousTraitCount;
private boolean activateBSSVS = false;
public boolean useAmbiguitiesTreeLikelihood = false;
private FrequencyPolicyType frequencyPolicy = FrequencyPolicyType.ESTIMATED;
private boolean gammaHetero = false;
private int gammaCategories = 4;
private boolean invarHetero = false;
private String codonHeteroPattern = null;
private boolean unlinkedSubstitutionModel = true;
private boolean unlinkedHeterogeneityModel = true;
private boolean unlinkedFrequencyModel = true;
private boolean dolloModel = false;
private MicroSatModelType.RateProportionality ratePorportion = MicroSatModelType.RateProportionality.EQUAL_RATE;
private MicroSatModelType.MutationalBias mutationBias = MicroSatModelType.MutationalBias.UNBIASED;
private MicroSatModelType.Phase phase = MicroSatModelType.Phase.ONE_PHASE;
private Microsatellite microsatellite = null;
public PartitionSubstitutionModel(BeautiOptions options, AbstractPartitionData partition) {
// this(options, partition.getName(),(partition.getTrait() == null)
// ? partition.getDataType() : GeneralDataType.INSTANCE);
super(options, partition.getName());
if (partition.getTraits() != null && partition.getDataType().getType() == DataType.CONTINUOUS) {
continuousTraitCount = partition.getTraits().size();
} else {
continuousTraitCount = 0;
}
}
/**
* A copy constructor
*
* @param options the beauti options
* @param name the name of the new model
* @param source the source model
*/
public PartitionSubstitutionModel(BeautiOptions options, String name, PartitionSubstitutionModel source) {
super(options, name);
nucSubstitutionModel = source.nucSubstitutionModel;
aaSubstitutionModel = source.aaSubstitutionModel;
binarySubstitutionModel = source.binarySubstitutionModel;
discreteSubstType = source.discreteSubstType;
continuousSubstModelType = source.continuousSubstModelType;
continuousTraitCount = source.continuousTraitCount;
activateBSSVS = source.activateBSSVS;
useAmbiguitiesTreeLikelihood = source.useAmbiguitiesTreeLikelihood;
frequencyPolicy = source.frequencyPolicy;
gammaHetero = source.gammaHetero;
gammaCategories = source.gammaCategories;
invarHetero = source.invarHetero;
codonHeteroPattern = source.codonHeteroPattern;
unlinkedSubstitutionModel = source.unlinkedSubstitutionModel;
unlinkedHeterogeneityModel = source.unlinkedHeterogeneityModel;
unlinkedFrequencyModel = source.unlinkedFrequencyModel;
dolloModel = source.dolloModel;
ratePorportion = source.ratePorportion;
mutationBias = source.mutationBias;
phase = source.phase;
microsatellite = source.microsatellite;
}
public PartitionSubstitutionModel(BeautiOptions options, String name) {
super(options, name);
continuousTraitCount = 0;
}
// only init in PartitionSubstitutionModel
protected void initModelParametersAndOpererators() {
double substWeights = 0.1;
//Substitution model parameters
createZeroOneParameterUniformPrior("frequencies", "base frequencies", 0.25);
createZeroOneParameterUniformPrior("CP1.frequencies", "base frequencies for codon position 1", 0.25);
createZeroOneParameterUniformPrior("CP2.frequencies", "base frequencies for codon position 2", 0.25);
createZeroOneParameterUniformPrior("CP1+2.frequencies", "base frequencies for codon positions 1 & 2", 0.25);
createZeroOneParameterUniformPrior("CP3.frequencies", "base frequencies for codon position 3", 0.25);
//This prior is moderately diffuse with a median of 2.718
createParameterLognormalPrior("kappa", "HKY transition-transversion parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1.kappa", "HKY transition-transversion parameter for codon position 1",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP2.kappa", "HKY transition-transversion parameter for codon position 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1+2.kappa", "HKY transition-transversion parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP3.kappa", "HKY transition-transversion parameter for codon position 3",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("kappa1", "TN93 1st transition-transversion parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1.kappa1", "TN93 1st transition-transversion parameter for codon position 1",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP2.kappa1", "TN93 1st transition-transversion parameter for codon position 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1+2.kappa1", "TN93 1st transition-transversion parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP3.kappa1", "TN93 1st transition-transversion parameter for codon position 3",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("kappa2", "TN93 2nd transition-transversion parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1.kappa2", "TN93 2nd transition-transversion parameter for codon position 1",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP2.kappa2", "TN93 2nd transition-transversion parameter for codon position 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP1+2.kappa2", "TN93 2nd transition-transversion parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
createParameterLognormalPrior("CP3.kappa2", "TN93 2nd transition-transversion parameter for codon position 3",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY);
// createParameter("frequencies", "GTR base frequencies", UNITY_SCALE, 0.25, 0.0, 1.0);
// createParameter("CP1.frequencies", "GTR base frequencies for codon position 1", UNITY_SCALE, 0.25, 0.0, 1.0);
// createParameter("CP2.frequencies", "GTR base frequencies for codon position 2", UNITY_SCALE, 0.25, 0.0, 1.0);
// createParameter("CP1+2.frequencies", "GTR base frequencies for codon positions 1 & 2", UNITY_SCALE, 0.25, 0.0, 1.0);
// createParameter("CP3.frequencies", "GTR base frequencies for codon position 3", UNITY_SCALE, 0.25, 0.0, 1.0);
// create the relative rate parameters for the GTR rate matrix
for (int j = 0; j < 5; j++) {
if (j == 1) {
createParameterGammaPrior(GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, false);
} else {
createParameterGammaPrior(GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, false);
}
for (int i = 1; i <= 3; i++) {
if (j == 1) {
createParameterGammaPrior("CP" + i + "." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon position " + i,
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, false);
} else {
createParameterGammaPrior("CP" + i + "." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon position " + i,
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, false);
}
}
if (j == 1) {
createParameterGammaPrior("CP1+2." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, false);
} else {
createParameterGammaPrior("CP1+2." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, false);
}
}
// createParameter("frequencies", "Binary Simple frequencies", UNITY_SCALE, 0.5, 0.0, 1.0);
// createParameter("frequencies", "Binary Covarion frequencies of the visible states", UNITY_SCALE, 0.5, 0.0, 1.0);
createZeroOneParameterUniformPrior("hfrequencies", "Binary Covarion frequencies of the hidden rates", 0.5);
createZeroOneParameterUniformPrior("bcov.alpha", "Binary Covarion rate of evolution in slow mode", 0.5);
createParameterGammaPrior("bcov.s", "Binary Covarion rate of flipping between slow and fast modes",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.05, 10, false);
createParameterExponentialPrior("alpha", "gamma shape parameter",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0);
createParameterExponentialPrior("CP1.alpha", "gamma shape parameter for codon position 1",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0);
createParameterExponentialPrior("CP2.alpha", "gamma shape parameter for codon position 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0);
createParameterExponentialPrior("CP1+2.alpha", "gamma shape parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0);
createParameterExponentialPrior("CP3.alpha", "gamma shape parameter for codon position 3",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0);
createZeroOneParameterUniformPrior("pInv", "proportion of invariant sites parameter", 0.5);
createZeroOneParameterUniformPrior("CP1.pInv", "proportion of invariant sites parameter for codon position 1", 0.5);
createZeroOneParameterUniformPrior("CP2.pInv", "proportion of invariant sites parameter for codon position 2", 0.5);
createZeroOneParameterUniformPrior("CP1+2.pInv", "proportion of invariant sites parameter for codon positions 1 & 2", 0.5);
createZeroOneParameterUniformPrior("CP3.pInv", "proportion of invariant sites parameter for codon position 3", 0.5);
createNonNegativeParameterInfinitePrior("mu", "relative rate parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0);
createNonNegativeParameterInfinitePrior("CP1.mu", "relative rate parameter for codon position 1",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0);
createNonNegativeParameterInfinitePrior("CP2.mu", "relative rate parameter for codon position 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0);
createNonNegativeParameterInfinitePrior("CP1+2.mu", "relative rate parameter for codon positions 1 & 2",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0);
createNonNegativeParameterInfinitePrior("CP3.mu", "relative rate parameter for codon position 3",
PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0);
// A vector of relative rates across all partitions...
createAllMusParameter(this, "allMus", "All the relative rates regarding codon positions");
// This only works if the partitions are of the same size...
// createOperator("centeredMu", "Relative rates",
// "Scales codon position rates relative to each other maintaining mean", "allMus",
// OperatorType.CENTERED_SCALE, 0.75, 3.0);
createOperator("deltaMu", RelativeRatesType.MU_RELATIVE_RATES.toString(),
"Currently use to scale codon position rates relative to each other maintaining mean", "allMus",
OperatorType.DELTA_EXCHANGE, 0.75, 3.0);
createScaleOperator("kappa", demoTuning, substWeights);
createScaleOperator("CP1.kappa", demoTuning, substWeights);
createScaleOperator("CP2.kappa", demoTuning, substWeights);
createScaleOperator("CP1+2.kappa", demoTuning, substWeights);
createScaleOperator("CP3.kappa", demoTuning, substWeights);
createScaleOperator("kappa1", demoTuning, substWeights);
createScaleOperator("CP1.kappa1", demoTuning, substWeights);
createScaleOperator("CP2.kappa1", demoTuning, substWeights);
createScaleOperator("CP1+2.kappa1", demoTuning, substWeights);
createScaleOperator("CP3.kappa1", demoTuning, substWeights);
createScaleOperator("kappa2", demoTuning, substWeights);
createScaleOperator("CP1.kappa2", demoTuning, substWeights);
createScaleOperator("CP2.kappa2", demoTuning, substWeights);
createScaleOperator("CP1+2.kappa2", demoTuning, substWeights);
createScaleOperator("CP3.kappa2", demoTuning, substWeights);
createOperator("frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
createOperator("CP1.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
createOperator("CP2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
createOperator("CP1+2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
createOperator("CP3.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
for (String rateName : GTR_RATE_NAMES) {
createScaleOperator(rateName, demoTuning, substWeights);
for (int j = 1; j <= 3; j++) {
createScaleOperator("CP" + j + "." + rateName, demoTuning, substWeights);
}
createScaleOperator("CP1+2." + rateName, demoTuning, substWeights);
}
createScaleOperator("alpha", demoTuning, substWeights);
for (int i = 1; i <= 3; i++) {
createScaleOperator("CP" + i + ".alpha", demoTuning, substWeights);
}
createScaleOperator("CP1+2.alpha", demoTuning, substWeights);
createScaleOperator("pInv", demoTuning, substWeights);
for (int i = 1; i <= 3; i++) {
createScaleOperator("CP" + i + ".pInv", demoTuning, substWeights);
}
createScaleOperator("CP1+2.pInv", demoTuning, substWeights);
createScaleOperator("bcov.alpha", demoTuning, substWeights);
createScaleOperator("bcov.s", demoTuning, substWeights);
createOperator("hfrequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights);
createParameterGammaPrior("propLinear", "Proportionality linear function",
PriorScaleType.NONE, 0.5, 1.0, 1.0, false);
createParameterNormalPrior("biasConst", "Constant bias", PriorScaleType.NONE,
0.0, 0.0, 10.0, 0.0);
createParameterNormalPrior("biasLinear", "Linear bias", PriorScaleType.NONE,
0.0, 0.0, 10.0, 0.0);
createZeroOneParameterUniformPrior("geomDist", "The success probability of geometric distribution", 0.5);
createZeroOneParameterUniformPrior("onePhaseProb", "A probability of geomDist being the last step of series", 1.0);
createScaleOperator("propLinear", demoTuning, substWeights);
// createOperator("deltaBiasConst", "deltaBiasConst", "Delta exchange on constant bias", "biasConst",
// OperatorType.DELTA_EXCHANGE, 0.001, 1.6);
createOperator("randomWalkBiasConst", "randomWalkBiasConst", "Random walk on constant bias", "biasConst",
OperatorType.RANDOM_WALK, 0.01, 2.0);
createOperator("randomWalkBiasLinear", "randomWalkBiasLinear", "Random walk on linear bias", "biasLinear",
OperatorType.RANDOM_WALK, 0.001, 2.0);
createOperator("randomWalkGeom", "randomWalkGeom", "Random walk on geomDist", "geomDist",
OperatorType.RANDOM_WALK, 0.01, 2.0);
}
public void selectParameters(List<Parameter> params) {
setAvgRootAndRate();
boolean includeRelativeRates = getCodonPartitionCount() > 1;//TODO check
switch (getDataType().getType()) {
case DataType.NUCLEOTIDES:
if (includeRelativeRates && unlinkedSubstitutionModel) {
if (codonHeteroPattern.equals("123")) {
switch (nucSubstitutionModel) {
case HKY:
params.add(getParameter("CP1.kappa"));
params.add(getParameter("CP2.kappa"));
params.add(getParameter("CP3.kappa"));
break;
case TN93:
params.add(getParameter("CP1.kappa1"));
params.add(getParameter("CP2.kappa1"));
params.add(getParameter("CP3.kappa1"));
params.add(getParameter("CP1.kappa2"));
params.add(getParameter("CP2.kappa2"));
params.add(getParameter("CP3.kappa2"));
break;
case GTR:
for (int i = 1; i <= getCodonPartitionCount(); i++) {
for (String rateName : GTR_RATE_NAMES) {
params.add(getParameter("CP" + i + "." + rateName));
}
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
} else if (codonHeteroPattern.equals("112")) {
switch (nucSubstitutionModel) {
case HKY:
params.add(getParameter("CP1+2.kappa"));
params.add(getParameter("CP3.kappa"));
break;
case TN93:
params.add(getParameter("CP1+2.kappa1"));
params.add(getParameter("CP3.kappa1"));
params.add(getParameter("CP1+2.kappa2"));
params.add(getParameter("CP3.kappa2"));
break;
case GTR:
for (String rateName : GTR_RATE_NAMES) {
params.add(getParameter("CP1+2." + rateName));
}
for (String rateName : GTR_RATE_NAMES) {
params.add(getParameter("CP3." + rateName));
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else { // no codon partitioning, or unlinkedSubstitutionModel
switch (nucSubstitutionModel) {
case HKY:
params.add(getParameter("kappa"));
break;
case TN93:
params.add(getParameter("kappa1"));
params.add(getParameter("kappa2"));
break;
case GTR:
for (String rateName : GTR_RATE_NAMES) {
params.add(getParameter(rateName));
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
}
if (includeRelativeRates) {
if (codonHeteroPattern.equals("123")) {
params.add(getParameter("CP1.mu"));
params.add(getParameter("CP2.mu"));
params.add(getParameter("CP3.mu"));
} else if (codonHeteroPattern.equals("112")) {
params.add(getParameter("CP1+2.mu"));
params.add(getParameter("CP3.mu"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else { // no codon partitioning
//TODO
}
// only AMINO_ACIDS not addFrequency
addFrequencyParams(params, includeRelativeRates);
break;
case DataType.AMINO_ACIDS:
if (includeRelativeRates) {
params.add(getParameter("mu"));
}
break;
case DataType.TWO_STATES:
case DataType.COVARION:
switch (binarySubstitutionModel) {
case BIN_SIMPLE:
case BIN_DOLLO:
break;
case BIN_COVARION:
// useAmbiguitiesTreeLikelihood = true;
params.add(getParameter("bcov.alpha"));
params.add(getParameter("bcov.s"));
params.add(getParameter("hfrequencies")); // no codon for binary
break;
default:
throw new IllegalArgumentException("Unknown binary substitution model");
}
if (includeRelativeRates) {
params.add(getParameter("mu"));
}
// only AMINO_ACIDS not addFrequency
addFrequencyParams(params, includeRelativeRates);
break;
case DataType.GENERAL:
// This model is controlled by DiscreteTraitComponentOptions
break;
case DataType.CONTINUOUS:
// This model is controlled by ContinuousTraitComponentOptions
break;
case DataType.MICRO_SAT:
if (ratePorportion == MicroSatModelType.RateProportionality.EQUAL_RATE) {
} else if (ratePorportion == MicroSatModelType.RateProportionality.PROPORTIONAL_RATE) {
params.add(getParameter("propLinear"));
} else if (ratePorportion == MicroSatModelType.RateProportionality.ASYM_QUAD) {
}
if (mutationBias == MicroSatModelType.MutationalBias.UNBIASED) {
} else if (mutationBias == MicroSatModelType.MutationalBias.CONSTANT_BIAS) {
params.add(getParameter("biasConst"));
} else if (mutationBias == MicroSatModelType.MutationalBias.LINEAR_BIAS) {
params.add(getParameter("biasConst"));
params.add(getParameter("biasLinear"));
}
if (phase == MicroSatModelType.Phase.ONE_PHASE) {
} else if (phase == MicroSatModelType.Phase.TWO_PHASE) {
params.add(getParameter("geomDist"));
} else if (phase == MicroSatModelType.Phase.TWO_PHASE_STAR) {
params.add(getParameter("geomDist"));
params.add(getParameter("onePhaseProb"));
}
break;
default:
throw new IllegalArgumentException("Unknown data type");
}
// if gamma do shape move
if (gammaHetero) {
if (includeRelativeRates && unlinkedHeterogeneityModel) {
if (codonHeteroPattern.equals("123")) {
params.add(getParameter("CP1.alpha"));
params.add(getParameter("CP2.alpha"));
params.add(getParameter("CP3.alpha"));
} else if (codonHeteroPattern.equals("112")) {
params.add(getParameter("CP1+2.alpha"));
params.add(getParameter("CP3.alpha"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
params.add(getParameter("alpha"));
}
}
// if pinv do pinv move
if (invarHetero) {
if (includeRelativeRates && unlinkedHeterogeneityModel) {
if (codonHeteroPattern.equals("123")) {
params.add(getParameter("CP1.pInv"));
params.add(getParameter("CP2.pInv"));
params.add(getParameter("CP3.pInv"));
} else if (codonHeteroPattern.equals("112")) {
params.add(getParameter("CP1+2.pInv"));
params.add(getParameter("CP3.pInv"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
params.add(getParameter("pInv"));
}
}
if (hasCodon()) getParameter("allMus");
}
private void addFrequencyParams(List<Parameter> params, boolean includeRelativeRates) {
if (frequencyPolicy == FrequencyPolicyType.ESTIMATED) {
if (includeRelativeRates && unlinkedSubstitutionModel && unlinkedFrequencyModel) {
if (codonHeteroPattern.equals("123")) {
params.add(getParameter("CP1.frequencies"));
params.add(getParameter("CP2.frequencies"));
params.add(getParameter("CP3.frequencies"));
} else if (codonHeteroPattern.equals("112")) {
params.add(getParameter("CP1+2.frequencies"));
params.add(getParameter("CP3.frequencies"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
params.add(getParameter("frequencies"));
}
}
}
public void selectOperators(List<Operator> ops) {
boolean includeRelativeRates = getCodonPartitionCount() > 1;//TODO check
switch (getDataType().getType()) {
case DataType.NUCLEOTIDES:
if (includeRelativeRates && unlinkedSubstitutionModel) {
if (codonHeteroPattern.equals("123")) {
switch (nucSubstitutionModel) {
case HKY:
ops.add(getOperator("CP1.kappa"));
ops.add(getOperator("CP2.kappa"));
ops.add(getOperator("CP3.kappa"));
break;
case TN93:
ops.add(getOperator("CP1.kappa1"));
ops.add(getOperator("CP2.kappa1"));
ops.add(getOperator("CP3.kappa1"));
ops.add(getOperator("CP1.kappa2"));
ops.add(getOperator("CP2.kappa2"));
ops.add(getOperator("CP3.kappa2"));
break;
case GTR:
for (int i = 1; i <= 3; i++) {
for (String rateName : GTR_RATE_NAMES) {
ops.add(getOperator("CP" + i + "." + rateName));
}
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
} else if (codonHeteroPattern.equals("112")) {
switch (nucSubstitutionModel) {
case HKY:
ops.add(getOperator("CP1+2.kappa"));
ops.add(getOperator("CP3.kappa"));
break;
case TN93:
ops.add(getOperator("CP1+2.kappa1"));
ops.add(getOperator("CP3.kappa1"));
ops.add(getOperator("CP1+2.kappa2"));
ops.add(getOperator("CP3.kappa2"));
break;
case GTR:
for (String rateName : GTR_RATE_NAMES) {
ops.add(getOperator("CP1+2." + rateName));
}
for (String rateName : GTR_RATE_NAMES) {
ops.add(getOperator("CP3." + rateName));
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else { // no codon partitioning, or unlinkedSubstitutionModel
switch (nucSubstitutionModel) {
case HKY:
ops.add(getOperator("kappa"));
break;
case TN93:
ops.add(getOperator("kappa1"));
ops.add(getOperator("kappa2"));
break;
case GTR:
for (String rateName : GTR_RATE_NAMES) {
ops.add(getOperator(rateName));
}
break;
default:
throw new IllegalArgumentException("Unknown nucleotides substitution model");
}
}
// only AMINO_ACIDS not addFrequency
addFrequencyOps(ops, includeRelativeRates);
break;
case DataType.AMINO_ACIDS:
break;
case DataType.TWO_STATES:
case DataType.COVARION:
switch (binarySubstitutionModel) {
case BIN_SIMPLE:
case BIN_DOLLO:
break;
case BIN_COVARION:
ops.add(getOperator("bcov.alpha"));
ops.add(getOperator("bcov.s"));
ops.add(getOperator("hfrequencies"));
break;
default:
throw new IllegalArgumentException("Unknown binary substitution model");
}
// only AMINO_ACIDS not addFrequency
addFrequencyOps(ops, includeRelativeRates);
break;
case DataType.GENERAL:
break;
case DataType.CONTINUOUS:
break;
case DataType.MICRO_SAT:
if (ratePorportion == MicroSatModelType.RateProportionality.EQUAL_RATE) {
} else if (ratePorportion == MicroSatModelType.RateProportionality.PROPORTIONAL_RATE) {
ops.add(getOperator("propLinear"));
} else if (ratePorportion == MicroSatModelType.RateProportionality.ASYM_QUAD) {
}
if (mutationBias == MicroSatModelType.MutationalBias.UNBIASED) {
} else if (mutationBias == MicroSatModelType.MutationalBias.CONSTANT_BIAS) {
ops.add(getOperator("randomWalkBiasConst"));
} else if (mutationBias == MicroSatModelType.MutationalBias.LINEAR_BIAS) {
ops.add(getOperator("randomWalkBiasConst"));
ops.add(getOperator("randomWalkBiasLinear"));
}
if (phase == MicroSatModelType.Phase.ONE_PHASE) {
} else if (phase == MicroSatModelType.Phase.TWO_PHASE) {
ops.add(getOperator("randomWalkGeom"));
} else if (phase == MicroSatModelType.Phase.TWO_PHASE_STAR) {
// ops.add(getOperator("randomWalkGeom"));
// ops.add(getOperator("onePhaseProb"));
}
break;
default:
throw new IllegalArgumentException("Unknown data type");
}
// if gamma do shape move
if (gammaHetero) {
if (includeRelativeRates && unlinkedHeterogeneityModel) {
if (codonHeteroPattern.equals("123")) {
ops.add(getOperator("CP1.alpha"));
ops.add(getOperator("CP2.alpha"));
ops.add(getOperator("CP3.alpha"));
} else if (codonHeteroPattern.equals("112")) {
ops.add(getOperator("CP1+2.alpha"));
ops.add(getOperator("CP3.alpha"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
ops.add(getOperator("alpha"));
}
}
// if pinv do pinv move
if (invarHetero) {
if (includeRelativeRates && unlinkedHeterogeneityModel) {
if (codonHeteroPattern.equals("123")) {
ops.add(getOperator("CP1.pInv"));
ops.add(getOperator("CP2.pInv"));
ops.add(getOperator("CP3.pInv"));
} else if (codonHeteroPattern.equals("112")) {
ops.add(getOperator("CP1+2.pInv"));
ops.add(getOperator("CP3.pInv"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
ops.add(getOperator("pInv"));
}
}
if (hasCodon()) {
Operator deltaMuOperator = getOperator("deltaMu");
// update delta mu operator weight
deltaMuOperator.weight = 0.0;
for (PartitionSubstitutionModel pm : options.getPartitionSubstitutionModels()) {
deltaMuOperator.weight += pm.getCodonPartitionCount();
}
ops.add(deltaMuOperator);
}
}
private void addFrequencyOps(List<Operator> ops, boolean includeRelativeRates) {
if (frequencyPolicy == FrequencyPolicyType.ESTIMATED) {
if (includeRelativeRates && unlinkedSubstitutionModel && unlinkedFrequencyModel) {
if (codonHeteroPattern.equals("123")) {
ops.add(getOperator("CP1.frequencies"));
ops.add(getOperator("CP2.frequencies"));
ops.add(getOperator("CP3.frequencies"));
} else if (codonHeteroPattern.equals("112")) {
ops.add(getOperator("CP1+2.frequencies"));
ops.add(getOperator("CP3.frequencies"));
} else {
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
} else {
ops.add(getOperator("frequencies"));
}
}
}
/**
* @return true either if the options have more than one partition or any partition is
* broken into codon positions.
*/
public boolean hasCodon() {
return getCodonPartitionCount() > 1;
}
public int getCodonPartitionCount() {
if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) {
return 1;
}
if (codonHeteroPattern.equals("123")) {
return 3;
}
if (codonHeteroPattern.equals("112")) {
return 2;
}
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
public void addWeightsForPartition(AbstractPartitionData partition, int[] weights, int offset) {
int n = partition.getSiteCount();
int codonCount = n / 3;
int remainder = n % 3;
if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) {
weights[offset] += n;
return;
}
if (codonHeteroPattern.equals("123")) {
weights[offset] += codonCount + (remainder > 0 ? 1 : 0);
weights[offset + 1] += codonCount + (remainder > 1 ? 1 : 0);
weights[offset + 2] += codonCount;
return;
}
if (codonHeteroPattern.equals("112")) {
weights[offset] += codonCount * 2 + remainder; // positions 1 + 2
weights[offset + 1] += codonCount; // position 3
return;
}
throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'");
}
/**
* This returns an integer vector of the number of sites in each partition (including any codon partitions). These
* are strictly in the same order as the 'mu' relative rates are listed.
*
* @return weights for each partition model
*/
public int[] getPartitionCodonWeights() {
int[] weights = new int[getCodonPartitionCount()];
int k = 0;
for (AbstractPartitionData partition : options.getDataPartitions(this)) {
if (partition.getPartitionSubstitutionModel() == this) {
addWeightsForPartition(partition, weights, k);
}
}
k += getCodonPartitionCount();
assert (k == weights.length);
return weights;
}
public NucModelType getNucSubstitutionModel() {
return nucSubstitutionModel;
}
public void setNucSubstitutionModel(NucModelType nucSubstitutionModel) {
this.nucSubstitutionModel = nucSubstitutionModel;
}
public AminoAcidModelType getAaSubstitutionModel() {
return aaSubstitutionModel;
}
public void setAaSubstitutionModel(AminoAcidModelType aaSubstitutionModel) {
this.aaSubstitutionModel = aaSubstitutionModel;
}
public BinaryModelType getBinarySubstitutionModel() {
return binarySubstitutionModel;
}
public void setBinarySubstitutionModel(BinaryModelType binarySubstitutionModel) {
this.binarySubstitutionModel = binarySubstitutionModel;
}
public DiscreteSubstModelType getDiscreteSubstType() {
return discreteSubstType;
}
public void setDiscreteSubstType(DiscreteSubstModelType discreteSubstType) {
this.discreteSubstType = discreteSubstType;
}
public ContinuousSubstModelType getContinuousSubstModelType() {
return continuousSubstModelType;
}
public void setContinuousSubstModelType(final ContinuousSubstModelType continuousSubstModelType) {
this.continuousSubstModelType = continuousSubstModelType;
}
public int getContinuousTraitCount() {
return continuousTraitCount;
}
public MicroSatModelType.RateProportionality getRatePorportion() {
return ratePorportion;
}
public void setRatePorportion(MicroSatModelType.RateProportionality ratePorportion) {
this.ratePorportion = ratePorportion;
}
public MicroSatModelType.MutationalBias getMutationBias() {
return mutationBias;
}
public void setMutationBias(MicroSatModelType.MutationalBias mutationBias) {
this.mutationBias = mutationBias;
}
public MicroSatModelType.Phase getPhase() {
return phase;
}
public void setPhase(MicroSatModelType.Phase phase) {
this.phase = phase;
}
public Microsatellite getMicrosatellite() {
return microsatellite;
}
public void setMicrosatellite(Microsatellite microsatellite) {
this.microsatellite = microsatellite;
}
public boolean isActivateBSSVS() {
return activateBSSVS;
}
public void setActivateBSSVS(boolean activateBSSVS) {
this.activateBSSVS = activateBSSVS;
}
public FrequencyPolicyType getFrequencyPolicy() {
return frequencyPolicy;
}
public void setFrequencyPolicy(FrequencyPolicyType frequencyPolicy) {
this.frequencyPolicy = frequencyPolicy;
}
public boolean isGammaHetero() {
return gammaHetero;
}
public void setGammaHetero(boolean gammaHetero) {
this.gammaHetero = gammaHetero;
}
public int getGammaCategories() {
return gammaCategories;
}
public void setGammaCategories(int gammaCategories) {
this.gammaCategories = gammaCategories;
}
public boolean isInvarHetero() {
return invarHetero;
}
public void setInvarHetero(boolean invarHetero) {
this.invarHetero = invarHetero;
}
public String getCodonHeteroPattern() {
return codonHeteroPattern;
}
public void setCodonHeteroPattern(String codonHeteroPattern) {
this.codonHeteroPattern = codonHeteroPattern;
}
/**
* @return true if the rate matrix parameters are unlinked across codon positions
*/
public boolean isUnlinkedSubstitutionModel() {
return unlinkedSubstitutionModel;
}
public void setUnlinkedSubstitutionModel(boolean unlinkedSubstitutionModel) {
this.unlinkedSubstitutionModel = unlinkedSubstitutionModel;
}
public boolean isUnlinkedHeterogeneityModel() {
return unlinkedHeterogeneityModel;
}
public void setUnlinkedHeterogeneityModel(boolean unlinkedHeterogeneityModel) {
this.unlinkedHeterogeneityModel = unlinkedHeterogeneityModel;
}
public boolean isUnlinkedFrequencyModel() {
return unlinkedFrequencyModel;
}
public void setUnlinkedFrequencyModel(boolean unlinkedFrequencyModel) {
this.unlinkedFrequencyModel = unlinkedFrequencyModel;
}
public boolean isDolloModel() {
return dolloModel;
}
public void setDolloModel(boolean dolloModel) {
this.dolloModel = dolloModel;
}
public boolean isUseAmbiguitiesTreeLikelihood() {
return useAmbiguitiesTreeLikelihood;
}
public void setUseAmbiguitiesTreeLikelihood(boolean useAmbiguitiesTreeLikelihood) {
this.useAmbiguitiesTreeLikelihood = useAmbiguitiesTreeLikelihood;
}
public String getPrefix() {
String prefix = "";
if (options.getPartitionSubstitutionModels(Nucleotides.INSTANCE).size() +
options.getPartitionSubstitutionModels(AminoAcids.INSTANCE).size() > 1) {
// There is more than one active partition model, or doing species analysis
prefix += getName() + ".";
}
return prefix;
}
public String getPrefix(DataType dataType) {
String prefix = "";
if (options.getPartitionSubstitutionModels(dataType).size() > 1) {
// There is more than one active partition model, or doing species analysis
prefix += getName() + ".";
}
return prefix;
}
public String getPrefix(int codonPartitionNumber) {
String prefix = "";
prefix += getPrefix();
prefix += getPrefixCodon(codonPartitionNumber);
return prefix;
}
public String getPrefixCodon(int codonPartitionNumber) {
String prefix = "";
if (getCodonPartitionCount() > 1 && codonPartitionNumber > 0) {
if (getCodonHeteroPattern().equals("123")) {
prefix += "CP" + codonPartitionNumber + ".";
} else if (getCodonHeteroPattern().equals("112")) {
if (codonPartitionNumber == 1) {
prefix += "CP1+2.";
} else {
prefix += "CP3.";
}
} else {
throw new IllegalArgumentException("unsupported codon hetero pattern");
}
}
return prefix;
}
/**
* returns the union of the set of states for all traits using this discrete CTMC model
*
* @return
*/
public Set<String> getDiscreteStateSet() {
Set<String> states = new HashSet<String>();
for (AbstractPartitionData partition : options.getDataPartitions(this)) {
if (partition.getTraits() != null) {
states.addAll(partition.getTraits().get(0).getStatesOfTrait(options.taxonList));
}
}
return states;
}
}
|
package dr.inference.distribution;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.math.UnivariateFunction;
import dr.math.distributions.GammaDistribution;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.GammaDistributionImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* A class that acts as a model for gamma distributed data.
*
* @author Alexei Drummond
* @version $Id: GammaDistributionModel.java,v 1.6 2005/05/24 20:25:59 rambaut Exp $
*/
public class GammaDistributionModel extends AbstractModel implements ParametricDistributionModel {
public static final String GAMMA_DISTRIBUTION_MODEL = "gammaDistributionModel";
public static final String ONE_P_GAMMA_DISTRIBUTION_MODEL = "onePGammaDistributionModel";
/**
* Construct a constant mutation rate model.
*/
public GammaDistributionModel(Variable<Double> shape, Variable<Double> scale) {
super(GAMMA_DISTRIBUTION_MODEL);
this.shape = shape;
this.scale = scale;
addVariable(shape);
shape.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
if (scale != null) {
addVariable(scale);
scale.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
}
}
/**
* Construct a constant mutation rate model.
*/
public GammaDistributionModel(Variable<Double> shape) {
super(GAMMA_DISTRIBUTION_MODEL);
this.shape = shape;
addVariable(shape);
shape.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
}
// Interface Distribution
public double pdf(double x) {
return GammaDistribution.pdf(x, getShape(), getScale());
}
public double logPdf(double x) {
return GammaDistribution.logPdf(x, getShape(), getScale());
}
public double cdf(double x) {
return GammaDistribution.cdf(x, getShape(), getScale());
}
public double quantile(double y) {
try {
return (new GammaDistributionImpl(getShape(), getScale())).inverseCumulativeProbability(y);
} catch (MathException e) {
return Double.NaN;
}
}
public double mean() {
return GammaDistribution.mean(getShape(), getScale());
}
public double variance() {
return GammaDistribution.variance(getShape(), getScale());
}
public final UnivariateFunction getProbabilityDensityFunction() {
return pdfFunction;
}
private final UnivariateFunction pdfFunction = new UnivariateFunction() {
public final double evaluate(double x) {
return pdf(x);
}
public final double getLowerBound() {
return 0.0;
}
public final double getUpperBound() {
return Double.POSITIVE_INFINITY;
}
};
// Interface Model
public void handleModelChangedEvent(Model model, Object object, int index) {
// no intermediates need to be recalculated...
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
// no intermediates need to be recalculated...
}
protected void storeState() {
} // no additional state needs storing
protected void restoreState() {
} // no additional state needs restoring
protected void acceptState() {
} // no additional state needs accepting
// XMLElement IMPLEMENTATION
public Element createElement(Document document) {
throw new RuntimeException("Not implemented!");
}
public double getShape() {
return shape.getValue(0);
}
public double getScale() {
if (scale == null) return (1.0 / getShape());
return scale.getValue(0);
}
// Private instance variables
private Variable<Double> shape = null;
private Variable<Double> scale = null;
}
|
package edu.berkeley.guir.prefuse.action;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Node;
public class GraphEdgeFilter extends Filter {
private boolean m_edgesVisible;
/**
* Filters graph edges, connecting filtered graph nodes into a
* graph structure. Filtered edges are visible by default.
*/
public GraphEdgeFilter() {
this(true);
}
/**
* Filters graph edges, connecting filtered graph nodes into a
* graph structure. DefaultEdge visibility can be controlled.
* @param edgesVisible determines whether or not the filtered
* edges are visible in the display.
*/
public GraphEdgeFilter(boolean edgesVisible) {
super(ItemRegistry.DEFAULT_EDGE_CLASS, true);
m_edgesVisible = edgesVisible;
}
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Iterator nodeIter = registry.getNodeItems();
while ( nodeIter.hasNext() ) {
NodeItem nitem = (NodeItem)nodeIter.next();
Node node = (Node)nitem.getEntity();
Iterator edgeIter = node.getEdges();
while ( edgeIter.hasNext() ) {
Edge edge = (Edge)edgeIter.next();
Node n = edge.getAdjacentNode(node);
if ( registry.isVisible(n) ) {
EdgeItem eitem = registry.getEdgeItem(edge, true);
nitem.addEdge(eitem);
if ( !m_edgesVisible ) eitem.setVisible(false);
}
}
}
// optional garbage collection
super.run(registry, frac);
}
} // end of class GraphEdgeFilter
|
package org.voovan.tools.pool;
import org.voovan.Global;
import org.voovan.tools.TEnv;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.json.JSON;
import org.voovan.tools.reflect.TReflect;
import org.voovan.tools.reflect.annotation.NotSerialization;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
public class ObjectPool<T> {
private volatile ConcurrentHashMap<Long, PooledObject<T>> objects = new ConcurrentHashMap<Long, PooledObject<T>>();
private volatile LinkedBlockingDeque<Long> unborrowedIdList = new LinkedBlockingDeque<Long>();
private long aliveTime = 0;
private boolean autoRefreshOnGet = true;
private Function<T, Boolean> destory;
private Supplier<T> supplier = null;
private int minSize = 0;
private int maxSize = Integer.MAX_VALUE;
private int interval = 1;
/**
*
* @param aliveTime ,0,:
* @param autoRefreshOnGet
*/
public ObjectPool(long aliveTime, boolean autoRefreshOnGet){
this.aliveTime = aliveTime;
this.autoRefreshOnGet = autoRefreshOnGet;
}
/**
*
* @param aliveTime ,:
*/
public ObjectPool(long aliveTime){
this.aliveTime = aliveTime;
}
public ObjectPool(){
}
public long getAliveTime() {
return aliveTime;
}
public ObjectPool autoRefreshOnGet(boolean autoRefreshOnGet) {
this.autoRefreshOnGet = autoRefreshOnGet;
return this;
}
public int getMinSize() {
return minSize;
}
public ObjectPool minSize(int minSize) {
this.minSize = minSize;
return this;
}
public int getMaxSize() {
return maxSize;
}
public ObjectPool maxSize(int maxSize) {
this.maxSize = maxSize;
return this;
}
public int getInterval() {
return interval;
}
public ObjectPool interval(int interval) {
this.interval = interval;
return this;
}
/**
*
*
* @return
*/
public Supplier getSupplier() {
return supplier;
}
/**
*
*
* @param supplier
* @return ObjectPool
*/
public ObjectPool supplier(Supplier supplier) {
this.supplier = supplier;
return this;
}
/**
*
*
* @return
*/
public Function destory() {
return destory;
}
/**
*
*
* @param destory
* @return ObjectPool
*/
public ObjectPool destory(Function destory) {
this.destory = destory;
return this;
}
/**
*
* @param aliveTime ,:
* @return ObjectPool
*/
public ObjectPool aliveTime(long aliveTime) {
this.aliveTime = aliveTime;
return this;
}
/**
* ObjectId
* @return ObjectId
*/
private long genObjectId(){
return Global.UNIQUE_ID.nextNumber();
}
/**
*
* @return
*/
public boolean isAutoRefreshOnGet(){
return autoRefreshOnGet;
}
/**
*
* @param obj
* @return id
*/
public Long add(T obj){
return add(obj, false);
}
/**
*
* @param obj
* @parma
* @return id
*/
private Long add(T obj, boolean isBorrow){
Objects.requireNonNull(obj, "add a null object failed");
if(obj instanceof PoolObject) {
if (objects.size() >= maxSize) {
return null;
}
long id = genObjectId();
((PoolObject)obj).setPoolObjectId(id);
PooledObject pooledObject = new PooledObject<T>(this, id, obj);
objects.put(id, pooledObject);
if(!isBorrow) {
unborrowedIdList.offer(id);
}
return id;
} else {
throw new RuntimeException("the Object is not implement PoolBase interface, please make " + TReflect.getClassName(obj.getClass()) +
" implemets PoolObject.class or add use annotation @Pool on " + TReflect.getClassName(obj.getClass()) +" and Aop support");
}
}
/**
*
* @param id id
* @return
*/
private T get(Long id) {
if(id != null) {
PooledObject<T> pooledObject = objects.get(id);
if (pooledObject != null) {
pooledObject.setBorrow(true);
return pooledObject.getObject();
} else {
return null;
}
} else {
return null;
}
}
/**
*
* supplier , , null
* @return ID
*/
public T borrow(){
Long id = unborrowedIdList.poll();
if (id != null && objects.get(id).isBorrow()) {
throw new RuntimeException("Object already borrowed");
}
T result = get(id);
if (result == null && supplier != null) {
if(objects.size() <= maxSize) {
synchronized (unborrowedIdList) {
result = get(add(supplier.get(), true));
}
}
}
return result;
}
/**
*
* @param waitTime
* @return , null
* @throws TimeoutException
*/
public T borrow(long waitTime) throws TimeoutException {
Long id = null;
//, borrow() supplier
T result = borrow();
if (result == null) {
try {
id = unborrowedIdList.poll(waitTime, TimeUnit.MILLISECONDS);
if (id != null && objects.get(id).isBorrow()) {
throw new RuntimeException("Object already borrowed");
}
return get(id);
} catch (InterruptedException e) {
throw new TimeoutException("borrow failed.");
}
} else {
return result;
}
}
/**
*
* @param obj
*/
public void restitution(T obj) {
if(obj instanceof PoolObject) {
Long id = ((PoolObject) obj).getPoolObjectId();
PooledObject pooledObject = objects.get(id);
if (!pooledObject.isRemoved() && objects.get(id).setBorrow(false)) {
unborrowedIdList.offer(id);
}
} else {
throw new RuntimeException("the Object is not implement PoolBase interface, please make " + TReflect.getClassName(obj.getClass()) +
" implemets PoolObject.class or add use annotation @Pool on " + TReflect.getClassName(obj.getClass()) +" and Aop support");
}
}
/**
*
* @param id hash
* @return true: , false:
*/
public boolean contains(long id){
return unborrowedIdList.contains(id);
}
/**
*
* @param id hash
*/
public void remove(long id){
unborrowedIdList.remove(id);
PooledObject pooledObject = objects.remove(id);
if(pooledObject!=null) {
pooledObject.remove();
}
}
/**
*
* @return
*/
public int size(){
return objects.size();
}
/**
*
* @return
*/
public int borrowedSize(){
return objects.size() - unborrowedIdList.size();
}
/**
*
* @return
*/
public int avaliableSize(){
return unborrowedIdList.size();
}
public synchronized void clear(){
for(PooledObject pooledObject : objects.values()) {
pooledObject.remove();
}
unborrowedIdList.clear();
objects.clear();
}
/**
* ObjectPool
* @return ObjectPool
*/
public ObjectPool create(){
final ObjectPool finalobjectPool = this;
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
try {
Iterator<PooledObject<T>> iterator = objects.values().iterator();
while (iterator.hasNext()) {
if(objects.size() <= minSize){
return;
}
PooledObject<T> pooledObject = iterator.next();
if (!pooledObject.isAlive()) {
if(destory!=null){
// null , null
if(destory.apply(pooledObject.getObject())){
remove(pooledObject.getId());
} else {
pooledObject.refresh();
}
} else {
remove(pooledObject.getId());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, this.interval, true);
return this;
}
public class PooledObject<T>{
private long lastVisiediTime;
private long id;
@NotSerialization
private T object;
@NotSerialization
private ObjectPool objectCachedPool;
private AtomicBoolean isBorrow = new AtomicBoolean(false);
private AtomicBoolean isRemoved = new AtomicBoolean(false);
private AtomicInteger count = new AtomicInteger();
public PooledObject(ObjectPool objectCachedPool, long id, T object) {
this.objectCachedPool = objectCachedPool;
this.lastVisiediTime = System.currentTimeMillis();
this.id = id;
this.object = object;
}
protected boolean setBorrow(Boolean isBorrow) {
if(isBorrow) {
count.incrementAndGet();
} else {
count.decrementAndGet();
}
return this.isBorrow.compareAndSet(!isBorrow, isBorrow);
}
protected boolean isBorrow() {
return isBorrow.get();
}
public boolean remove() {
return this.isRemoved.compareAndSet(false, true);
}
public boolean isRemoved() {
return isRemoved.get();
}
public void refresh() {
lastVisiediTime = System.currentTimeMillis();
}
/**
*
* @return
*/
public T getObject() {
if(objectCachedPool.isAutoRefreshOnGet()) {
refresh();
}
return object;
}
/**
*
* @param object
*/
public void setObject(T object) {
this.object = object;
}
/**
* id
* @return id
*/
public Long getId() {
return id;
}
/**
*
* @return true: , false:
*/
public boolean isAlive(){
if(objectCachedPool.aliveTime<=0){
return true;
}
long currentAliveTime = System.currentTimeMillis() - lastVisiediTime;
if (objectCachedPool.aliveTime>0 && currentAliveTime >= objectCachedPool.aliveTime*1000){
return false;
}else{
return true;
}
}
public String toString(){
return JSON.toJSON(this).replace("\"","");
}
}
public String toString(){
return "{Total:" + objects.size() + ", unborrow:" + unborrowedIdList.size()+"}";
}
}
|
package nl.mpi.arbil.ui;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.StringTokenizer;
import javax.swing.ComboBoxEditor;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.Timer;
import nl.mpi.arbil.ui.fieldeditors.ControlledVocabularyComboBoxEditor;
/**
*
* @author Twan Goosen <twan.goosen@mpi.nl>
*/
public abstract class TypeAheadComboBoxEditor implements ComboBoxEditor {
/**
* Gets requested item from vocabulary by index
* @param index
* @return Requested item
*/
protected abstract String getItemAt(int index);
/**
*
* @return Total number of items
*/
protected abstract int getItemsCount();
/**
*
* @return Whether multiple items can be entered
*/
protected abstract boolean isList();
/**
*
* @return Whether arbitrary items can be entered
*/
protected abstract boolean isOpen();
/**
* Constructor. Call init() after this!
* @param editor Editor component
* @param initialValue Initial value for editor
* @param originalValue Original value for editor (will revert to this at escape)
* @param comboBox Combobox this will be editor for
* @see init()
*/
protected TypeAheadComboBoxEditor(JTextField editor, String initialValue, String originalValue, JComboBox comboBox) {
this.editor = editor;
if (comboBox != null) {
setComboBox(comboBox);
// Also set combobox item to initial value because it will feed its selected item
// back into the setItem method of this object
comboBox.setSelectedItem(initialValue);
}
this.originalValue = originalValue;
}
/**
* Initializes editor. Initializes key and focus listeners and the timer. Must be called in constructor!
*/
protected final void init() {
getTextField().addKeyListener(keyListener);
getTextField().addFocusListener(focusListener);
initTypeaheadTimer();
}
public void addActionListener(ActionListener l) {
getTextField().addActionListener(l);
}
public String getCurrentValue() {
return getCurrentValueString();
}
/**
* Implements getEditorComponent
*/
public Component getEditorComponent() {
return getTextField();
}
/**
* Implements ComboBoxEditor getItem
* @param anObject
*/
public Object getItem() {
return getTextField().getText();
}
/**
* @return the editor
*/
public JTextField getTextField() {
return editor;
}
public void removeActionListener(ActionListener l) {
getTextField().removeActionListener(l);
}
public void selectAll() {
getTextField().selectAll();
}
public final void setComboBox(JComboBox comboBox) {
this.comboBox = comboBox;
comboBox.setEditable(true);
}
/**
* Implements ComboBoxEditor setItem
* @param item
*/
public void setItem(Object item) {
if (!typingAhead) {
String itemString = item.toString();
// Decide what to do, depending on whether there are multiple values
if (itemString.indexOf(ControlledVocabularyComboBoxEditor.SEPARATOR()) >= 0) {
// Set item value for entire text
getTextField().setText(itemString);
} else {
// Set only value currently being edited
setEditorValue(itemString);
}
}
}
private void handleTextEntryKey(KeyEvent e) {
if (!typingAhead) {
if (!e.isActionKey()
&& e.getKeyChar() != KeyEvent.CHAR_UNDEFINED
&& e.getKeyCode() != KeyEvent.VK_BACK_SPACE
&& e.getKeyCode() != KeyEvent.VK_DELETE) {
// Text is being typed. Start (or restart) timer, so that typeahead
// is executed after last keystroke within delay
startTypeaheadTimer(TYPEAHEAD_DELAY_SHORT());
} else if (!isOpen()
&& (e.getKeyCode() == KeyEvent.VK_BACK_SPACE
|| e.getKeyCode() == KeyEvent.VK_DELETE)) {
// In closed list, also autocomplete on backspace/delete but use
// a longer delay so as not to make it impossible to remove characters
// or even submit the (non-existent) entry
startTypeaheadTimer(TYPEAHEAD_DELAY_LONG());
}
}
}
private void handleNavigateComboKey(KeyEvent e) {
if (e.getModifiers() == 0) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
moveSelectedIndex(+1);
e.consume();
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
moveSelectedIndex(-1);
e.consume();
} else if (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) {
moveSelectedIndex(+5);
e.consume();
} else if (e.getKeyCode() == KeyEvent.VK_PAGE_UP) {
moveSelectedIndex(-5);
e.consume();
}
}
}
private synchronized void handleAutocompleteKey(KeyEvent e) {
typingAhead = true;
if (typeaheadTimer.isRunning()) {
typeaheadTimer.stop();
}
if (autoComplete()) {
// Completed current item, do not perform any more actions
// on this key event
e.consume();
}
typingAhead = false;
}
// TYPE-AHEAD AND AUTO-COMPLETE METHODS
/**
* Types ahead current item. If a match is found, remaining part of the
* target string is selected.
*/
private synchronized void typeAhead() {
typingAhead = true;
String currentEditorValue = getEditorValue();
int matchIndex = getMatchingItem(currentEditorValue);
if (matchIndex >= 0) {
// Match found
String match = getItemAt(matchIndex);
if (comboBox != null) {
// Make combobox jump to the selected item
comboBox.setSelectedItem(match);
}
int position = getTextField().getCaretPosition();
// Insert match into editor
setEditorValue(match);
// Set caret back to original position
getTextField().setCaretPosition(position);
// Select remaining part of match
getTextField().setSelectionStart(position);
getTextField().setSelectionEnd(position + match.length() - currentEditorValue.length());
}
typingAhead = false;
}
/**
* Performs auto complete on current item. In effect, current selection is
* skipped. If nothing is selected, nothing is skipped and false is returned
*
* @return Whether any action was taken
*/
private boolean autoComplete() {
if (getTextField().getSelectionEnd() > getTextField().getSelectionStart()) {
getTextField().setCaretPosition(getTextField().getSelectionEnd());
return true;
}
return false;
}
private int previousMatch = -1;
/**
* Tries to find an item that matches the given text
* @param text Text to find match for
* @return Index of matching item, guaranteed to be a String; -1 if no match
*/
private int getMatchingItem(String text) {
if (null != text && text.length() > 0) {
int itemsCount = getItemsCount();
// Try previous match first, in many cases it will match and there's
// no need to iterate over all items
if (previousMatch >= 0
&& previousMatch < itemsCount
&& ((String) getItemAt(previousMatch)).toLowerCase().startsWith(text.toLowerCase())) {
return previousMatch;
}
for (int i = 0; i < itemsCount; i++) {
String item = getItemAt(i);
if (item != null) {
if (item.regionMatches(true, 0, text, 0, text.length())) {
previousMatch = i;
return i;
}
}
}
}
return -1;
}
// EDITOR MANIPULATION & ACCESS HELPER METHODS
/**
* Creates a sanitized string of the current value(s) of the editor
* @return
*/
private String getCurrentValueString() {
StringTokenizer st = new StringTokenizer(getTextField().getText(), Character.toString(SEPARATOR()));
StringBuilder sb = new StringBuilder(st.countTokens());
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.length() > 0) {
sb.append(token);
if (st.hasMoreTokens()) {
sb.append(SEPARATOR());
}
}
}
return sb.toString();
}
/**
* Gets value of the current (determined by caret position) text
* @return
*/
private String getEditorValue() {
String value = getTextField().getText();
int lastIndex = value.length();
String separator = Character.toString(SEPARATOR());
if (!value.contains(separator)) {
return value;
} else {
int[] startEnd = getEditorCurrentStartEnd();
return value.substring(Math.min(startEnd[0], lastIndex), Math.min(startEnd[1], lastIndex));
}
}
/**
* Set the value of the CURRENT editor sub-item (i.e. whatever is between
* the separators closest to the caret position
* @param value
*/
private void setEditorValue(String value) {
int[] startEnd = getEditorCurrentStartEnd();
String text = getTextField().getText();
getTextField().setText(
text.substring(0, startEnd[0]) // everything before
.concat(value) // insert value
.concat(text.substring(startEnd[1]))); // everything after
getTextField().setCaretPosition(startEnd[0] + value.length());
}
/**
* @return Array containing indices of [start, end] of current editor value
*/
private int[] getEditorCurrentStartEnd() {
String value = getTextField().getText();
if (!isList()) {
// Single valued vocabulary is treated as single entry
return new int[]{0, value.length()};
} else {
// Find bounds of item of current caret position
int lastIndex = value.length();
String separator = Character.toString(SEPARATOR());
int currentIndex = getEditorIndex();
int start = 0;
// Traverse editor value to find current start position
if (currentIndex > 0) {
int current = 0;
do {
start = value.indexOf(separator, Math.min(start, lastIndex)) + 1;
current++;
} while (current < currentIndex);
}
// Find first bound after start position
int end = value.indexOf(separator, Math.min(start, lastIndex));
if (end <= 0) {
end = lastIndex;
}
return new int[]{start, end};
}
}
/**
* Gets index for currentValues array that corresponds with current caret position in editor
* @return
*/
private int getEditorIndex() {
String value = getTextField().getText();
int position = getTextField().getCaretPosition();
int index = 0;
for (int i = 0; i < position; i++) {
if (value.charAt(i) == SEPARATOR()) {
index++;
}
}
return index;
}
private void moveSelectedIndex(int delta) {
int target = comboBox.getSelectedIndex() + delta;
// Don't move up to the first item, as it contains the previous value of the field
target = Math.max(target, 0);
// Don't try to mobe below final item
target = Math.min(target, comboBox.getItemCount() - 1);
// Target should be in list and not equal to current target
if (target >= 0 && target != comboBox.getSelectedIndex()) {
// Target should not be multi-valued
if (comboBox.getItemAt(target).toString().indexOf(SEPARATOR()) >= 0) {
target = Math.min(target + 1, comboBox.getItemCount() - 1);
}
comboBox.setSelectedIndex(target);
}
}
private void startTypeaheadTimer(int delay) {
if (typeaheadTimer.isRunning()) {
typeaheadTimer.stop();
}
//typeaheadTimer.setDelay(delay);
//typeaheadTimer.restart();
typeaheadTimer.setInitialDelay(delay);
typeaheadTimer.start();
}
private void initTypeaheadTimer() {
typeaheadTimer = new Timer(TYPEAHEAD_DELAY_SHORT(), new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!typingAhead) {
typeaheadTimer.stop();
typeAhead();
}
}
});
typeaheadTimer.setRepeats(false);
}
private final KeyListener keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (!comboBox.isPopupVisible()) {
comboBox.setPopupVisible(true);
} else {
if (e.getKeyCode() == KeyEvent.VK_ENTER || (isList() && e.getKeyChar() == ControlledVocabularyComboBoxEditor.SEPARATOR())) {
// ENTER pressed or SEPARATOR in list field.
// Autocomplete current item
handleAutocompleteKey(e);
} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
getTextField().setText(originalValue);
} else if (e.isActionKey()) {
// Navigate combo items
handleNavigateComboKey(e);
} else {
// Probably text entry
handleTextEntryKey(e);
}
}
}
};
private final FocusListener focusListener = new FocusListener() {
public void focusGained(FocusEvent e) {
startTypeaheadTimer(ControlledVocabularyComboBoxEditor.TYPEAHEAD_DELAY_SHORT());
}
public void focusLost(FocusEvent e) {
}
};
// Private members
private JComboBox comboBox;
private Timer typeaheadTimer;
private String originalValue;
private JTextField editor;
/**
* Flag indicating whether type ahead is in process
*/
private boolean typingAhead = false;
/**
* Character that separates items in a list-type field
*/
private static final char SEPARATOR = ',';
/**
* Response rate limit in milliseconds
*/
private static final int TYPEAHEAD_DELAY_SHORT = 200;
private static final int TYPEAHEAD_DELAY_LONG = 1000;
/**
* @return Item separator. Can be overridden, default is comma
*/
protected static char SEPARATOR() {
return SEPARATOR;
}
/**
* Delay used for auto complete, except in closed lists where long delay is used
* @return Short typeahead delay, can be overridden
* @see TYPEAHEAD_DELAY_LONG()
*/
protected static int TYPEAHEAD_DELAY_SHORT() {
return TYPEAHEAD_DELAY_SHORT;
}
/**
* Delay used for auto complete in <em>closed lists</em>, given users a chance to enforce their non-matching input
* @return Long typeahead delay, can be overridden.
* @see TYPEAHEAD_DELAY_SHORT()
*/
protected static int TYPEAHEAD_DELAY_LONG() {
return TYPEAHEAD_DELAY_LONG;
}
}
|
package net.tomp2p.holep;
import java.io.IOException;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;
import net.tomp2p.dht.FutureGet;
import net.tomp2p.dht.FuturePut;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.dht.PutBuilder;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDone;
import net.tomp2p.futures.FutureResponse;
import net.tomp2p.futures.FutureShutdown;
import net.tomp2p.nat.FutureRelayNAT;
import net.tomp2p.nat.PeerBuilderNAT;
import net.tomp2p.nat.PeerNAT;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.p2p.builder.SendDirectBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.rpc.ObjectDataReply;
import net.tomp2p.storage.Data;
public class HolePTestApp {
private static final int port = 4001;
private static final String PEER_1 = "peer1";
private static final String PEER_2 = "peer2";
private Peer peer;
private PeerNAT pNAT;
private PeerAddress masterPeerAddress;
private PeerAddress natPeerAddress;
public HolePTestApp() {
}
public void startMasterPeer() throws Exception {
peer = new PeerBuilder(Number160.createHash("master")).ports(port).start();
pNAT = new PeerBuilderNAT(peer).start();
System.err.println("SERVER BOOTSTRAP SUCCESS!");
System.err.println("IP: " + peer.peerAddress().inetAddress());
System.err.println("ID: " + peer.peerID());
// store own PeerAddress into storage
HolePStaticStorage.peerAdresses().put(peer.peerID(), peer.peerAddress());
peer.objectDataReply(new ObjectDataReply() {
@Override
public FutureDone<PeerAddress> reply(PeerAddress sender, Object request) throws Exception {
FutureDone<PeerAddress> futureDone = new FutureDone<PeerAddress>();
int command = (Integer) request;
switch (command) {
case 0: {
HolePStaticStorage.peerAdresses().put(sender.peerId(), sender);
System.err.println("NEW PEERADDRESS STORED IN HOLEPSTATICSTORAGE!");
System.err.println(sender);
break;
}
case 1: {
if (Number160.createHash(PEER_1).equals(sender.peerId())) {
futureDone.done(HolePStaticStorage.peerAdresses().get(Number160.createHash(PEER_2)));
System.err.println("RETURNED PEERADDRESS OF PEER_2!");
System.err.println(sender);
} else {
futureDone.done(HolePStaticStorage.peerAdresses().get(Number160.createHash(PEER_1)));
System.err.println("RETURNED PEERADDRESS OF PEER_1!");
System.err.println(sender);
}
}
default:
break;
}
return futureDone;
}
});
}
public void startNormalPeer(String[] args) throws Exception {
peer = new PeerBuilder(Number160.createHash(args[1])).ports(port).start();
FutureBootstrap fb = peer.bootstrap().inetAddress(Inet4Address.getByName(args[0])).ports(port).start();
fb.awaitUninterruptibly();
if (!fb.isSuccess()) {
System.err.println("ERROR WHILE NORMAL-BOOTSTRAPPING. THE APPLICATION WILL NOW SHUTDOWN!");
System.exit(1);
} else {
System.err.println("NORMAL-BOOTSTRAP SUCCESS!");
}
}
public void startNATPeer(String[] args) throws Exception {
peer = new PeerBuilder(Number160.createHash(args[1])).ports(port).start();
PeerAddress bootstrapPeerAddress = new PeerAddress(Number160.createHash("master"), Inet4Address.getByName(args[0]), port, port);
masterPeerAddress = bootstrapPeerAddress;
// Set the isFirewalledUDP and isFirewalledTCP flags
PeerAddress upa = peer.peerBean().serverPeerAddress();
upa = upa.changeFirewalledTCP(true).changeFirewalledUDP(true);
peer.peerBean().serverPeerAddress(upa);
// find neighbors
FutureBootstrap futureBootstrap = peer.bootstrap().peerAddress(bootstrapPeerAddress).start();
futureBootstrap.awaitUninterruptibly();
// setup relay
pNAT = new PeerBuilderNAT(peer).start();
// set up 3 relays
// FutureRelay futureRelay = uNat.startSetupRelay(new FutureRelay());
// futureRelay.awaitUninterruptibly();
FutureRelayNAT frn = pNAT.startRelay(bootstrapPeerAddress);
frn.awaitUninterruptibly();
// find neighbors again
FutureBootstrap fb = peer.bootstrap().peerAddress(bootstrapPeerAddress).start();
fb.awaitUninterruptibly();
if (!fb.isSuccess()) {
System.err.println("ERROR WHILE NAT-BOOTSTRAPPING. THE APPLICATION WILL NOW SHUTDOWN!");
System.exit(1);
} else {
System.err.println("NAT-BOOTSTRAP SUCCESS!");
}
// do maintenance
// uNat.bootstrapBuilder(peer.bootstrap().peerAddress(bootstrapPeerAddress));
// uNat.startRelayMaintenance(futureRelay);
// store own PeerAddress on Server
FutureDirect fd = peer.sendDirect(masterPeerAddress).object(new Integer(0)).start();
if (fd.isSuccess()) {
System.err.println("OWN PEERADDRESS STORED ON SERVER!");
} else {
System.err.println("COULD NOT STORE OWN PEERADDRESS ON SERVER!");
}
}
public void setObjectDataReply() {
peer.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.out.println("SUCCESS HIT");
System.out.println("Sender: " + sender.toString());
System.out.println("NATPEER: " + (PeerAddress) request);
natPeerAddress = (PeerAddress) request;
return null;
}
});
}
public void runTextInterface() throws Exception {
System.out.println("Welcome to the textinterface of HolePTestApp!");
Scanner scan = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Choose a valid order. \n" + " 0 = Exit process \n" + " 1 = getNatPeerAddress() CURRENTLY NOT WORKING! \n"
+ " 2 = putNATPeerAddress() CURRENTLY NOT WORKING! \n" + " 3 = sendDirectMessage() \n"
+ " 4 = sendDirectNATMessage() \n" + " 5 = getOtherPeerAddress()");
System.out.println();
int command = scan.nextInt();
System.out.println("You've entered the number " + command + ".");
switch (command) {
case 0: // end process
scan.close();
exit = true;
break;
case 3: // send Message to peer not behind a NAT
sendDirectMessage();
break;
case 4: // send Message to peer behind a NAT
sendDirectNATMessage();
break;
case 5: // send Relay message to get to the PeerAddress of one
// another
sendRelayNATMessage();
default: // start process again
break;
}
}
// if 0 is chosen, the peer should shutdown and the program should end
FutureShutdown fs = (FutureShutdown) peer.shutdown();
fs.awaitUninterruptibly();
System.exit(0);
}
private void sendRelayNATMessage(){
setObjectDataReply();
final FutureDone<PeerAddress> fDone = new FutureDone<PeerAddress>();
FutureDirect fDirect = peer.sendDirect(masterPeerAddress).object(new Integer(1)).start();
fDirect.addListener(new BaseFutureAdapter<FutureDone<PeerAddress>>() {
@Override
public void operationComplete(FutureDone<PeerAddress> future) throws Exception {
if (future.isSuccess()) {
PeerAddress peer2Address = (PeerAddress) future.object();
System.err.println("RELAY SENDDIRECT SUCCESS!");
} else {
System.err.println("NO RELAY SENDDIRECT COULD BE MADE!");
}
}
});
}
private void sendDirectNATMessage() throws IOException {
setObjectDataReply();
FutureDirect fd = peer.sendDirect(natPeerAddress).object("Hello World").start();
fd.awaitUninterruptibly();
if (!fd.isSuccess()) {
System.err.println("SENDDIRECT-NATMESSAGE FAIL!");
} else {
System.err.println("SENDDIRECT-NATMESSAGE SUCCESS!");
}
}
private void sendDirectMessage() throws IOException {
setObjectDataReply();
peer.peerAddress().changeRelayed(true);
SendDirectBuilder sdb = peer.sendDirect(masterPeerAddress.changeRelayed(true)).forceUDP(true).forceTCP(false).object("Hello World");
FutureDirect fd = sdb.start();
fd.awaitUninterruptibly();
if (!fd.isSuccess()) {
System.err.println("SENDDIRECT-MESSAGE FAIL!");
} else {
System.err.println("SENDDIRECT-MESSAGE SUCCESS!");
}
}
}
|
package tlc2.tool.management;
import java.io.IOException;
import javax.management.NotCompliantMBeanException;
import tlc2.tool.ModelChecker;
import tlc2.tool.distributed.management.TLCStatisticsMXBean;
import tlc2.tool.fp.DiskFPSet;
/**
* @author Markus Alexander Kuppe
*/
public class ModelCheckerMXWrapper extends TLCStandardMBean implements TLCStatisticsMXBean {
private final ModelChecker modelChecker;
public ModelCheckerMXWrapper(final ModelChecker aModelChecker)
throws NotCompliantMBeanException {
super(TLCStatisticsMXBean.class);
this.modelChecker = aModelChecker;
// register all TLCStatisticsMXBeans under the same name
registerMBean("tlc2.tool:type=ModelChecker");
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getStatesGenerated()
*/
public long getStatesGenerated() {
return modelChecker.getStatesGenerated();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getDistinctStatesGenerated()
*/
public long getDistinctStatesGenerated() {
// if impl is DiskFPSet we don't want to add to the lock contention on
// the RWLock in DiskFPSet and thus compromise on reading dirty values
// (acceptable for statistics/metrics)
if(modelChecker.theFPSet instanceof DiskFPSet) {
DiskFPSet diskFPSet = (DiskFPSet) modelChecker.theFPSet;
return diskFPSet.getFileCnt() + diskFPSet.getTblCnt();
}
return modelChecker.theFPSet.size();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getStateQueueSize()
*/
public long getStateQueueSize() {
return modelChecker.theStateQueue.size();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getStatesGeneratedPerMinute()
*/
public long getStatesGeneratedPerMinute() {
return modelChecker.statesPerMinute;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getDistinctStatesGeneratedPerMinute()
*/
public long getDistinctStatesGeneratedPerMinute() {
return modelChecker.distinctStatesPerMinute;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.management.TLCStatisticsMXBean#getProgress()
*/
public int getProgress() {
try {
return modelChecker.trace.getLevelForReporting();
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
}
|
package io.spine.server;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.grpc.stub.StreamObserver;
import io.spine.client.Subscription;
import io.spine.client.SubscriptionUpdate;
import io.spine.client.Target;
import io.spine.client.Topic;
import io.spine.client.grpc.SubscriptionServiceGrpc;
import io.spine.core.Response;
import io.spine.logging.Logging;
import io.spine.server.stand.Stand;
import io.spine.system.server.EntityStateChanged;
import io.spine.type.TypeUrl;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.grpc.StreamObservers.forwardErrorsOnly;
/**
* The {@code SubscriptionService} provides an asynchronous way to fetch read-side state
* from the server.
*
* <p>For synchronous read-side updates please see {@link QueryService}.
*/
public class SubscriptionService
extends SubscriptionServiceGrpc.SubscriptionServiceImplBase
implements Logging {
private final ImmutableMap<TypeUrl, BoundedContext> typeToContextMap;
private SubscriptionService(Map<TypeUrl, BoundedContext> map) {
super();
this.typeToContextMap = ImmutableMap.copyOf(map);
}
public static Builder newBuilder() {
return new Builder();
}
@Override
public void subscribe(Topic topic, StreamObserver<Subscription> responseObserver) {
log().debug("Creating the subscription to a topic: {}", topic);
try {
Target target = topic.getTarget();
BoundedContext boundedContext = selectBoundedContext(target);
Stand stand = boundedContext.getStand();
stand.subscribe(topic, responseObserver);
} catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) {
log().error("Error processing subscription request", e);
responseObserver.onError(e);
}
}
@Override
public void activate(Subscription subscription,
StreamObserver<SubscriptionUpdate> responseObserver) {
log().debug("Activating the subscription: {}", subscription);
try {
BoundedContext boundedContext = selectBoundedContext(subscription);
Stand.NotifySubscriptionAction notifyAction = update -> {
checkNotNull(update);
responseObserver.onNext(update);
};
Stand targetStand = boundedContext.getStand();
targetStand.activate(subscription, notifyAction, forwardErrorsOnly(responseObserver));
} catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) {
log().error("Error activating the subscription", e);
responseObserver.onError(e);
}
}
@Override
public void cancel(Subscription subscription, StreamObserver<Response> responseObserver) {
log().debug("Incoming cancel request for the subscription topic: {}", subscription);
BoundedContext boundedContext = selectBoundedContext(subscription);
try {
Stand stand = boundedContext.getStand();
stand.cancel(subscription, responseObserver);
} catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) {
log().error("Error processing cancel subscription request", e);
responseObserver.onError(e);
}
}
private BoundedContext selectBoundedContext(Subscription subscription) {
Target target = subscription.getTopic().getTarget();
BoundedContext context = selectBoundedContext(target);
return context;
}
private BoundedContext selectBoundedContext(Target target) {
TypeUrl type = TypeUrl.parse(target.getType());
BoundedContext result = typeToContextMap.get(type);
return result;
}
public static class Builder {
private final Set<BoundedContext> boundedContexts = Sets.newHashSet();
public Builder add(BoundedContext boundedContext) {
// Save it to a temporary set so that it is easy to remove it if needed.
boundedContexts.add(boundedContext);
return this;
}
public Builder remove(BoundedContext boundedContext) {
boundedContexts.remove(boundedContext);
return this;
}
@SuppressWarnings("ReturnOfCollectionOrArrayField") // the collection returned is immutable
public ImmutableList<BoundedContext> getBoundedContexts() {
return ImmutableList.copyOf(boundedContexts);
}
public SubscriptionService build() throws IllegalStateException {
if (boundedContexts.isEmpty()) {
throw new IllegalStateException(
"Subscription service must have at least one bounded context.");
}
ImmutableMap<TypeUrl, BoundedContext> map = createMap();
SubscriptionService result = new SubscriptionService(map);
return result;
}
private ImmutableMap<TypeUrl, BoundedContext> createMap() {
ImmutableMap.Builder<TypeUrl, BoundedContext> builder = ImmutableMap.builder();
for (BoundedContext boundedContext : boundedContexts) {
putIntoMap(boundedContext, builder);
}
return builder.build();
}
private static void putIntoMap(BoundedContext boundedContext,
ImmutableMap.Builder<TypeUrl, BoundedContext> mapBuilder) {
Stand stand = boundedContext.getStand();
ImmutableSet<TypeUrl> exposedTypes = stand.getExposedTypes();
for (TypeUrl availableType : exposedTypes) {
mapBuilder.put(availableType, boundedContext);
}
}
}
}
|
package gov.nih.nci.calab.ui.workflow;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.dto.workflow.FileBean;
import gov.nih.nci.calab.dto.workflow.FileDownloadInfo;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.service.util.ActionUtil;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorActionForm;
/**
* This class handle workflow upload process.
*
* @author zhoujim
*
*/
public class FileDownloadAction extends AbstractDispatchAction
{
private static org.apache.log4j.Logger logger_ =
org.apache.log4j.Logger.getLogger(FileDownloadAction.class);
public String fullPathName = null;
/**
* This method is setting up the parameters for the workflow input upload files
* or output upload files.
*
* @param mapping
* @param form
* @param request
* @param response
* @return mapping forward
*/
public ActionForward setup(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
HttpSession session = request.getSession();
ExecuteWorkflowService workflowService = new ExecuteWorkflowService();
String runId = request.getParameter("runId");
RunBean runBean = workflowService.getAssayInfoByRun((ExecuteWorkflowBean)session.getAttribute("workflow"), runId);
DynaValidatorActionForm fileForm = (DynaValidatorActionForm)form;
fileForm.set("assayType", runBean.getAssayBean().getAssayType());
fileForm.set("assay", runBean.getAssayBean().getAssayName());
fileForm.set("run", runBean.getName());
fileForm.set("inout", request.getParameter("type"));
String contentPath = request.getContextPath();
String path = PropertyReader.getProperty(CalabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
fullPathName = path + fileForm.get("assayType") + File.separator
+ fileForm.get("assay") + File.separator
+ fileForm.get("run") + File.separator
+ fileForm.get("inout") + File.separator
+ CalabConstants.UNCOMPRESSED_FILE_DIRECTORY;
// Retrieve filename(not uri) from database
List<FileBean> fileBeanList = new ArrayList<FileBean>();
if ((request.getParameter("type")).equalsIgnoreCase(CalabConstants.INPUT)) {
fileBeanList = runBean.getInputFileBeans();
} else if ((request.getParameter("type")).equalsIgnoreCase(CalabConstants.OUTPUT)) {
fileBeanList = runBean.getOutputFileBeans();
}
List<FileDownloadInfo> fileNameHolder = new ArrayList<FileDownloadInfo>();
for(FileBean fileBean: fileBeanList)
{
FileDownloadInfo fileDownloadInfo = new FileDownloadInfo();
fileDownloadInfo.setFileName(fileBean.getFilename());
fileDownloadInfo.setUploadDate(fileBean.getCreatedDate());
fileDownloadInfo.setAction(contentPath+"/fileDownload.do?method=downloadFile&fileName="+fileBean.getFilename());
fileNameHolder.add(fileDownloadInfo);
}
fileForm.set("fileInfoList", fileNameHolder);
fileForm.set("downloadAll", contentPath+"/fileDownload.do?method=downloadFile&fileName="+CalabConstants.ALL_FILES+".zip");
return mapping.findForward("success");
}
public ActionForward downloadFile(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
DynaValidatorActionForm fileForm = (DynaValidatorActionForm)form;
String fileName = (String)fileForm.get("fileName");
File f = new File(fullPathName+File.separator+fileName);
if (!f.exists())
{
logger_.error("File has been remove, please contact system administrator.");
throw new Exception ("File has been remove, please contact system administrator.");
}
ActionUtil actionUtil = new ActionUtil();
actionUtil.writeBinaryStream(f, response);
return null;
}
public boolean loginRequired() {
return true;
}
}
|
package gov.nih.nci.rembrandt.web.servlets;
import gov.nih.nci.evs.domain.DescLogicConcept;
import gov.nih.nci.evs.query.EVSQuery;
import gov.nih.nci.evs.query.EVSQueryImpl;
import gov.nih.nci.system.applicationservice.ApplicationService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.tree.DefaultMutableTreeNode;
public class GOTreeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req,res); // Pass all GET request to the the doPost method
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html"); // Set the content type of the response
PrintWriter out=res.getWriter(); // PrintWriter to write text to the response
// out.println("Hello World"); // Write Hello World
// out.println(req.getParameter("a"));
// out.close(); // Close the PrintWriter
String serverURL = "http://cbioqa101.nci.nih.gov:49080/cacore31/http/remoteService";
//
//
EVSQuery evsQuery = new EVSQueryImpl();
String term = "biological_process";
ApplicationService appService = ApplicationService.getRemoteInstance(serverURL);
List results = null;
evsQuery.getTree("GO", term, true, false, 0, 3, null);
long l1 = 0;
try {
GregorianCalendar gc1 = new GregorianCalendar();
Date d1 = gc1.getTime();
l1 = d1.getTime();
results =(List) appService.evsSearch(evsQuery);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GregorianCalendar gc2 = new GregorianCalendar();
Date d2 = gc2.getTime();
long l2 = d2.getTime();
long difference = l2 - l1;
long seconds = difference/1000;
System.out.println("Elapsed seconds: " + seconds);
DefaultMutableTreeNode dn = (DefaultMutableTreeNode)results.get(0);
DescLogicConcept theUserObject = (DescLogicConcept) dn.getUserObject();
out.println(theUserObject.getName() + " : " + theUserObject.getCode());
//out.println(results);
out.close();
}
}
|
package infodoc.basic.scheduling;
import infodoc.basic.activity.CreateAndScheduleCreate;
import infodoc.core.container.InfodocContainerFactory;
import infodoc.core.dto.Activity;
import infodoc.core.dto.Case;
import infodoc.core.ui.activity.ActivityExecutorHelper;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import enterpriseapp.EnterpriseApplication;
import enterpriseapp.Utils;
public class CreateActivityScheduler {
private static final Logger logger = LoggerFactory.getLogger(CreateActivityScheduler.class);
public static void schedulePending() throws ParseException {
try {
List<Activity> activities = InfodocContainerFactory.getActivityContainer().listAll();
for(Activity activity : activities) {
Class<?> clazz = Class.forName(activity.getJavaClass());
if(CreateAndScheduleCreate.class.isAssignableFrom(clazz)) {
CreateAndScheduleCreate createAndScheduleActivity = (CreateAndScheduleCreate) ActivityExecutorHelper.getActivityExecutorComponent(activity, null);
createAndScheduleActivity.parseParams();
List<Case> cases = InfodocContainerFactory.getCaseContainer().findByLastActivityId(activity.getId());
for(Case caseDto : cases) {
String cronExpression = createAndScheduleActivity.getCronExpression(caseDto.getPropertyValues());
Long scheduleActivityId = createAndScheduleActivity.getScheduleActivityId();
schedule(caseDto.getId(), scheduleActivityId, cronExpression, caseDto.getActivityInstances().iterator().next().getUser().getId());
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void schedule(Long caseId, Long scheduleActivityId, String cronExpression, Long userId) throws ParseException {
try {
logger.info("Scheduling job for case " + caseId + " and activity " + scheduleActivityId + " (" + cronExpression + ")");
JobKey key = new JobKey(CreateActivityExecutionJob.class.getSimpleName() + "_" + caseId + "_" + scheduleActivityId);
JobDetail jobDetail = JobBuilder.newJob(CreateActivityExecutionJob.class)
.withIdentity(key)
.usingJobData("activityId", scheduleActivityId)
.usingJobData("caseId", caseId)
.usingJobData("userId", userId)
.build();
CronTriggerImpl trigger = new CronTriggerImpl();
trigger.setName(CreateActivityScheduler.class.getSimpleName() + "_" + caseId + "_" + scheduleActivityId);
trigger.setCronExpression(cronExpression);
Date date = EnterpriseApplication.getScheduler().scheduleJob(jobDetail, trigger);
logger.info("Job for case " + caseId + " and activity " + scheduleActivityId + "(" + cronExpression + ") starting at " + Utils.dateTimeToString(date));
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
public static void unschedule(Long caseId, Long scheduleActivityId) {
try {
logger.info("Unscheduling job for case " + caseId + " and activity " + scheduleActivityId);
JobKey key = new JobKey(CreateActivityExecutionJob.class.getSimpleName() + "_" + caseId + "_" + scheduleActivityId);
EnterpriseApplication.getScheduler().deleteJob(key);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}
|
package edu.umd.cs.findbugs;
import java.io.IOException;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.GETSTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.SourceInfoMap;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
/**
* A BugAnnotation specifying a particular field in particular class.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class FieldAnnotation extends PackageMemberAnnotation {
private static final long serialVersionUID = 1L;
private static final String DEFAULT_ROLE = "FIELD_DEFAULT";
private String fieldName;
private String fieldSig;
private boolean isStatic;
/**
* Constructor.
*
* @param className the name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig the type signature of the field
*/
public FieldAnnotation(String className, String fieldName, String fieldSig, boolean isStatic) {
super(className, DEFAULT_ROLE);
if (fieldSig.indexOf(".") >= 0) {
assert false : "signatures should not be dotted: " + fieldSig;
fieldSig = fieldSig.replace('.','/');
}
this.fieldName = fieldName;
this.fieldSig = fieldSig;
this.isStatic = isStatic;
}
/**
* Factory method. Class name, field name, and field signatures are taken from
* the given visitor, which is visiting the field.
*
* @param visitor the visitor which is visiting the field
* @return the FieldAnnotation object
*/
public static FieldAnnotation fromVisitedField(PreorderVisitor visitor) {
return new FieldAnnotation(visitor.getDottedClassName(),
visitor.getFieldName(), visitor.getFieldSig(),
visitor.getFieldIsStatic());
}
/**
* Factory method. Class name, field name, and field signatures are taken from
* the given visitor, which is visiting a reference to the field
* (i.e., a getfield or getstatic instruction).
*
* @param visitor the visitor which is visiting the field reference
* @return the FieldAnnotation object
*/
public static FieldAnnotation fromReferencedField(DismantleBytecode visitor) {
String className = visitor.getDottedClassConstantOperand();
return new FieldAnnotation(className,
visitor.getNameConstantOperand(),
visitor.getSigConstantOperand(), visitor.getRefFieldIsStatic());
}
/**
* Factory method. Construct from class name and BCEL Field object.
*
* @param className the name of the class which defines the field
* @param field the BCEL Field object
* @return the FieldAnnotation
*/
public static FieldAnnotation fromBCELField(String className, Field field) {
return new FieldAnnotation(className, field.getName(), field.getSignature(), field.isStatic());
}
/**
* Factory method. Construct from a FieldDescriptor.
*
* @param fieldDescriptor the FieldDescriptor
* @return the FieldAnnotation
*/
public static FieldAnnotation fromFieldDescriptor(FieldDescriptor fieldDescriptor) {
return new FieldAnnotation(
fieldDescriptor.getClassName(),
fieldDescriptor.getName(),
fieldDescriptor.getSignature(),
fieldDescriptor.isStatic());
}
public static FieldAnnotation fromXField(XField fieldDescriptor) {
return new FieldAnnotation(
fieldDescriptor.getClassName(),
fieldDescriptor.getName(),
fieldDescriptor.getSignature(),
fieldDescriptor.isStatic());
}
/**
* Get the field name.
*/
public String getFieldName() {
return fieldName;
}
/**
* Get the type signature of the field.
*/
public String getFieldSignature() {
return fieldSig;
}
/**
* Return whether or not the field is static.
*/
public boolean isStatic() {
return isStatic;
}
/**
* Is the given instruction a read of a field?
*
* @param ins the Instruction to check
* @param cpg ConstantPoolGen of the method containing the instruction
* @return the Field if the instruction is a read of a field, null otherwise
*/
public static FieldAnnotation isRead(Instruction ins, ConstantPoolGen cpg) {
if (ins instanceof GETFIELD || ins instanceof GETSTATIC) {
FieldInstruction fins = (FieldInstruction) ins;
String className = fins.getClassName(cpg);
return new FieldAnnotation(className, fins.getName(cpg), fins.getSignature(cpg), fins instanceof GETSTATIC);
} else
return null;
}
/**
* Is the instruction a write of a field?
*
* @param ins the Instruction to check
* @param cpg ConstantPoolGen of the method containing the instruction
* @return the Field if instruction is a write of a field, null otherwise
*/
public static FieldAnnotation isWrite(Instruction ins, ConstantPoolGen cpg) {
if (ins instanceof PUTFIELD || ins instanceof PUTSTATIC) {
FieldInstruction fins = (FieldInstruction) ins;
String className = fins.getClassName(cpg);
return new FieldAnnotation(className, fins.getName(cpg), fins.getSignature(cpg), fins instanceof PUTSTATIC);
} else
return null;
}
public void accept(BugAnnotationVisitor visitor) {
visitor.visitFieldAnnotation(this);
}
@Override
protected String formatPackageMember(String key, ClassAnnotation primaryClass) {
if (key.equals("") || key.equals("hash"))
return className + "." + fieldName;
else if (key.equals("givenClass")) {
if (className.equals(primaryClass.getClassName())) return getNameInClass(primaryClass);
else return shorten(primaryClass.getPackageName(), className) + "." + getNameInClass(primaryClass);
}
else if (key.equals("name"))
return fieldName;
else if (key.equals("fullField")) {
SignatureConverter converter = new SignatureConverter(fieldSig);
StringBuffer result = new StringBuffer();
if (isStatic)
result.append("static ");
result.append(converter.parseNext());
result.append(' ');
result.append(className);
result.append('.');
result.append(fieldName);
return result.toString();
} else
throw new IllegalArgumentException("unknown key " + key);
}
/**
* @param primaryClass
* @return
*/
private String getNameInClass(ClassAnnotation primaryClass) {
if (primaryClass == null)
return className + "." + fieldName;
String givenPackageName = primaryClass.getPackageName();
String thisPackageName = this.getPackageName();
if (thisPackageName.equals(givenPackageName))
if (thisPackageName.length() == 0) return fieldName;
else return className.substring(thisPackageName.length() + 1) +"." + fieldName;
return className + "." + fieldName;
}
@Override
public int hashCode() {
return className.hashCode() + fieldName.hashCode() + fieldSig.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FieldAnnotation))
return false;
FieldAnnotation other = (FieldAnnotation) o;
return className.equals(other.className)
&& fieldName.equals(other.fieldName)
&& fieldSig.equals(other.fieldSig)
&& isStatic == other.isStatic;
}
public int compareTo(BugAnnotation o) {
if (!(o instanceof FieldAnnotation)) // BugAnnotations must be Comparable with any type of BugAnnotation
return this.getClass().getName().compareTo(o.getClass().getName());
FieldAnnotation other = (FieldAnnotation) o;
int cmp;
cmp = className.compareTo(other.className);
if (cmp != 0)
return cmp;
cmp = fieldName.compareTo(other.fieldName);
if (cmp != 0)
return cmp;
return fieldSig.compareTo(other.fieldSig);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.PackageMemberAnnotation#getSourceLines()
*/
@Override
public SourceLineAnnotation getSourceLines() {
if (sourceLines == null) {
// Create source line annotation for field on demand
AnalysisContext currentAnalysisContext = AnalysisContext.currentAnalysisContext();
if (currentAnalysisContext == null)
sourceLines = new SourceLineAnnotation(className, sourceFileName, -1, -1, -1, -1);
else {
SourceInfoMap.SourceLineRange fieldLine = currentAnalysisContext
.getSourceInfoMap()
.getFieldLine(className, fieldName);
if (fieldLine == null) sourceLines = new SourceLineAnnotation(
className, sourceFileName, -1, -1, -1, -1);
else sourceLines = new SourceLineAnnotation(
className, sourceFileName, fieldLine.getStart(), fieldLine.getEnd(), -1, -1);
}
}
return sourceLines;
}
private static final String ELEMENT_NAME = "Field";
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, false);
}
public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList()
.addAttribute("classname", getClassName())
.addAttribute("name", getFieldName())
.addAttribute("signature", getFieldSignature())
.addAttribute("isStatic", String.valueOf(isStatic()));
String role = getDescription();
if (!role.equals(DEFAULT_ROLE))
attributeList.addAttribute("role", role);
xmlOutput.openTag(ELEMENT_NAME, attributeList);
getSourceLines().writeXML(xmlOutput, addMessages);
if (addMessages) {
xmlOutput.openTag(BugAnnotation.MESSAGE_TAG);
xmlOutput.writeText(this.toString());
xmlOutput.closeTag(BugAnnotation.MESSAGE_TAG);
}
xmlOutput.closeTag(ELEMENT_NAME);
}
}
// vim:ts=4
|
package nl.fhict.happynews.crawler.api;
import nl.fhict.happynews.crawler.model.instagramapi.InstagramEnvelope;
import org.springframework.beans.factory.annotation.Value;
public class InstagramAPI extends API<InstagramEnvelope> {
@Value("${instagram.apikey}")
private String API_KEY;
@Value("${instagram.apiurl}")
private String API_URL;
public InstagramAPI() {
super();
}
public InstagramEnvelope getRaw(String... args) {
//TODO
return null;
}
}
|
package data.little;
public class Value implements Comparable<Value> {
final int myVal;
final int herVal;
public Value(int myVal, int herVal){
this.myVal = myVal;
this.herVal = herVal;
}
public boolean equals(Object o){
return (o instanceof Value) &&
myVal == ((Value)o).myVal &&
herVal == ((Value)o).herVal;
}
public int hashCode(){
return myVal + (5*herVal);
}
public int compareTo(Value o){
if (myVal != o.myVal) {
return myVal - o.myVal;
} else {
return herVal - o.herVal;
}
}
}
|
package org.pdxfinder.services;
import org.apache.lucene.util.automaton.LevenshteinAutomata;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONException;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.admin.pojos.MappingContainer;
import org.pdxfinder.admin.pojos.MappingEntity;
import org.pdxfinder.dao.Sample;
import org.pdxfinder.repositories.SampleRepository;
import org.pdxfinder.utils.DamerauLevenshteinAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class MappingService {
private final static Logger log = LoggerFactory.getLogger(MappingService.class);
@Value("${diagnosis.mappings.file}")
private String savedDiagnosisMappingsFile;
private SampleRepository sampleRepository;
private MappingContainer existingDiagnosisMappings;
@Autowired
public MappingService(SampleRepository sampleRepository) {
this.sampleRepository = sampleRepository;
}
private void loadSavedDiagnosisMappings(){
String json = parseFile(savedDiagnosisMappingsFile);
existingDiagnosisMappings = new MappingContainer();
try {
JSONObject job = new JSONObject(json);
if (job.has("rows")) {
JSONArray rows = job.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONObject row = rows.getJSONObject(i);
String dataSource = row.getString("datasource");
String sampleDiagnosis = row.getString("samplediagnosis").toLowerCase();
String originTissue = row.getString("origintissue");
String tumorType = row.getString("tumortype");
String ontologyTerm = row.getString("ontologyterm");
String mapType = row.getString("maptype");
String justification = row.getString("justification");
//if(ds!= null && !ds.toLowerCase().equals(dataSource.toLowerCase())) continue;
if (ontologyTerm.equals("") || ontologyTerm == null) continue;
if (sampleDiagnosis.equals("") || sampleDiagnosis == null) continue;
String updatedDiagnosis = sampleDiagnosis;
String pattern = "(.*)Malignant(.*)Neoplasm(.*)";
if (sampleDiagnosis.matches(pattern)) {
updatedDiagnosis = (sampleDiagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim();
log.info("Updating label from mapping service of diagnosis '{}' with '{}'", sampleDiagnosis, updatedDiagnosis);
}
// Remove commas from diagnosis
sampleDiagnosis = updatedDiagnosis.replaceAll(",", "");
//DO not ask, I know it looks horrible...
if (originTissue == null || originTissue.equals("null")) originTissue = "";
if (tumorType == null || tumorType.equals("null")) tumorType = "";
if (justification == null || justification.equals("null")) justification = "";
//make everything lowercase
if (dataSource != null) dataSource = dataSource.toLowerCase();
if (originTissue != null) originTissue = originTissue.toLowerCase();
if (tumorType != null) tumorType = tumorType.toLowerCase();
sampleDiagnosis = sampleDiagnosis.toLowerCase();
Map<String, String> mappingValues = new HashMap<>();
mappingValues.put("DataSource", dataSource);
mappingValues.put("SampleDiagnosis", sampleDiagnosis);
mappingValues.put("OriginTissue", originTissue);
mappingValues.put("TumorType", tumorType);
MappingEntity me = new MappingEntity(new Long(i+1), "DIAGNOSIS", getDiagnosisMappingLabels(), mappingValues);
me.setMappedTerm(ontologyTerm);
me.setMapType(mapType);
me.setJustification(justification);
existingDiagnosisMappings.add(me);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public MappingContainer getSavedDiagnosisMappings(String ds){
if(existingDiagnosisMappings == null){
loadSavedDiagnosisMappings();
}
//no filter, return everything
if(ds == null) return existingDiagnosisMappings;
MappingContainer mc = new MappingContainer();
List<MappingEntity> results = existingDiagnosisMappings.getMappings().values().stream().filter(
x -> x.getEntityType().equals("DIAGNOSIS") &&
x.getMappingValues().get("DataSource").equals(ds)).collect(Collectors.toList());
results.forEach(x -> {
mc.add(x);
});
return mc;
}
public MappingContainer getMissingDiagnosisMappings(String ds){
MappingContainer mc = new MappingContainer();
Collection<Sample> samplesWithoutMappedTerm;
Set<String> existingCombinations = new HashSet<>();
if(ds == null || ds.isEmpty()){
samplesWithoutMappedTerm = sampleRepository.findSamplesWithoutOntologyMapping();
}
else{
samplesWithoutMappedTerm = sampleRepository.findSamplesWithoutOntologyMappingByDataSource(ds);
}
int mappingCounter = 1;
log.info("Size: "+samplesWithoutMappedTerm.size());
for(Sample s : samplesWithoutMappedTerm){
String dataSource = s.getDataSource();
String sampleDiagnosis = s.getDiagnosis();
String originTissue = "";
String tumorType = "";
if(s.getOriginTissue() != null){
originTissue = s.getOriginTissue().getName();
}
if(s.getType() != null){
tumorType = s.getType().getName();
}
if(!existingCombinations.contains(dataSource+";"+sampleDiagnosis+";"+originTissue+";"+tumorType)){
Map<String, String> mappingValues = new HashMap<>();
mappingValues.put("DataSource", dataSource);
mappingValues.put("SampleDiagnosis", sampleDiagnosis);
mappingValues.put("OriginTissue", originTissue);
mappingValues.put("TumorType", tumorType);
MappingEntity me = new MappingEntity(mc.getNextAvailableId(), "DIAGNOSIS", getDiagnosisMappingLabels(), mappingValues);
//get suggestions for missing mapping
me.setSuggestedMappings(getSuggestionsForUnmappedEntity(me, getSavedDiagnosisMappings(null)));
mc.add(me);
existingCombinations.add(dataSource+";"+sampleDiagnosis+";"+originTissue+";"+tumorType);
}
}
return mc;
}
private List<MappingEntity> getSuggestionsForUnmappedEntity(MappingEntity me, MappingContainer mc){
String entityType = me.getEntityType();
TreeMap<Integer, List<MappingEntity>> unorderedSuggestions = new TreeMap<>();
//APPLY MAPPING SUGGESTION LOGIC HERE
List<MappingEntity> mapSuggList = mc.getMappings().values().stream().filter(x -> x.getEntityType().equals(entityType)).collect(Collectors.toList());
//Use the Damerau Levenshtein algorithm to determine string similarity
DamerauLevenshteinAlgorithm dla = new DamerauLevenshteinAlgorithm(1,1,2,2);
String typeKeyValues1 = getTypeKeyValues(me);
mapSuggList.forEach(x -> {
//get similarity index components
int simIndex = 0;
for(String label : x.getMappingLabels()){
simIndex += getSimilarityIndexComponent(dla, me.getEntityType(), label, me.getMappingValues().get(label), x.getMappingValues().get(label));
}
//x.setSimilarityIndex(getStringSimilarity(dla, typeKeyValues1, getTypeKeyValues(x)));
Integer index = new Integer(simIndex);
if(unorderedSuggestions.containsKey(index)){
unorderedSuggestions.get(index).add(x);
}
else{
List<MappingEntity> list = new ArrayList<>();
list.add(x);
unorderedSuggestions.put(index, list);
}
});
//take all mapped entities and order them by their stringsimilarity to the unmapped entity
//mapSuggList.stream().sorted((x1, x2) -> Integer.compare(getStringSimilarity(dla, typeKeyValues1, getTypeKeyValues(x1)), getStringSimilarity(dla, typeKeyValues1, getTypeKeyValues(x2))) );
//mapSuggList = mapSuggList.stream().sorted(Comparator.comparing(MappingEntity::getSimilarityIndex)).collect(Collectors.toList());
TreeMap<Integer, List<MappingEntity>> orderedSuggestions = new TreeMap<>(unorderedSuggestions);
List<MappingEntity> resultList = new ArrayList<>();
log.info("UNMAPPED: "+me.getMappingValues().get("SampleDiagnosis")+" "+me.getMappingValues().get("OriginTissue"));
int entityCounter = 0;
for(Map.Entry<Integer, List<MappingEntity>> entry : orderedSuggestions.entrySet()){
Integer ix = entry.getKey();
List<MappingEntity> list = entry.getValue();
for(MappingEntity ment : list){
log.info("SUGG: "+ment.getMappingValues().get("SampleDiagnosis")+" "+ment.getMappingValues().get("OriginTissue") + "INDEX:"+ix);
resultList.add(ment);
entityCounter++;
if(entityCounter>=10) break;
}
if(entityCounter>=10) break;
}
//return the first 10 suggestions
return resultList;
}
private String parseFile(String path) {
StringBuilder sb = new StringBuilder();
try {
Stream<String> stream = Files.lines(Paths.get(path));
Iterator itr = stream.iterator();
while (itr.hasNext()) {
sb.append(itr.next());
}
} catch (Exception e) {
log.error("Failed to load file " + path, e);
}
return sb.toString();
}
private int getSimilarityIndexComponent(DamerauLevenshteinAlgorithm dla, String entityType, String entityAttribute, String attribute1, String attribute2){
if(entityType.equals("DIAGNOSIS")){
if(entityAttribute.equals("SampleDiagnosis")){
return dla.execute(attribute1.toLowerCase(), attribute2.toLowerCase()) * 5;
}
else if(entityAttribute.equals("OriginTissue")){
int diff = dla.execute(attribute1.toLowerCase(), attribute2.toLowerCase());
//the origin tissue is very different, less likely will be a good suggestion
if(diff > 4) return 50;
return diff;
}
else{
int diff = dla.execute(attribute1.toLowerCase(), attribute2.toLowerCase());
if(diff > 4) return 1;
return diff;
}
}
return 10000;
}
String getTypeKeyValues(MappingEntity me){
String key = "";
if(me == null) return key;
switch (me.getEntityType()){
case "DIAGNOSIS":
for(String label : getDiagnosisMappingLabels()){
key += me.getMappingValues().get(label).toLowerCase();
}
break;
default: key = "";
}
return key;
}
List<String> getDiagnosisMappingLabels(){
List<String> mapLabels = new ArrayList<>();
mapLabels.add("DataSource");
mapLabels.add("SampleDiagnosis");
mapLabels.add("OriginTissue");
mapLabels.add("TumorType");
return mapLabels;
}
private int getStringSimilarity(DamerauLevenshteinAlgorithm dla, String key1, String key2){
return dla.execute(key1, key2);
}
}
|
package edu.umd.cs.findbugs.ba;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.ba.constant.ConstantAnalysis;
import edu.umd.cs.findbugs.ba.constant.ConstantDataflow;
/**
* A ClassContext caches all of the auxiliary objects used to analyze
* the methods of a class. That way, these objects don't need to
* be created over and over again.
*
* @author David Hovemeyer
*/
public class ClassContext implements AnalysisFeatures {
/**
* We only do pruning of infeasible exception edges
* if the <code>WORK_HARD</code> analysis feature
* is enabled.
*/
public static final boolean PRUNE_INFEASIBLE_EXCEPTION_EDGES = WORK_HARD;
/**
* Only try to determine unconditional exception throwers
* if we're not trying to conserve space.
*/
public static final boolean PRUNE_UNCONDITIONAL_EXCEPTION_THROWER_EDGES =
!CONSERVE_SPACE;
public static final boolean DEBUG = Boolean.getBoolean("classContext.debug");
private static final int PRUNED_INFEASIBLE_EXCEPTIONS = 1;
private static final int PRUNED_UNCONDITIONAL_THROWERS = 2;
private static final boolean TIME_ANALYSES = Boolean.getBoolean("classContext.timeAnalyses");
private static final boolean DEBUG_CFG = Boolean.getBoolean("classContext.debugCFG");
private static int depth;
private static void indent() {
for (int i = 0; i < depth; ++i) System.out.print(" ");
}
/**
* An AnalysisResult stores the result of requesting an analysis
* from an AnalysisFactory. It can represent a successful outcome
* (where the Analysis object can be returned), or an unsuccessful
* outcome (where an exception was thrown trying to create the
* analysis). For unsuccessful outcomes, we rethrow the original
* exception rather than making another attempt to create the analysis
* (since if it fails once, it will never succeed).
*/
private static class AnalysisResult<Analysis> {
private boolean analysisSetExplicitly;
private Analysis analysis;
private AnalysisException analysisException;
private CFGBuilderException cfgBuilderException;
private DataflowAnalysisException dataflowAnalysisException;
public Analysis getAnalysis() throws CFGBuilderException, DataflowAnalysisException {
if (analysisSetExplicitly)
return analysis;
if (dataflowAnalysisException != null)
throw dataflowAnalysisException;
if (analysisException != null)
throw analysisException;
if (cfgBuilderException != null)
throw cfgBuilderException;
throw new IllegalStateException();
}
/**
* Record a successful outcome, where the analysis was created.
*
* @param analysis the Analysis
*/
public void setAnalysis(Analysis analysis) {
this.analysisSetExplicitly = true;
this.analysis = analysis;
}
/**
* Record that an AnalysisException occurred while attempting
* to create the Analysis.
*
* @param analysisException the AnalysisException
*/
public void setAnalysisException(AnalysisException analysisException) {
this.analysisException = analysisException;
}
/**
* Record that a CFGBuilderException occurred while attempting
* to create the Analysis.
*
* @param cfgBuilderException the CFGBuilderException
*/
public void setCFGBuilderException(CFGBuilderException cfgBuilderException) {
this.cfgBuilderException = cfgBuilderException;
}
/**
* Record that a DataflowAnalysisException occurred while attempting
* to create the Analysis.
*
* @param dataflowException the DataflowAnalysisException
*/
public void setDataflowAnalysisException(DataflowAnalysisException dataflowException) {
this.dataflowAnalysisException = dataflowException;
}
}
/**
* Abstract factory class for creating analysis objects.
* Handles caching of analysis results for a method.
*/
private abstract class AnalysisFactory <Analysis> {
private String analysisName;
private HashMap<Method, ClassContext.AnalysisResult<Analysis>> map =
new HashMap<Method, ClassContext.AnalysisResult<Analysis>>();
/**
* Constructor.
*
* @param analysisName name of the analysis factory: for diagnostics/debugging
*/
public AnalysisFactory(String analysisName) {
this.analysisName = analysisName;
}
/**
* Get the Analysis for given method.
* If Analysis has already been performed, the cached result is
* returned.
*
* @param method the method to analyze
* @return the Analysis object representing the result of analyzing the method
* @throws CFGBuilderException if the CFG can't be constructed for the method
* @throws DataflowAnalysisException if dataflow analysis fails on the method
*/
public Analysis getAnalysis(Method method) throws CFGBuilderException, DataflowAnalysisException {
AnalysisResult<Analysis> result = map.get(method);
if (result == null) {
if (TIME_ANALYSES) {
++depth;
indent();
System.out.println("CC: Starting " + analysisName + " for " +
SignatureConverter.convertMethodSignature(jclass, method) + ":");
}
long begin = System.currentTimeMillis();
// Create a new AnalysisResult
result = new AnalysisResult<Analysis>();
// Attempt to create the Analysis and store it in the AnalysisResult.
// If an exception occurs, record it in the AnalysisResult.
Analysis analysis = null;
try {
analysis = analyze(method);
result.setAnalysis(analysis);
} catch (CFGBuilderException e) {
result.setCFGBuilderException(e);
} catch (DataflowAnalysisException e) {
if (TIME_ANALYSES) {
long end = System.currentTimeMillis();
indent();
System.out.println("CC: " + analysisName + " killed by exception after " +
(end - begin) + " millis");
e.printStackTrace();
--depth;
}
result.setDataflowAnalysisException(e);
} catch (AnalysisException e) {
result.setAnalysisException(e);
}
if (TIME_ANALYSES) {
long end = System.currentTimeMillis();
indent();
System.out.println("CC: finished " + analysisName + " in " + (end - begin) + " millis");
--depth;
}
// Cache the outcome of this analysis attempt.
map.put(method, result);
}
return result.getAnalysis();
}
protected abstract Analysis analyze(Method method)
throws CFGBuilderException, DataflowAnalysisException;
}
private abstract class NoExceptionAnalysisFactory <AnalysisResult> extends AnalysisFactory<AnalysisResult> {
public NoExceptionAnalysisFactory(String analysisName) {
super(analysisName);
}
public AnalysisResult getAnalysis(Method method) {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
} catch (CFGBuilderException e) {
throw new IllegalStateException("Should not happen");
}
}
}
private abstract class NoDataflowAnalysisFactory <AnalysisResult> extends AnalysisFactory<AnalysisResult> {
public NoDataflowAnalysisFactory(String analysisName) {
super(analysisName);
}
public AnalysisResult getAnalysis(Method method) throws CFGBuilderException {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
}
}
}
private static final Set<String> busyCFGSet = new HashSet<String>();
private class CFGFactory extends AnalysisFactory<CFG> {
public CFGFactory() {
super("CFG construction");
}
public CFG getAnalysis(Method method) throws CFGBuilderException {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
}
}
public CFG getRawCFG(Method method) throws CFGBuilderException {
return getAnalysis(method);
}
public CFG getRefinedCFG(Method method) throws CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getRawCFG(method);
// HACK:
// Due to recursive method invocations, we may get a recursive
// request for the pruned CFG of a method. In this case,
// we just return the raw CFG.
String methodId = methodGen.getClassName() + "." + methodGen.getName() + ":" + methodGen.getSignature();
if (DEBUG_CFG) {
indent();
System.out.println("CC: getting refined CFG for " + methodId);
}
if (DEBUG) System.out.println("ClassContext: request to prune " + methodId);
if (!busyCFGSet.add(methodId))
return cfg;
if (PRUNE_INFEASIBLE_EXCEPTION_EDGES && !cfg.isFlagSet(PRUNED_INFEASIBLE_EXCEPTIONS)) {
try {
TypeDataflow typeDataflow = getTypeDataflow(method);
new PruneInfeasibleExceptionEdges(cfg, getMethodGen(method), typeDataflow).execute();
} catch (DataflowAnalysisException e) {
// FIXME: should report the error
} catch (ClassNotFoundException e) {
getLookupFailureCallback().reportMissingClass(e);
}
}
cfg.setFlags(cfg.getFlags() | PRUNED_INFEASIBLE_EXCEPTIONS);
if (PRUNE_UNCONDITIONAL_EXCEPTION_THROWER_EDGES && !cfg.isFlagSet(PRUNED_UNCONDITIONAL_THROWERS)) {
try {
new PruneUnconditionalExceptionThrowerEdges(methodGen, cfg, getConstantPoolGen(), analysisContext).execute();
} catch (DataflowAnalysisException e) {
// FIXME: should report the error
}
}
cfg.setFlags(cfg.getFlags() | PRUNED_UNCONDITIONAL_THROWERS);
busyCFGSet.remove(methodId);
return cfg;
}
protected CFG analyze(Method method) throws CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFGBuilder cfgBuilder = CFGBuilderFactory.create(methodGen);
cfgBuilder.build();
return cfgBuilder.getCFG();
}
}
private JavaClass jclass;
private AnalysisContext analysisContext;
private NoExceptionAnalysisFactory<MethodGen> methodGenFactory =
new NoExceptionAnalysisFactory<MethodGen>("MethodGen construction") {
protected MethodGen analyze(Method method) {
if (method.getCode() == null)
return null;
return new MethodGen(method, jclass.getClassName(), getConstantPoolGen());
}
};
private CFGFactory cfgFactory = new CFGFactory();
private AnalysisFactory<ValueNumberDataflow> vnaDataflowFactory =
new AnalysisFactory<ValueNumberDataflow>("value number analysis") {
protected ValueNumberDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
LoadedFieldSet loadedFieldSet = getLoadedFieldSet(method);
ValueNumberAnalysis analysis = new ValueNumberAnalysis(methodGen, dfs, loadedFieldSet,
getLookupFailureCallback());
CFG cfg = getCFG(method);
ValueNumberDataflow vnaDataflow = new ValueNumberDataflow(cfg, analysis);
vnaDataflow.execute();
return vnaDataflow;
}
};
private AnalysisFactory<IsNullValueDataflow> invDataflowFactory =
new AnalysisFactory<IsNullValueDataflow>("null value analysis") {
protected IsNullValueDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getCFG(method);
ValueNumberDataflow vnaDataflow = getValueNumberDataflow(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
AssertionMethods assertionMethods = getAssertionMethods();
IsNullValueAnalysis invAnalysis = new IsNullValueAnalysis(methodGen, cfg, vnaDataflow, dfs, assertionMethods);
IsNullValueDataflow invDataflow = new IsNullValueDataflow(cfg, invAnalysis);
invDataflow.execute();
return invDataflow;
}
};
private AnalysisFactory<TypeDataflow> typeDataflowFactory =
new AnalysisFactory<TypeDataflow>("type analysis") {
protected TypeDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getRawCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
ExceptionSetFactory exceptionSetFactory = getExceptionSetFactory(method);
TypeAnalysis typeAnalysis =
new TypeAnalysis(methodGen, cfg, dfs, getLookupFailureCallback(), exceptionSetFactory);
TypeDataflow typeDataflow = new TypeDataflow(cfg, typeAnalysis);
typeDataflow.execute();
return typeDataflow;
}
};
private NoDataflowAnalysisFactory<DepthFirstSearch> dfsFactory =
new NoDataflowAnalysisFactory<DepthFirstSearch>("depth first search") {
protected DepthFirstSearch analyze(Method method) throws CFGBuilderException {
CFG cfg = getRawCFG(method);
DepthFirstSearch dfs = new DepthFirstSearch(cfg);
dfs.search();
return dfs;
}
};
private NoDataflowAnalysisFactory<ReverseDepthFirstSearch> rdfsFactory =
new NoDataflowAnalysisFactory<ReverseDepthFirstSearch>("reverse depth first search") {
protected ReverseDepthFirstSearch analyze(Method method) throws CFGBuilderException {
CFG cfg = getRawCFG(method);
ReverseDepthFirstSearch rdfs = new ReverseDepthFirstSearch(cfg);
rdfs.search();
return rdfs;
}
};
private NoExceptionAnalysisFactory<BitSet> bytecodeSetFactory =
new NoExceptionAnalysisFactory<BitSet>("bytecode set construction") {
protected BitSet analyze(Method method) {
final BitSet result = new BitSet();
Code code = method.getCode();
if (code != null) {
byte[] instructionList = code.getCode();
// Create a callback to put the opcodes of the method's
// bytecode instructions into the BitSet.
BytecodeScanner.Callback callback = new BytecodeScanner.Callback() {
public void handleInstruction(int opcode, int index) {
result.set(opcode, true);
}
};
// Scan the method.
BytecodeScanner scanner = new BytecodeScanner();
scanner.scan(instructionList, callback);
}
return result;
}
};
private AnalysisFactory<LockDataflow> lockDataflowFactory =
new AnalysisFactory<LockDataflow>("lock set analysis") {
protected LockDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
ValueNumberDataflow vnaDataflow = getValueNumberDataflow(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
CFG cfg = getCFG(method);
LockAnalysis analysis = new LockAnalysis(methodGen, vnaDataflow, dfs);
LockDataflow dataflow = new LockDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<LockChecker> lockCheckerFactory =
new AnalysisFactory<LockChecker>("lock checker meta-analysis") {
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.ClassContext.AnalysisFactory#analyze(org.apache.bcel.classfile.Method)
*/
protected LockChecker analyze(Method method) throws CFGBuilderException,
DataflowAnalysisException {
LockChecker lockChecker = new LockChecker(ClassContext.this, method);
lockChecker.execute();
return lockChecker;
}
};
private AnalysisFactory<ReturnPathDataflow> returnPathDataflowFactory =
new AnalysisFactory<ReturnPathDataflow>("return path analysis") {
protected ReturnPathDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
ReturnPathAnalysis analysis = new ReturnPathAnalysis(dfs);
ReturnPathDataflow dataflow = new ReturnPathDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<DominatorsAnalysis> nonExceptionDominatorsAnalysisFactory =
new AnalysisFactory<DominatorsAnalysis>("non-exception dominators analysis") {
protected DominatorsAnalysis analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
DominatorsAnalysis analysis = new DominatorsAnalysis(cfg, dfs, true);
Dataflow<java.util.BitSet, DominatorsAnalysis> dataflow =
new Dataflow<java.util.BitSet, DominatorsAnalysis>(cfg, analysis);
dataflow.execute();
return analysis;
}
};
private AnalysisFactory<PostDominatorsAnalysis> nonExceptionPostDominatorsAnalysisFactory =
new AnalysisFactory<PostDominatorsAnalysis>("non-exception postdominators analysis") {
protected PostDominatorsAnalysis analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
ReverseDepthFirstSearch rdfs = getReverseDepthFirstSearch(method);
PostDominatorsAnalysis analysis = new PostDominatorsAnalysis(cfg, rdfs, true);
Dataflow<java.util.BitSet, PostDominatorsAnalysis> dataflow =
new Dataflow<java.util.BitSet, PostDominatorsAnalysis>(cfg, analysis);
dataflow.execute();
return analysis;
}
};
private NoExceptionAnalysisFactory<ExceptionSetFactory> exceptionSetFactoryFactory =
new NoExceptionAnalysisFactory<ExceptionSetFactory>("exception set factory") {
protected ExceptionSetFactory analyze(Method method) {
return new ExceptionSetFactory();
}
};
private NoExceptionAnalysisFactory<String[]> parameterSignatureListFactory =
new NoExceptionAnalysisFactory<String[]>("parameter signature list factory") {
protected String[] analyze(Method method) {
SignatureParser parser = new SignatureParser(method.getSignature());
ArrayList<String> resultList = new ArrayList<String>();
for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
resultList.add(i.next());
}
return resultList.toArray(new String[resultList.size()]);
}
};
private AnalysisFactory<ConstantDataflow> constantDataflowFactory =
new AnalysisFactory<ConstantDataflow>("constant propagation analysis") {
//@Override
protected ConstantDataflow analyze(Method method) throws CFGBuilderException, DataflowAnalysisException {
ConstantAnalysis analysis = new ConstantAnalysis(
getMethodGen(method),
getDepthFirstSearch(method)
);
ConstantDataflow dataflow = new ConstantDataflow(getCFG(method), analysis);
dataflow.execute();
return dataflow;
}
};
private static final BitSet fieldInstructionOpcodeSet = new BitSet();
static {
fieldInstructionOpcodeSet.set(Constants.GETFIELD);
fieldInstructionOpcodeSet.set(Constants.PUTFIELD);
fieldInstructionOpcodeSet.set(Constants.GETSTATIC);
fieldInstructionOpcodeSet.set(Constants.PUTSTATIC);
}
/**
* Factory to determine which fields are loaded and stored
* by the instructions in a method, and the overall method.
* The main purpose is to support efficient redundant load elimination
* and forward substitution in ValueNumberAnalysis (there is no need to
* remember stores of fields that are never read,
* or loads of fields that are only loaded in one location).
* However, it might be useful for other kinds of analysis.
*
* <p> The tricky part is that in addition to fields loaded and stored
* with get/putfield and get/putstatic, we also try to figure
* out field accessed through calls to inner-class access methods.
*/
private NoExceptionAnalysisFactory<LoadedFieldSet> loadedFieldSetFactory =
new NoExceptionAnalysisFactory<LoadedFieldSet>("loaded field set factory") {
protected LoadedFieldSet analyze(Method method) {
MethodGen methodGen = getMethodGen(method);
InstructionList il = methodGen.getInstructionList();
LoadedFieldSet loadedFieldSet = new LoadedFieldSet(methodGen);
for (InstructionHandle handle = il.getStart(); handle != null; handle = handle.getNext()) {
Instruction ins = handle.getInstruction();
short opcode = ins.getOpcode();
try {
if (opcode == Constants.INVOKESTATIC) {
INVOKESTATIC inv = (INVOKESTATIC) ins;
if (Hierarchy.isInnerClassAccess(inv, getConstantPoolGen())) {
InnerClassAccess access = Hierarchy.getInnerClassAccess(inv, getConstantPoolGen());
/*
if (access == null) {
System.out.println("Missing inner class access in " +
SignatureConverter.convertMethodSignature(methodGen) + " at " +
inv);
}
*/
if (access != null) {
if (access.isLoad())
loadedFieldSet.addLoad(handle, access.getField());
else
loadedFieldSet.addStore(handle, access.getField());
}
}
} else if (fieldInstructionOpcodeSet.get(opcode)) {
boolean isLoad = (opcode == Constants.GETFIELD || opcode == Constants.GETSTATIC);
XField field = Hierarchy.findXField((FieldInstruction) ins, getConstantPoolGen());
if (field != null) {
if (isLoad)
loadedFieldSet.addLoad(handle, field);
else
loadedFieldSet.addStore(handle, field);
}
}
} catch (ClassNotFoundException e) {
analysisContext.getLookupFailureCallback().reportMissingClass(e);
}
}
return loadedFieldSet;
}
};
private AnalysisFactory<LiveLocalStoreDataflow> liveLocalStoreDataflowFactory =
new AnalysisFactory<LiveLocalStoreDataflow>("live local stores analysis") {
protected LiveLocalStoreDataflow analyze(Method method)
throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
MethodGen methodGen = getMethodGen(method);
ReverseDepthFirstSearch rdfs = getReverseDepthFirstSearch(method);
LiveLocalStoreAnalysis analysis = new LiveLocalStoreAnalysis(methodGen, rdfs);
LiveLocalStoreDataflow dataflow = new LiveLocalStoreDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<Dataflow<BlockType, BlockTypeAnalysis>> blockTypeDataflowFactory =
new AnalysisFactory<Dataflow<BlockType, BlockTypeAnalysis>>("block type analysis") {
protected Dataflow<BlockType, BlockTypeAnalysis> analyze(Method method)
throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
BlockTypeAnalysis analysis = new BlockTypeAnalysis(dfs);
Dataflow<BlockType, BlockTypeAnalysis> dataflow =
new Dataflow<BlockType, BlockTypeAnalysis>(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private ClassGen classGen;
private AssignedFieldMap assignedFieldMap;
private AssertionMethods assertionMethods;
/**
* Constructor.
*
* @param jclass the JavaClass
*/
public ClassContext(JavaClass jclass, AnalysisContext analysisContext) {
this.jclass = jclass;
this.analysisContext = analysisContext;
this.classGen = null;
this.assignedFieldMap = null;
this.assertionMethods = null;
}
/**
* Get the JavaClass.
*/
public JavaClass getJavaClass() {
return jclass;
}
/**
* Get the AnalysisContext.
*/
public AnalysisContext getAnalysisContext() {
return analysisContext;
}
/**
* Get the RepositoryLookupFailureCallback.
*
* @return the RepositoryLookupFailureCallback
*/
public RepositoryLookupFailureCallback getLookupFailureCallback() {
return analysisContext.getLookupFailureCallback();
}
/**
* Get a MethodGen object for given method.
*
* @param method the method
* @return the MethodGen object for the method, or null
* if the method has no Code attribute (and thus cannot be analyzed)
*/
public MethodGen getMethodGen(Method method) {
return methodGenFactory.getAnalysis(method);
}
/**
* Get a "raw" CFG for given method.
* No pruning is done, although the CFG may already be pruned.
*
* @param method the method
* @return the raw CFG
*/
public CFG getRawCFG(Method method) throws CFGBuilderException {
return cfgFactory.getRawCFG(method);
}
/**
* Get a CFG for given method.
* If pruning options are in effect, pruning will be done.
* Because the CFG pruning can involve interprocedural analysis,
* it is done on a best-effort basis, so the CFG returned might
* not actually be pruned.
*
* @param method the method
* @return the CFG
* @throws CFGBuilderException if a CFG cannot be constructed for the method
*/
public CFG getCFG(Method method) throws CFGBuilderException {
return cfgFactory.getRefinedCFG(method);
}
/**
* Get the ConstantPoolGen used to create the MethodGens
* for this class.
*
* @return the ConstantPoolGen
*/
public ConstantPoolGen getConstantPoolGen() {
if (classGen == null)
classGen = new ClassGen(jclass);
return classGen.getConstantPool();
}
/**
* Get a ValueNumberDataflow for given method.
*
* @param method the method
* @return the ValueNumberDataflow
*/
public ValueNumberDataflow getValueNumberDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return vnaDataflowFactory.getAnalysis(method);
}
/**
* Get an IsNullValueDataflow for given method.
*
* @param method the method
* @return the IsNullValueDataflow
*/
public IsNullValueDataflow getIsNullValueDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return invDataflowFactory.getAnalysis(method);
}
/**
* Get a TypeDataflow for given method.
*
* @param method the method
* @return the TypeDataflow
*/
public TypeDataflow getTypeDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return typeDataflowFactory.getAnalysis(method);
}
/**
* Get a DepthFirstSearch for given method.
*
* @param method the method
* @return the DepthFirstSearch
*/
public DepthFirstSearch getDepthFirstSearch(Method method) throws CFGBuilderException {
return dfsFactory.getAnalysis(method);
}
/**
* Get a ReverseDepthFirstSearch for given method.
*
* @param method the method
* @return the ReverseDepthFirstSearch
*/
public ReverseDepthFirstSearch getReverseDepthFirstSearch(Method method)
throws CFGBuilderException {
return rdfsFactory.getAnalysis(method);
}
/**
* Get a BitSet representing the bytecodes that are used in the given method.
* This is useful for prescreening a method for the existence of particular instructions.
* Because this step doesn't require building a MethodGen, it is very
* fast and memory-efficient. It may allow a Detector to avoid some
* very expensive analysis, which is a Big Win for the user.
*
* @param method the method
* @return the BitSet containing the opcodes which appear in the method
*/
public BitSet getBytecodeSet(Method method) {
return bytecodeSetFactory.getAnalysis(method);
}
/**
* Get dataflow for LockAnalysis for given method.
*
* @param method the method
* @return the LockDataflow
*/
public LockDataflow getLockDataflow(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return lockDataflowFactory.getAnalysis(method);
}
/**
* Get LockChecker for method.
* This is like LockDataflow, but may be able to avoid performing
* the actual dataflow analyses if the method doesn't contain
* explicit monitorenter/monitorexit instructions.
*
* @param method the method
* @return the LockChecker
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
public LockChecker getLockChecker(Method method) throws CFGBuilderException, DataflowAnalysisException {
return lockCheckerFactory.getAnalysis(method);
}
/**
* Get ReturnPathDataflow for method.
*
* @param method the method
* @return the ReturnPathDataflow
*/
public ReturnPathDataflow getReturnPathDataflow(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return returnPathDataflowFactory.getAnalysis(method);
}
/**
* Get DominatorsAnalysis for given method,
* where exception edges are ignored.
*
* @param method the method
* @return the DominatorsAnalysis
*/
public DominatorsAnalysis getNonExceptionDominatorsAnalysis(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return nonExceptionDominatorsAnalysisFactory.getAnalysis(method);
}
/**
* Get PostDominatorsAnalysis for given method,
* where exception edges are ignored.
*
* @param method the method
* @return the PostDominatorsAnalysis
*/
public PostDominatorsAnalysis getNonExceptionPostDominatorsAnalysis(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return nonExceptionPostDominatorsAnalysisFactory.getAnalysis(method);
}
/**
* Get ExceptionSetFactory for given method.
*
* @param method the method
* @return the ExceptionSetFactory
*/
public ExceptionSetFactory getExceptionSetFactory(Method method) {
return exceptionSetFactoryFactory.getAnalysis(method);
}
/**
* Get array of type signatures of parameters for given method.
*
* @param method the method
* @return an array of type signatures indicating the types
* of the method's parameters
*/
public String[] getParameterSignatureList(Method method) {
return parameterSignatureListFactory.getAnalysis(method);
}
/**
* Get the set of fields loaded by given method.
*
* @param method the method
* @return the set of fields loaded by the method
*/
public LoadedFieldSet getLoadedFieldSet(Method method) {
return loadedFieldSetFactory.getAnalysis(method);
}
/**
* Get LiveLocalStoreAnalysis dataflow for given method.
*
* @param method the method
* @return the Dataflow object for LiveLocalStoreAnalysis on the method
*/
public LiveLocalStoreDataflow getLiveLocalStoreDataflow(Method method)
throws DataflowAnalysisException, CFGBuilderException {
return liveLocalStoreDataflowFactory.getAnalysis(method);
}
/**
* Get BlockType dataflow for given method.
*
* @param method the method
* @return the Dataflow object for BlockTypeAnalysis on the method
*/
public Dataflow<BlockType, BlockTypeAnalysis> getBlockTypeDataflow(Method method)
throws DataflowAnalysisException, CFGBuilderException {
return blockTypeDataflowFactory.getAnalysis(method);
}
/**
* Get the assigned field map for the class.
*
* @return the AssignedFieldMap
* @throws ClassNotFoundException if a class lookup prevents
* the class's superclasses from being searched for
* assignable fields
*/
public AssignedFieldMap getAssignedFieldMap() throws ClassNotFoundException {
if (assignedFieldMap == null) {
assignedFieldMap = new AssignedFieldMap(this);
}
return assignedFieldMap;
}
/**
* Get AssertionMethods for class.
*
* @return the AssertionMethods
*/
public AssertionMethods getAssertionMethods() {
if (assertionMethods == null) {
assertionMethods = new AssertionMethods(jclass);
}
return assertionMethods;
}
public ConstantDataflow getConstantDataflow(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return constantDataflowFactory.getAnalysis(method);
}
}
// vim:ts=3
|
package edu.umd.cs.findbugs.ba.ch;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.DefaultAnnotationForParameters;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ObjectTypeFactory;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.bcel.BCELUtil;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.util.DualKeyHashMap;
/**
* Class for performing class hierarchy queries.
* Does <em>not</em> require JavaClass objects to be in memory.
* Instead, uses XClass objects.
*
* @author David Hovemeyer
*/
@DefaultAnnotationForParameters(NonNull.class)
public class Subtypes2 {
public static final boolean ENABLE_SUBTYPES2 = true; //SystemProperties.getBoolean("findbugs.subtypes2");
public static final boolean ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES =
true; //SystemProperties.getBoolean("findbugs.subtypes2.superclass");
public static final boolean DEBUG = SystemProperties.getBoolean("findbugs.subtypes2.debug");
public static final boolean DEBUG_QUERIES = SystemProperties.getBoolean("findbugs.subtypes2.debugqueries");
private final InheritanceGraph graph;
private final Map<ClassDescriptor, ClassVertex> classDescriptorToVertexMap;
private final Map<ClassDescriptor, SupertypeQueryResults> supertypeSetMap;
private final Map<ClassDescriptor, Set<ClassDescriptor>> subtypeSetMap;
private final Set<XClass> xclassSet;
private final DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType> firstCommonSuperclassQueryCache;
private final ObjectType SERIALIZABLE;
private final ObjectType CLONEABLE;
/**
* Object to record the results of a supertype search.
*/
private static class SupertypeQueryResults {
private Set<ClassDescriptor> supertypeSet = new HashSet<ClassDescriptor>();
private boolean encounteredMissingClasses = false;
public void addSupertype(ClassDescriptor classDescriptor) {
supertypeSet.add(classDescriptor);
}
public void setEncounteredMissingClasses(boolean encounteredMissingClasses) {
this.encounteredMissingClasses = encounteredMissingClasses;
}
public boolean containsType(ClassDescriptor possibleSupertypeClassDescriptor) throws ClassNotFoundException {
if (supertypeSet.contains(possibleSupertypeClassDescriptor)) {
return true;
} else if (!encounteredMissingClasses) {
return false;
} else {
// We don't really know which class was missing.
// However, any missing classes will already have been reported.
throw new ClassNotFoundException();
}
}
}
/**
* Constructor.
*/
public Subtypes2() {
this.graph = new InheritanceGraph();
this.classDescriptorToVertexMap = new HashMap<ClassDescriptor, ClassVertex>();
this.supertypeSetMap = new HashMap<ClassDescriptor, SupertypeQueryResults>();// XXX: use MapCache?
this.subtypeSetMap = new HashMap<ClassDescriptor, Set<ClassDescriptor>>();// XXX: use MapCache?
this.xclassSet = new HashSet<XClass>();
this.SERIALIZABLE = ObjectTypeFactory.getInstance("java.io.Serializable");
this.CLONEABLE = ObjectTypeFactory.getInstance("java.lang.Cloneable");
this.firstCommonSuperclassQueryCache = new DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType>();
}
/**
* @return Returns the graph.
*/
public InheritanceGraph getGraph() {
return graph;
}
/**
* Add an application class, and its transitive supertypes, to the inheritance graph.
*
* @param appXClass application XClass to add to the inheritance graph
*/
public void addApplicationClass(XClass appXClass) {
ClassVertex vertex = addClassAndGetClassVertex(appXClass);
vertex.markAsApplicationClass();
}
/**
* Add a class or interface, and its transitive supertypes, to the inheritance graph.
*
* @param xclass XClass to add to the inheritance graph
*/
public void addClass(XClass xclass) {
addClassAndGetClassVertex(xclass);
}
/**
* Add an XClass and all of its supertypes to
* the InheritanceGraph.
*
* @param xclass an XClass
* @return the ClassVertex representing the class in
* the InheritanceGraph
*/
private ClassVertex addClassAndGetClassVertex(XClass xclass) {
if (xclass == null) {
throw new IllegalStateException();
}
LinkedList<XClass> workList = new LinkedList<XClass>();
workList.add(xclass);
while (!workList.isEmpty()) {
XClass work = workList.removeFirst();
ClassVertex vertex = classDescriptorToVertexMap.get(work.getClassDescriptor());
if (vertex != null && vertex.isFinished()) {
// This class has already been processed.
continue;
}
if (vertex == null) {
vertex = ClassVertex.createResolvedClassVertex(work.getClassDescriptor(), work);
addVertexToGraph(work.getClassDescriptor(), vertex);
}
addSupertypeEdges(vertex, workList);
vertex.setFinished(true);
}
return classDescriptorToVertexMap.get(xclass.getClassDescriptor());
}
private void addVertexToGraph(ClassDescriptor classDescriptor, ClassVertex vertex) {
if (classDescriptorToVertexMap.get(classDescriptor) != null) {
throw new IllegalStateException();
}
if (DEBUG) {
System.out.println("Adding " + classDescriptor.toDottedClassName() + " to inheritance graph");
}
graph.addVertex(vertex);
classDescriptorToVertexMap.put(classDescriptor, vertex);
if (vertex.isResolved()) {
xclassSet.add(vertex.getXClass());
}
if (vertex.isInterface()) {
// There is no need to add additional worklist nodes because java/lang/Object has no supertypes.
addInheritanceEdge(vertex, DescriptorFactory.instance().getClassDescriptor("java/lang/Object"), false, null);
}
}
/**
* Determine whether or not a given ReferenceType is a subtype of another.
* Throws ClassNotFoundException if the question cannot be answered
* definitively due to a missing class.
*
* @param type a ReferenceType
* @param possibleSupertype another Reference type
* @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not
* @throws ClassNotFoundException if a missing class prevents a definitive answer
*/
public boolean isSubtype(ReferenceType type, ReferenceType possibleSupertype) throws ClassNotFoundException {
// Eliminate some easy cases
if (type.equals(possibleSupertype)) {
return true;
}
// others?
boolean typeIsObjectType = (type instanceof ObjectType);
boolean possibleSupertypeIsObjectType = (possibleSupertype instanceof ObjectType);
if (typeIsObjectType && possibleSupertypeIsObjectType) {
// Both types are ordinary object (non-array) types.
return isSubtype((ObjectType) type, (ObjectType) possibleSupertype);
}
boolean typeIsArrayType = (type instanceof ArrayType);
boolean possibleSupertypeIsArrayType = (possibleSupertype instanceof ArrayType);
if (typeIsArrayType) {
// Check superclass/interfaces
if (possibleSupertype.equals(ObjectType.OBJECT)
|| possibleSupertype.equals(SERIALIZABLE)
|| possibleSupertype.equals(CLONEABLE)) {
return true;
}
// We checked all of the possible class/interface supertypes,
// so if possibleSupertype is not an array type,
// then we can definitively say no
if (!possibleSupertypeIsArrayType) {
return false;
}
// Check array/array subtype relationship
ArrayType typeAsArrayType = (ArrayType) type;
ArrayType possibleSupertypeAsArrayType = (ArrayType) possibleSupertype;
// Must have same number of dimensions
if (typeAsArrayType.getDimensions() < possibleSupertypeAsArrayType.getDimensions()) {
return false;
}
Type possibleSupertypeBasicType = possibleSupertypeAsArrayType.getBasicType();
if (!(possibleSupertypeBasicType instanceof ObjectType)) {
return false;
}
Type typeBasicType = typeAsArrayType.getBasicType();
// If dimensions differ, see if element types are compatible.
if (typeAsArrayType.getDimensions() > possibleSupertypeAsArrayType.getDimensions()) {
return isSubtype(new ArrayType(typeBasicType,typeAsArrayType.getDimensions() - possibleSupertypeAsArrayType.getDimensions() ),
(ObjectType) possibleSupertypeBasicType);
}
// type's base type must be a subtype of possibleSupertype's base type.
// Note that neither base type can be a non-ObjectType if we are to answer yes.
if (!(typeBasicType instanceof ObjectType)) {
return false;
}
return isSubtype((ObjectType) typeBasicType, (ObjectType) possibleSupertypeBasicType);
}
// OK, we've exhausted the possibilities now
return false;
}
/**
* Determine whether or not a given ObjectType is a subtype of another.
* Throws ClassNotFoundException if the question cannot be answered
* definitively due to a missing class.
*
* @param type a ReferenceType
* @param possibleSupertype another Reference type
* @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not
* @throws ClassNotFoundException if a missing class prevents a definitive answer
*/
public boolean isSubtype(ObjectType type, ObjectType possibleSupertype) throws ClassNotFoundException {
if (DEBUG_QUERIES) {
System.out.println("isSubtype: check " + type + " subtype of " + possibleSupertype);
}
if (type.equals(possibleSupertype)) {
if (DEBUG_QUERIES) {
System.out.println(" ==> yes, types are same");
}
return true;
}
ClassDescriptor typeClassDescriptor = BCELUtil.getClassDescriptor(type);
ClassDescriptor possibleSuperclassClassDescriptor = BCELUtil.getClassDescriptor(possibleSupertype);
ClassVertex possibleSuperclassClassVertex = resolveClassVertex(possibleSuperclassClassDescriptor);
// In principle, we should be able to answer no if the ObjectType objects
// are not equal and possibleSupertype is final.
// However, internally FindBugs creates special "subtypes" of java.lang.String
// These will end up resolving to the same ClassVertex as java.lang.String,
// which will Do The Right Thing.
/*
if (possibleSuperclassClassVertex.isResolved() && possibleSuperclassClassVertex.getXClass().isFinal()) {
if (DEBUG_QUERIES) {
System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is final");
}
return false;
}
*/
// Get the supertype query results
SupertypeQueryResults supertypeQueryResults = getSupertypeQueryResults(typeClassDescriptor);
if (DEBUG_QUERIES) {
System.out.println(" Superclass set: " + supertypeQueryResults.supertypeSet);
}
boolean isSubtype = supertypeQueryResults.containsType(possibleSuperclassClassDescriptor);
if (DEBUG_QUERIES) {
if (isSubtype) {
System.out.println(" ==> yes, " + possibleSuperclassClassDescriptor + " is in superclass set");
} else {
System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is not in superclass set");
}
}
return isSubtype;
}
/**
* Get the first common superclass of the given reference types.
* Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the
* same type. Otherwise, we try to return as accurate a type as possible.
* This method is used as the meet operator in TypeDataflowAnalysis,
* and is intended to follow (more or less) the JVM bytecode verifier
* semantics.
*
* <p>This method should be used in preference to the getFirstCommonSuperclass()
* method in {@link ReferenceType}.</p>
*
* @param a a ReferenceType
* @param b another ReferenceType
* @return the first common superclass of <code>a</code> and <code>b</code>
* @throws ClassNotFoundException
*/
public ReferenceType getFirstCommonSuperclass(ReferenceType a, ReferenceType b) throws ClassNotFoundException {
// Easy case: same types
if (a.equals(b)) {
return a;
}
ReferenceType answer = checkFirstCommonSuperclassQueryCache(a, b);
if (answer == null) {
answer = computeFirstCommonSuperclassOfReferenceTypes(a, b);
putFirstCommonSuperclassQueryCache(a, b, answer);
}
return answer;
}
private ReferenceType computeFirstCommonSuperclassOfReferenceTypes(ReferenceType a, ReferenceType b) throws ClassNotFoundException {
boolean aIsArrayType = (a instanceof ArrayType);
boolean bIsArrayType = (b instanceof ArrayType);
if (aIsArrayType && bIsArrayType) {
// Merging array types - kind of a pain.
ArrayType aArrType = (ArrayType) a;
ArrayType bArrType = (ArrayType) b;
if (aArrType.getDimensions() == bArrType.getDimensions()) {
return computeFirstCommonSuperclassOfSameDimensionArrays(aArrType, bArrType);
} else {
return computeFirstCommonSuperclassOfDifferentDimensionArrays(aArrType, bArrType);
}
}
if (aIsArrayType || bIsArrayType) {
// One of a and b is an array type, but not both.
// Common supertype is Object.
return ObjectType.OBJECT;
}
// Neither a nor b is an array type.
// Find first common supertypes of ObjectTypes.
return getFirstCommonSuperclass((ObjectType) a, (ObjectType) b);
}
/**
* Get first common supertype of arrays with the same number of dimensions.
*
* @param aArrType an ArrayType
* @param bArrType another ArrayType with the same number of dimensions
* @return first common supertype
* @throws ClassNotFoundException
*/
private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType)
throws ClassNotFoundException {
assert aArrType.getDimensions() == bArrType.getDimensions();
Type aBaseType = aArrType.getBasicType();
Type bBaseType = bArrType.getBasicType();
boolean aBaseIsObjectType = (aBaseType instanceof ObjectType);
boolean bBaseIsObjectType = (bBaseType instanceof ObjectType);
if (!aBaseIsObjectType || !bBaseIsObjectType) {
assert (aBaseType instanceof BasicType) || (bBaseType instanceof BasicType);
if (aArrType.getDimensions() > 1) {
// E.g.: first common supertype of int[][] and WHATEVER[][] is Object[]
return new ArrayType(Type.OBJECT, aArrType.getDimensions() - 1);
} else {
assert aArrType.getDimensions() == 1;
// E.g.: first common supertype type of int[] and WHATEVER[] is Object
return Type.OBJECT;
}
} else {
assert (aBaseType instanceof ObjectType);
assert (bBaseType instanceof ObjectType);
// Base types are both ObjectTypes, and number of dimensions is same.
// We just need to find the first common supertype of base types
// and return a new ArrayType using that base type.
ObjectType firstCommonBaseType = getFirstCommonSuperclass((ObjectType) aBaseType, (ObjectType) bBaseType);
return new ArrayType(firstCommonBaseType, aArrType.getDimensions());
}
}
/**
* Get the first common superclass of
* arrays with different numbers of dimensions.
*
* @param aArrType an ArrayType
* @param bArrType another ArrayType
* @return ReferenceType representing first common superclass
*/
private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) {
assert aArrType.getDimensions() != bArrType.getDimensions();
boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType);
boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType);
if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) {
int minDimensions, maxDimensions;
if (aArrType.getDimensions() < bArrType.getDimensions()) {
minDimensions = aArrType.getDimensions();
maxDimensions = bArrType.getDimensions();
} else {
minDimensions = bArrType.getDimensions();
maxDimensions = aArrType.getDimensions();
}
if (minDimensions == 1) {
// One of the types was something like int[].
// The only possible common supertype is Object.
return Type.OBJECT;
} else {
// Weird case: e.g.,
// - first common supertype of int[][] and char[][][] is Object[]
// because f.c.s. of int[] and char[][] is Object
// - first common supertype of int[][][] and char[][][][][] is Object[][]
// because f.c.s. of int[] and char[][][] is Object
return new ArrayType(Type.OBJECT, maxDimensions - minDimensions);
}
} else {
// Both a and b have base types which are ObjectTypes.
// Since the arrays have different numbers of dimensions, the
// f.c.s. will have Object as its base type.
// E.g., f.c.s. of Cat[] and Dog[][] is Object[]
return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions()));
}
}
/**
* Get the first common superclass of the given object types.
* Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the
* same type. Otherwise, we try to return as accurate a type as possible.
* This method is used as the meet operator in TypeDataflowAnalysis,
* and is intended to follow (more or less) the JVM bytecode verifier
* semantics.
*
* <p>This method should be used in preference to the getFirstCommonSuperclass()
* method in {@link ReferenceType}.</p>
*
* @param a an ObjectType
* @param b another ObjectType
* @return the first common superclass of <code>a</code> and <code>b</code>
* @throws ClassNotFoundException
*/
public ObjectType getFirstCommonSuperclass(ObjectType a, ObjectType b) throws ClassNotFoundException {
// Easy case
if (a.equals(b)) {
return a;
}
ObjectType firstCommonSupertype = (ObjectType) checkFirstCommonSuperclassQueryCache(a, b);
if (firstCommonSupertype == null) {
firstCommonSupertype = computeFirstCommonSuperclassOfObjectTypes(a, b);
firstCommonSuperclassQueryCache.put(a, b, firstCommonSupertype);
}
return firstCommonSupertype;
}
private ObjectType computeFirstCommonSuperclassOfObjectTypes(ObjectType a, ObjectType b) throws ClassNotFoundException {
ObjectType firstCommonSupertype;
ClassDescriptor aDesc = BCELUtil.getClassDescriptor(a);
ClassDescriptor bDesc = BCELUtil.getClassDescriptor(b);
ClassVertex aVertex = resolveClassVertex(aDesc);
ClassVertex bVertex = resolveClassVertex(bDesc);
ArrayList<ClassVertex> aSuperList = getAllSuperclassVertices(aVertex);
ArrayList<ClassVertex> bSuperList = getAllSuperclassVertices(bVertex);
// Work backwards until the lists diverge.
// The last element common to both lists is the first
// common superclass.
int aIndex = aSuperList.size() - 1;
int bIndex = bSuperList.size() - 1;
ClassVertex lastCommonInBackwardsSearch = null;
while (aIndex >= 0 && bIndex >= 0) {
if (aSuperList.get(aIndex) != bSuperList.get(bIndex)) {
break;
}
lastCommonInBackwardsSearch = aSuperList.get(aIndex);
aIndex
bIndex
}
if (lastCommonInBackwardsSearch == null) {
return ObjectType.OBJECT;
}
firstCommonSupertype = ObjectTypeFactory.getInstance(lastCommonInBackwardsSearch.getClassDescriptor().toDottedClassName());
return firstCommonSupertype;
}
private void putFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b, ReferenceType answer) {
if (a.getSignature().compareTo(b.getSignature()) > 0) {
ReferenceType tmp = a;
a = b;
b = tmp;
}
firstCommonSuperclassQueryCache.put(a, b, answer);
}
private ReferenceType checkFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b) {
if (a.getSignature().compareTo(b.getSignature()) > 0) {
ReferenceType tmp = a;
a = b;
b = tmp;
}
return firstCommonSuperclassQueryCache.get(a, b);
}
/**
* Get list of all superclasses of class represented by given class vertex,
* in order, including the class itself (which is trivially its own superclass
* as far as "first common superclass" queries are concerned.)
*
* @param vertex a ClassVertex
* @return list of all superclass vertices in order
*/
private ArrayList<ClassVertex> getAllSuperclassVertices(ClassVertex vertex) throws ClassNotFoundException {
ArrayList<ClassVertex> result = new ArrayList<ClassVertex>();
ClassVertex cur = vertex;
while (cur != null) {
if (!cur.isResolved()) {
BCELUtil.throwClassNotFoundException(cur.getClassDescriptor());
}
result.add(cur);
cur = cur.getDirectSuperclass();
}
return result;
}
/**
* Get known subtypes of given class.
*
* @param classDescriptor ClassDescriptor naming a class
* @return Set of ClassDescriptors which are the known subtypes of the class
* @throws ClassNotFoundException
*/
public Set<ClassDescriptor> getSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException {
Set<ClassDescriptor> result = subtypeSetMap.get(classDescriptor);
if (result == null) {
result = computeKnownSubtypes(classDescriptor);
subtypeSetMap.put(classDescriptor, result);
}
return result;
}
/**
* Get Collection of all XClass objects (resolved classes)
* seen so far.
*
* @return Collection of all XClass objects
*/
public Collection<XClass> getXClassCollection() {
return Collections.unmodifiableCollection(xclassSet);
}
/**
* Starting at the class named by the given ClassDescriptor,
* traverse the inheritance graph, exploring the entire fan-out
* of all supertypes (both class and interface).
*
* @param start ClassDescriptor naming the class where the traversal should start
* @param visitor an InheritanceGraphVisitor
* @throws ClassNotFoundException
*/
public void traverseSupertypes(ClassDescriptor start, InheritanceGraphVisitor visitor) throws ClassNotFoundException {
ClassVertex startVertex = resolveClassVertex(start);
LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>();
workList.addLast(startVertex);
Set<ClassDescriptor> seen = new HashSet<ClassDescriptor>();
seen.add(startVertex.getClassDescriptor());
while (!workList.isEmpty()) {
ClassVertex vertex = workList.removeFirst();
if (!visitor.visitClass(vertex.getClassDescriptor(), vertex.getXClass())) {
continue;
}
if (!vertex.isResolved()) {
continue;
}
ClassDescriptor superclassDescriptor = vertex.getXClass().getSuperclassDescriptor();
if (!vertex.isInterface() && visitEdge(vertex, superclassDescriptor, false, visitor)) {
assert !seen.contains(superclassDescriptor) : " Already seen " + superclassDescriptor;
addToWorkList(workList, superclassDescriptor);
seen.add(superclassDescriptor);
}
for (ClassDescriptor ifaceDesc : vertex.getXClass().getInterfaceDescriptorList()) {
if (visitEdge(vertex, ifaceDesc, true, visitor)
&& !seen.contains(ifaceDesc)) {
addToWorkList(workList, ifaceDesc);
seen.add(ifaceDesc);
}
}
}
}
private void addToWorkList(LinkedList<ClassVertex> workList, ClassDescriptor supertypeDescriptor) {
ClassVertex next = classDescriptorToVertexMap.get(supertypeDescriptor);
assert next != null;
workList.addLast(next);
}
private boolean visitEdge(
ClassVertex vertex,
@CheckForNull ClassDescriptor supertypeDescriptor,
boolean isInterfaceEdge,
InheritanceGraphVisitor visitor) {
if (supertypeDescriptor == null) {
// We reached java.lang.Object
return false;
}
ClassVertex supertypeVertex;
try {
supertypeVertex = resolveClassVertex(supertypeDescriptor);
} catch (ClassNotFoundException e) {
supertypeVertex = addClassVertexForMissingClass(supertypeDescriptor, isInterfaceEdge);
}
return visitor.visitEdge(vertex.getClassDescriptor(), vertex.getXClass(), supertypeDescriptor, supertypeVertex.getXClass());
}
/**
* Compute set of known subtypes of class named by given ClassDescriptor.
*
* @param classDescriptor a ClassDescriptor
* @throws ClassNotFoundException
*/
private Set<ClassDescriptor> computeKnownSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException {
LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>();
ClassVertex startVertex = resolveClassVertex(classDescriptor);
workList.addLast(startVertex);
Set<ClassDescriptor> result = new HashSet<ClassDescriptor>();
while (!workList.isEmpty()) {
ClassVertex current = workList.removeFirst();
if (result.contains(current.getClassDescriptor())) {
// Already added this class
continue;
}
// Add class to the result
result.add(current.getClassDescriptor());
// Add all known subtype vertices to the work list
Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(current);
while (i.hasNext()) {
InheritanceEdge edge = i.next();
workList.addLast(edge.getSource());
}
}
return result;
}
/**
* Look up or compute the SupertypeQueryResults for class
* named by given ClassDescriptor.
*
* @param classDescriptor a ClassDescriptor
* @return SupertypeQueryResults for the class named by the ClassDescriptor
* @throws ClassNotFoundException
*/
private SupertypeQueryResults getSupertypeQueryResults(ClassDescriptor classDescriptor) throws ClassNotFoundException {
SupertypeQueryResults supertypeQueryResults = supertypeSetMap.get(classDescriptor);
if (supertypeQueryResults == null) {
supertypeQueryResults = computeSupertypes(classDescriptor);
supertypeSetMap.put(classDescriptor, supertypeQueryResults);
}
return supertypeQueryResults;
}
/**
* Compute supertypes for class named by given ClassDescriptor.
*
* @param classDescriptor a ClassDescriptor
* @return SupertypeQueryResults containing known supertypes of the class
* @throws ClassNotFoundException if the class can't be found
*/
private SupertypeQueryResults computeSupertypes(ClassDescriptor classDescriptor) throws ClassNotFoundException {
if (DEBUG_QUERIES) {
System.out.println("Computing supertypes for " + classDescriptor.toDottedClassName());
}
// Try to fully resolve the class and its superclasses/superinterfaces.
ClassVertex typeVertex = resolveClassVertex(classDescriptor);
// Create new empty SupertypeQueryResults.
SupertypeQueryResults supertypeSet = new SupertypeQueryResults();
// Add all known superclasses/superinterfaces.
// The ClassVertexes for all of them should be in the
// InheritanceGraph by now.
LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>();
workList.addLast(typeVertex);
while (!workList.isEmpty()) {
ClassVertex vertex = workList.removeFirst();
if (vertex.isResolved()) {
if (DEBUG_QUERIES) {
System.out.println(" Adding supertype " + vertex.getClassDescriptor().toDottedClassName());
}
supertypeSet.addSupertype(vertex.getClassDescriptor());
} else {
if (DEBUG_QUERIES) {
System.out.println(
" Encountered unresolved class " +
vertex.getClassDescriptor().toDottedClassName() +
" in supertype query");
}
supertypeSet.setEncounteredMissingClasses(true);
}
Iterator<InheritanceEdge> i = graph.outgoingEdgeIterator(vertex);
while (i.hasNext()) {
InheritanceEdge edge = i.next();
workList.addLast(edge.getTarget());
}
}
return supertypeSet;
}
/**
* Resolve a class named by given ClassDescriptor and return
* its resolved ClassVertex.
*
* @param classDescriptor a ClassDescriptor
* @return resolved ClassVertex representing the class in the InheritanceGraph
* @throws ClassNotFoundException if the class named by the ClassDescriptor does not exist
*/
private ClassVertex resolveClassVertex(ClassDescriptor classDescriptor) throws ClassNotFoundException {
ClassVertex typeVertex = classDescriptorToVertexMap.get(classDescriptor);
if (typeVertex == null) {
// We have never tried to resolve this ClassVertex before.
// Try to find the XClass for this class.
XClass xclass = AnalysisContext.currentXFactory().getXClass(classDescriptor);
if (xclass == null) {
// Class we're trying to resolve doesn't exist.
// XXX: unfortunately, we don't know if the missing class is a class or interface
typeVertex = addClassVertexForMissingClass(classDescriptor, false);
} else {
// Add the class and all its superclasses/superinterfaces to the inheritance graph.
// This will result in a resolved ClassVertex.
typeVertex = addClassAndGetClassVertex(xclass);
}
}
if (!typeVertex.isResolved()) {
BCELUtil.throwClassNotFoundException(classDescriptor);
}
assert typeVertex.isResolved();
return typeVertex;
}
/**
* Add supertype edges to the InheritanceGraph
* for given ClassVertex. If any direct supertypes
* have not been processed, add them to the worklist.
*
* @param vertex a ClassVertex whose supertype edges need to be added
* @param workList work list of ClassVertexes that need to have
* their supertype edges added
*/
private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) {
XClass xclass = vertex.getXClass();
// Direct superclass
addInheritanceEdge(vertex, xclass.getSuperclassDescriptor(), false, workList);
// Directly implemented interfaces
for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) {
addInheritanceEdge(vertex, ifaceDesc, true, workList);
}
}
/**
* Add supertype edge to the InheritanceGraph.
*
* @param vertex source ClassVertex (subtype)
* @param superclassDescriptor ClassDescriptor of a direct supertype
* @param isInterfaceEdge true if supertype is (as far as we know) an interface
* @param workList work list of ClassVertexes that need to have
* their supertype edges added (null if no further work will be generated)
*/
private void addInheritanceEdge(
ClassVertex vertex,
ClassDescriptor superclassDescriptor,
boolean isInterfaceEdge,
@CheckForNull LinkedList<XClass> workList) {
if (superclassDescriptor == null) {
return;
}
ClassVertex superclassVertex = classDescriptorToVertexMap.get(superclassDescriptor);
if (superclassVertex == null) {
// Haven't encountered this class previously.
XClass superclassXClass = AnalysisContext.currentXFactory().getXClass(superclassDescriptor);
if (superclassXClass == null) {
// Inheritance graph will be incomplete.
// Add a dummy node to inheritance graph and report missing class.
superclassVertex = addClassVertexForMissingClass(superclassDescriptor, isInterfaceEdge);
} else {
// Haven't seen this class before.
superclassVertex = ClassVertex.createResolvedClassVertex(superclassDescriptor, superclassXClass);
addVertexToGraph(superclassDescriptor, superclassVertex);
if (workList != null) {
// We'll want to recursively process the superclass.
workList.addLast(superclassXClass);
}
}
}
assert superclassVertex != null;
if (graph.lookupEdge(vertex, superclassVertex) == null) {
if (DEBUG) {
System.out.println(" Add edge " + vertex.getClassDescriptor().toDottedClassName() + " -> " + superclassDescriptor.toDottedClassName());
}
graph.createEdge(vertex, superclassVertex);
}
}
/**
* Add a ClassVertex representing a missing class.
*
* @param missingClassDescriptor ClassDescriptor naming a missing class
* @param isInterfaceEdge
* @return the ClassVertex representing the missing class
*/
private ClassVertex addClassVertexForMissingClass(ClassDescriptor missingClassDescriptor, boolean isInterfaceEdge) {
ClassVertex missingClassVertex = ClassVertex.createMissingClassVertex(missingClassDescriptor, isInterfaceEdge);
missingClassVertex.setFinished(true);
addVertexToGraph(missingClassDescriptor, missingClassVertex);
AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(missingClassDescriptor);
return missingClassVertex;
}
}
|
package org.destinationsol.desktop;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import org.destinationsol.GameOptions;
import org.destinationsol.SolApplication;
import org.destinationsol.SolFileReader;
import org.destinationsol.game.DebugOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.crashreporter.CrashReporter;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class SolDesktop {
private static Logger logger = LoggerFactory.getLogger(SolDesktop.class);
private static final String NO_CRASH_REPORT = "-noCrashReport";
public static void main(String[] argv) {
List<String> commandLineArgs = Arrays.asList(argv);
LwjglApplicationConfiguration applicationConfig = new LwjglApplicationConfiguration();
boolean devBuild = java.nio.file.Files.exists(Paths.get("devBuild"));
if (devBuild) {
DebugOptions.DEV_ROOT_PATH = "main" + File.separator; // Lets the game run from source without a tweaked working directory
applicationConfig.vSyncEnabled = false; //Setting to false disables vertical sync
applicationConfig.foregroundFPS = 0; //disables foreground fps throttling
applicationConfig.backgroundFPS = 0; //disables background fps throttling
}
MyReader reader = new MyReader();
DebugOptions.read(reader);
if (DebugOptions.EMULATE_MOBILE) {
applicationConfig.width = 640;
applicationConfig.height = 480;
applicationConfig.fullscreen = false;
} else {
GameOptions d = new GameOptions(false, reader);
applicationConfig.width = d.x;
applicationConfig.height = d.y;
applicationConfig.fullscreen = d.fullscreen;
}
applicationConfig.title = "Destination Sol";
if (DebugOptions.DEV_ROOT_PATH == null) {
applicationConfig.addIcon("res/icon.png", Files.FileType.Internal);
} else {
applicationConfig.addIcon(DebugOptions.DEV_ROOT_PATH + "res/icon.png", Files.FileType.Absolute);
}
if (!commandLineArgs.contains(NO_CRASH_REPORT)) {
Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> {
// Get the exception stack trace string
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
ex.printStackTrace(printWriter);
String exceptionString = stringWriter.getBuffer().toString();
logger.error("This exception was not caught:", ex);
// Create a crash dump file
String fileName = "crash-" + new SimpleDateFormat("yyyy-dd-MM_HH-mm-ss").format(new Date()) + ".log";
List<String> lines = Collections.singletonList(exceptionString);
Path logPath = new MyReader().create(fileName, lines).toAbsolutePath().getParent();
// Run asynchronously so that the error message view is not blocked
new Thread(() -> CrashReporter.report(ex, logPath)).start();
});
}
new LwjglApplication(new SolApplication(), applicationConfig);
}
private static class MyReader implements SolFileReader {
@Override
public Path create(String fileName, List<String> lines) {
if (DebugOptions.DEV_ROOT_PATH != null) {
fileName = DebugOptions.DEV_ROOT_PATH + fileName;
}
Path file = Paths.get(fileName);
try {
java.nio.file.Files.write(file, lines, Charset.forName("UTF-8"));
} catch (IOException e) {
logger.error("Failed to write to file",e);
}
return file;
}
@Override
public List<String> read(String fileName) {
if (DebugOptions.DEV_ROOT_PATH != null) {
fileName = DebugOptions.DEV_ROOT_PATH + fileName;
}
ArrayList<String> lines = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
br.close();
} catch (IOException ignore) { }
return lines;
}
}
}
|
package com.codeaffine.util;
class Messages {
static final String ERROR_WRONG_NUMBER_OF_CASE_OPS = "Wrong number of case operations";
}
|
package edu.umd.cs.findbugs.workflow;
import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import org.dom4j.DocumentException;
import edu.umd.cs.findbugs.AppVersion;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.ClassAnnotation;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SloppyBugComparator;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.VersionInsensitiveBugComparator;
import edu.umd.cs.findbugs.config.CommandLine;
/**
* Java main application to compute update a historical bug collection with
* results from another build/analysis.
*
* @author William Pugh
*/
public class Update {
private static final String USAGE = "Usage: " + Update.class.getName()
+ " [options] <historyData> <newData> [<mergedData>] or "
+ Update.class.getName()
+ " [options] -output filename data1File data2File data3File ... ";
private static HashMap<BugInstance, BugInstance> mapFromNewToOldBug = new HashMap<BugInstance, BugInstance>();
private static HashSet<BugInstance> matchedOldBugs = new HashSet<BugInstance>();
static class UpdateCommandLine extends CommandLine {
String revisionName;
long revisionTimestamp = 0L;
UpdateCommandLine() {
addOption("-name", "name", "provide name for new results");
addOption("-output", "output file",
"explicit filename for merged results");
addOption("-timestamp", "when", "timestamp for new results");
}
@Override
protected void handleOption(String option, String optionExtraPart)
throws IOException {
throw new IllegalArgumentException("no option " + option);
}
@Override
protected void handleOptionWithArgument(String option, String argument)
throws IOException {
if (option.equals("-name"))
revisionName = argument;
else if (option.equals("-output"))
outputFilename = argument;
else if (option.equals("-timestamp"))
revisionTimestamp = Date.parse(argument);
else
throw new IllegalArgumentException("Can't handle option "
+ option);
}
}
public static BugCollection mergeCollections(BugCollection origCollection,
BugCollection newCollection) {
BugCollection resultCollection = newCollection
.createEmptyCollectionWithMetadata();
// Previous sequence number
long lastSequence = origCollection.getSequenceNumber();
// The AppVersion history is retained from the orig collection,
// adding an entry for the sequence/timestamp of the current state
// of the orig collection.
resultCollection.clearAppVersions();
for (Iterator<AppVersion> i = origCollection.appVersionIterator(); i
.hasNext();) {
AppVersion appVersion = i.next();
resultCollection.addAppVersion((AppVersion) appVersion.clone());
}
AppVersion origCollectionVersion = new AppVersion(lastSequence);
origCollectionVersion.setTimestamp(origCollection
.getCurrentAppVersion().getSequenceNumber());
origCollectionVersion.setReleaseName(origCollection
.getCurrentAppVersion().getReleaseName());
resultCollection.addAppVersion(origCollectionVersion);
// We assign a sequence number to the new collection as one greater than
// the
// original collection.
long currentSequence = origCollection.getSequenceNumber() + 1;
resultCollection.setSequenceNumber(currentSequence);
matchBugs(new SortedBugCollection.BugInstanceComparator(),
origCollection, newCollection);
matchBugs(VersionInsensitiveBugComparator.instance(), origCollection,
newCollection);
matchBugs(new SloppyBugComparator(), origCollection, newCollection);
int oldBugs = 0;
int newlyDeadBugs = 0;
int persistantBugs = 0;
int addedBugs = 0;
int addedInNewCode = 0;
int deadBugInDeadCode = 0;
// Copy unmatched bugs
for (BugInstance bug : origCollection.getCollection())
if (!matchedOldBugs.contains(bug)) {
if (bug.getLastVersion() == -1)
newlyDeadBugs++;
else
oldBugs++;
BugInstance newBug = (BugInstance) bug.clone();
if (newBug.getLastVersion() == -1) {
newBug.setLastVersion(lastSequence);
ClassAnnotation classBugFoundIn = bug.getPrimaryClass();
String className = classBugFoundIn.getClassName();
if (newCollection.getProjectStats()
.getClassStats(className) != null)
newBug.setRemovedByChangeOfPersistingClass(true);
else
deadBugInDeadCode++;
}
if (newBug.getFirstVersion() > newBug.getLastVersion())
throw new IllegalStateException("Illegal Version range: "
+ newBug.getFirstVersion() + ".."
+ newBug.getLastVersion());
resultCollection.add(newBug, false);
}
// Copy matched bugs
for (BugInstance bug : newCollection.getCollection()) {
BugInstance newBug = (BugInstance) bug.clone();
if (mapFromNewToOldBug.containsKey(bug)) {
BugInstance origWarning = mapFromNewToOldBug.get(bug);
assert origWarning.getLastVersion() == -1;
newBug.setUniqueId(origWarning.getUniqueId());
copyBugHistory(origWarning, newBug);
String annotation = newBug.getAnnotationText();
if (annotation.length() == 0)
newBug.setAnnotationText(origWarning.getAnnotationText());
persistantBugs++;
} else {
newBug.setFirstVersion(lastSequence + 1);
addedBugs++;
ClassAnnotation classBugFoundIn = bug.getPrimaryClass();
String className = classBugFoundIn.getClassName();
if (origCollection.getProjectStats().getClassStats(className) != null) {
newBug.setIntroducedByChangeOfExistingClass(true);
// System.out.println("added bug to existing code " +
// newBug.getUniqueId() + " : " + newBug.getAbbrev() + " in
// " + classBugFoundIn);
} else
addedInNewCode++;
}
assert newBug.getLastVersion() == -1;
if (newBug.getLastVersion() != -1)
throw new IllegalStateException("Illegal Version range: "
+ newBug.getFirstVersion() + ".."
+ newBug.getLastVersion());
int oldSize = resultCollection.getCollection().size();
resultCollection.add(newBug, false);
int newSize = resultCollection.getCollection().size();
if (newSize != oldSize + 1) {
System.out.println("Failed to add bug #" + newBug.getUniqueId()
+ " : " + newBug.getMessage());
}
}
if (verbose) {
System.out.println(origCollection.getCollection().size()
+ " orig bugs, " + newCollection.getCollection().size()
+ " new bugs");
System.out.println("Bugs: " + oldBugs + " old, "
+ deadBugInDeadCode + " in removed code, "
+ (newlyDeadBugs - deadBugInDeadCode) + " died, "
+ persistantBugs + " persist, " + addedInNewCode
+ " in new code, " + (addedBugs - addedInNewCode)
+ " added");
}
return resultCollection;
}
public static boolean verbose = false;
public static String outputFilename;
public static void main(String[] args) throws IOException,
DocumentException {
DetectorFactoryCollection.instance();
UpdateCommandLine commandLine = new UpdateCommandLine();
int argCount = commandLine.parse(args, 2, Integer.MAX_VALUE, USAGE);
int lastInputfile = args.length - 1;
if (outputFilename == null && args.length - argCount == 3) {
outputFilename = args[args.length - 1];
lastInputfile
}
verbose = outputFilename != null;
String origFileName = args[argCount++];
BugCollection origCollection;
origCollection = new SortedBugCollection(
SortedBugCollection.MultiversionBugInstanceComparator.instance);
BugCollection oCollection = origCollection;
origCollection.readXML(origFileName, new Project());
for (BugInstance bug : origCollection.getCollection())
if (bug.getLastVersion() >= 0
&& bug.getFirstVersion() > bug.getLastVersion())
throw new IllegalStateException("Illegal Version range: "
+ bug.getFirstVersion() + ".." + bug.getLastVersion());
Project currentProject = new Project();
while (argCount <= lastInputfile) {
BugCollection newCollection = new SortedBugCollection(
SortedBugCollection.MultiversionBugInstanceComparator.instance);
BugCollection nCollection = newCollection;
String newFilename = args[argCount++];
if (verbose)
System.out.println("Merging " + newFilename);
newCollection.readXML(newFilename, currentProject);
if (commandLine.revisionName != null)
newCollection.setReleaseName(commandLine.revisionName);
if (commandLine.revisionTimestamp != 0)
newCollection.setTimestamp(commandLine.revisionTimestamp);
origCollection = mergeCollections(origCollection, newCollection);
}
if (verbose) {
origCollection.writeXML(args[argCount++], currentProject);
} else
origCollection.writeXML(System.out, currentProject);
}
private static void copyBugHistory(BugInstance src, BugInstance dest) {
dest.setFirstVersion(src.getFirstVersion());
dest.setLastVersion(src.getLastVersion());
dest.setIntroducedByChangeOfExistingClass(src
.isIntroducedByChangeOfExistingClass());
dest.setRemovedByChangeOfPersistingClass(src
.isRemovedByChangeOfPersistingClass());
}
private static void matchBugs(
Comparator<BugInstance> bugInstanceComparator,
BugCollection origCollection, BugCollection newCollection) {
TreeMap<BugInstance, LinkedList<BugInstance>> set = new TreeMap<BugInstance, LinkedList<BugInstance>>(
bugInstanceComparator);
int oldBugs = 0;
int newBugs = 0;
int matchedBugs = 0;
for (BugInstance bug : origCollection.getCollection())
if (bug.getLastVersion() == -1 && !matchedOldBugs.contains(bug)) {
oldBugs++;
LinkedList<BugInstance> q = set.get(bug);
if (q == null) {
q = new LinkedList<BugInstance>();
set.put(bug, q);
}
q.offer(bug);
}
for (BugInstance bug : newCollection.getCollection()) if (!mapFromNewToOldBug.containsKey(bug)) {
newBugs++;
LinkedList<BugInstance> q = set.get(bug);
if (q != null && !q.isEmpty()) {
matchedBugs++;
BugInstance matchedBug = q.remove();
mapFromNewToOldBug.put(bug, matchedBug);
matchedOldBugs.add(matchedBug);
}
}
if (verbose) System.out.println("matched " + matchedBugs + " of " + oldBugs +"o/" + newBugs + "n bugs using " + bugInstanceComparator.getClass().getName());
}
}
|
package net.cazzar.mods.jukeboxreloaded.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.cazzar.corelib.client.gui.TexturedButton;
import net.cazzar.corelib.lib.SoundSystemHelper;
import net.cazzar.corelib.util.ClientUtil;
import net.cazzar.mods.jukeboxreloaded.blocks.TileJukebox;
import net.cazzar.mods.jukeboxreloaded.lib.RepeatMode;
import net.cazzar.mods.jukeboxreloaded.lib.Strings;
import net.cazzar.mods.jukeboxreloaded.network.packets.PacketJukeboxDescription;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import org.lwjgl.opengl.GL11;
import java.util.List;
import java.util.Random;
import static java.lang.Math.floor;
import static net.cazzar.mods.jukeboxreloaded.lib.Reference.JUKEBOX_GUI_TEXTURE;
import static net.cazzar.mods.jukeboxreloaded.lib.Reference.JukeboxGUIActions.*;
@SideOnly(Side.CLIENT)
public class GUIJukebox extends GuiContainer {
TileJukebox tileJukebox;
private TexturedButton btnPlay, btnStop, btnShuffleOn, btnShuffleOff, btnRepeatAll, btnRepeatOne, btnRepeatOff, btnNext, btnPrev;
private GuiButton volUp, volDown;
public GUIJukebox(EntityPlayer player, TileJukebox tileJukebox) {
super(new ContainerJukebox(player.inventory, tileJukebox));
this.tileJukebox = tileJukebox;
xSize = 176;
ySize = 176;
}
@Override
protected void actionPerformed(GuiButton btn) {
final boolean wasPlaying = tileJukebox.isPlayingRecord();
switch (btn.id) {
case PLAY:
tileJukebox.playSelectedRecord();
break;
case STOP:
tileJukebox.stopPlayingRecord();
break;
case NEXT:
if (wasPlaying) tileJukebox.stopPlayingRecord();
if (tileJukebox.shuffleEnabled()) {
final Random random = new Random();
if (tileJukebox.getLastSlotWithItem() <= 0) return;
final int nextDisk = random.nextInt(tileJukebox.getLastSlotWithItem());
if (tileJukebox.getCurrentRecordNumber() != nextDisk)
tileJukebox.setRecordPlaying(nextDisk);
}
tileJukebox.nextRecord();
if (wasPlaying) tileJukebox.playSelectedRecord();
break;
case PREVIOUS:
if (wasPlaying) tileJukebox.stopPlayingRecord();
tileJukebox.previousRecord();
if (wasPlaying) tileJukebox.playSelectedRecord();
break;
case REPEAT_ALL:
tileJukebox.setRepeatMode(RepeatMode.ALL);
break;
case REPEAT_ONE:
tileJukebox.setRepeatMode(RepeatMode.ONE);
break;
case REPEAT_OFF:
tileJukebox.setRepeatMode(RepeatMode.OFF);
break;
case SHUFFLE:
tileJukebox.setShuffle(true);
break;
case SHUFFLE_OFF:
tileJukebox.setShuffle(false);
break;
case VOLUME_UP:
if (tileJukebox.volume >= 1F) {
tileJukebox.volume = 1F;
break;
}
SoundSystemHelper.getSoundSystem().setVolume(tileJukebox.getIdentifier(), tileJukebox.volume * ClientUtil.mc().gameSettings.soundVolume);
tileJukebox.volume += 0.05F;
break;
case VOLUME_DOWN:
if (tileJukebox.volume <= 0F) {
tileJukebox.volume = 0F;
break;
}
SoundSystemHelper.getSoundSystem().setVolume(tileJukebox.getIdentifier(), tileJukebox.volume * ClientUtil.mc().gameSettings.soundVolume);
tileJukebox.volume -= 0.05F;
break;
}
updateButtonStates();
new PacketJukeboxDescription(tileJukebox).sendToServer();
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) {
updateButtonStates();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.func_110577_a(JUKEBOX_GUI_TEXTURE);
final int xStart = (width - xSize) / 2;
final int yStart = (height - ySize) / 2;
drawTexturedModalRect(xStart, yStart, 0, 0, xSize, ySize);
}
@SuppressWarnings("unchecked")
@Override
protected void drawGuiContainerForegroundLayer(int x, int y) {
final String containerName = Strings.GUI_JUKEBOX_NAME.toString();
fontRenderer.drawString(containerName,
xSize / 2 - fontRenderer.getStringWidth(containerName) / 2, 6,
4210752);
fontRenderer.drawString(
Strings.GUI_INVENTORY.toString(), 8,
ySize - 93, 4210752);
String str = (tileJukebox.volume == 1.0F) ? "10" : String.format("%.1f", tileJukebox.volume * 10);
fontRenderer.drawString(str, 21, 68, 4210752);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.func_110577_a(JUKEBOX_GUI_TEXTURE);
final int xOffset = 53;
final int yOffset = 16;
final int size = 18;
final int index = tileJukebox.getCurrentRecordNumber();
final int column = (int) floor(index / 4D);
final int row = index % 4;
drawTexturedModalRect(xOffset + size * row, yOffset + size * column, 176, 0, 18, 18);
final int xStart = (width - xSize) / 2;
final int yStart = (height - ySize) / 2;
for (GuiButton button : (List<GuiButton>) buttonList) {
if (!(button instanceof TexturedButton))
return;
TexturedButton btn = (TexturedButton) button;
if ((x >= btn.xPosition && x <= btn.xPosition + btn.getHeight()) && (y >= btn.yPosition && y <= btn.yPosition + btn.getWidth()))
if (!btn.getTooltip().trim().isEmpty() && btn.enabled)
btn.drawToolTip(x - xStart, y - yStart);
}
}
@SuppressWarnings("unchecked")
@Override
public void initGui() {
super.initGui();
initButtons();
initTooltips();
}
private void initTooltips() {
btnPlay.setTooltip(Strings.TOOLTIP_PLAY.toString());
btnStop.setTooltip(Strings.TOOLTIP_STOP.toString());
btnNext.setTooltip(Strings.TOOLTIP_NEXT.toString());
btnPrev.setTooltip(Strings.TOOLTIP_PREV.toString());
btnRepeatAll.setTooltip(Strings.TOOLTIP_REPEAT_ALL.toString());
btnRepeatOff.setTooltip(Strings.TOOLTIP_REPEAT_NONE.toString());
btnRepeatOne.setTooltip(Strings.TOOLTIP_REPEAT_ONE.toString());
btnShuffleOn.setTooltip(Strings.TOOLTIP_SHUFFLE_ON.toString());
btnShuffleOff.setTooltip(Strings.TOOLTIP_SHUFFLE_OFF.toString());
}
@SuppressWarnings("unchecked")
private void initButtons() {
final int xStart = (width - xSize) / 2;
final int yStart = (height - ySize) / 2;
buttonList.add(btnPlay = new TexturedButton(this, PLAY, xStart + 7, yStart + 17, 20, 20, JUKEBOX_GUI_TEXTURE, 176, 38, 176, 18, 176, 58));
buttonList.add(btnStop = new TexturedButton(this, STOP, xStart + 29, yStart + 17, 20, 20, JUKEBOX_GUI_TEXTURE, 176, 98, 176, 78, 176, 118));
buttonList.add(btnNext = new TexturedButton(this, NEXT, xStart + 29, yStart + 39, 20, 20, JUKEBOX_GUI_TEXTURE, 216, 38, 216, 18, 216, 58));
buttonList.add(btnPrev = new TexturedButton(this, PREVIOUS, xStart + 7, yStart + 39, 20, 20, JUKEBOX_GUI_TEXTURE, 236, 38, 236, 18, 236, 58));
buttonList.add(btnRepeatOne = new TexturedButton(this, REPEAT_ONE, xStart + 150, yStart + 17, 20, 20, JUKEBOX_GUI_TEXTURE, 196, 98, 196, 78, 196, 118));
buttonList.add(btnRepeatAll = new TexturedButton(this, REPEAT_ALL, xStart + 150, yStart + 40, 20, 20, JUKEBOX_GUI_TEXTURE, 216, 98, 216, 78, 216, 118));
buttonList.add(btnRepeatOff = new TexturedButton(this, REPEAT_OFF, xStart + 150, yStart + 63, 20, 20, JUKEBOX_GUI_TEXTURE, 196, 158, 196, 138, 196, 178));
buttonList.add(btnShuffleOn = new TexturedButton(this, SHUFFLE, xStart + 128, yStart + 17, 20, 20, JUKEBOX_GUI_TEXTURE, 236, 98, 236, 78, 236, 118));
buttonList.add(btnShuffleOff = new TexturedButton(this, SHUFFLE_OFF, xStart + 128, yStart + 40, 20, 20, JUKEBOX_GUI_TEXTURE, 176, 158, 176, 138, 176, 178));
buttonList.add(volDown = new GuiButton(VOLUME_DOWN, xStart + 7, yStart + 61, 12, 20, "-"));
buttonList.add(volUp = new GuiButton(VOLUME_UP, xStart + 37, yStart + 61, 12, 20, "+"));
}
public void updateButtonStates() {
if (tileJukebox.volume <= 0F) {
tileJukebox.volume = 0F;
((GuiButton)volDown).enabled = false;
((GuiButton)volUp).enabled = true;
} else if (tileJukebox.volume >= 1F) {
tileJukebox.volume = 1F;
((GuiButton)volUp).enabled = false;
((GuiButton)volDown).enabled = true;
} else {
((GuiButton)volUp).enabled = true;
((GuiButton)volDown).enabled = true;
}
((GuiButton)btnPlay).enabled = !(btnStop.enabled = tileJukebox.isPlayingRecord());
((GuiButton)btnShuffleOn).enabled = !tileJukebox.shuffleEnabled();
((GuiButton)btnShuffleOff).enabled = tileJukebox.shuffleEnabled();
switch (tileJukebox.getReplayMode()) {
case OFF:
((GuiButton)btnRepeatAll).enabled = true;
((GuiButton)btnRepeatOne).enabled = true;
((GuiButton)btnRepeatOff).enabled = false;
break;
case ONE:
((GuiButton)btnRepeatAll).enabled = true;
((GuiButton)btnRepeatOne).enabled = false;
((GuiButton)btnRepeatOff).enabled = true;
break;
case ALL:
((GuiButton)btnRepeatAll).enabled = false;
((GuiButton)btnRepeatOne).enabled = true;
((GuiButton)btnRepeatOff).enabled = true;
}
}
}
|
package com.serenegiant.view;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import com.serenegiant.common.R;
import com.serenegiant.view.animation.ResizeAnimation;
import java.util.Locale;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
/**
* SnackbarView
* XXX ConstraintLayout
* (ConstraintLayoutView)
*/
public class ViewSlider {
private static final boolean DEBUG = true; // set false on production
private static final String TAG = ViewSlider.class.getSimpleName();
private static final int DURATION_RESIZE_MS = 300;
/**
* View
*/
@NonNull
private final View mParent;
/**
* View
*/
@NonNull
private final View mTarget;
private int mTargetWidth;
private int mTargetHeight;
public ViewSlider(@NonNull final View parent, @IdRes final int viewId)
throws IllegalArgumentException{
mParent = parent;
mTarget = parent.findViewById(viewId);
if (mTarget == null) {
throw new IllegalArgumentException("Target view not found");
}
mTargetWidth = mTarget.getWidth();
mTargetHeight = mTarget.getHeight();
if (DEBUG) Log.v(TAG, String.format(":size(%dx%d)", mTargetWidth, mTargetHeight));
mParent.addOnLayoutChangeListener(mOnLayoutChangeListener);
mTarget.addOnLayoutChangeListener(mOnLayoutChangeListener);
if (mTarget.getVisibility() == View.GONE) {
mTarget.setVisibility(View.INVISIBLE);
}
}
@Override
protected void finalize() throws Throwable {
try {
release();
} finally {
super.finalize();
}
}
public void release() {
mTarget.clearAnimation();
mTarget.removeOnLayoutChangeListener(mOnLayoutChangeListener);
}
/**
* View
* @return
*/
@NonNull
public View getTargetView() {
return mTarget;
}
/**
* View
* @param autoHideDurationMs
*/
public void show(final long autoHideDurationMs) {
mParent.post(new Runnable() {
@Override
public void run() {
if (DEBUG) Log.i(TAG, String.format(Locale.US,
"show:size(%d,%d)",
mTarget.getWidth(), mTarget.getHeight()));
mTarget.clearAnimation();
final ResizeAnimation expandAnimation
= new ResizeAnimation(mTarget,
mTargetWidth, 0,
mTargetWidth, mTargetHeight);
expandAnimation.setDuration(DURATION_RESIZE_MS);
expandAnimation.setAnimationListener(mAnimationListener);
mTarget.setTag(R.id.visibility, 1);
mTarget.setTag(R.id.auto_hide_duration, autoHideDurationMs);
mParent.postDelayed(new Runnable() {
@Override
public void run() {
mTarget.setVisibility(View.VISIBLE);
mTarget.startAnimation(expandAnimation);
}
}, 50);
}
});
}
/**
* View
* @param durationMs
*/
public void hide(final long durationMs) {
mParent.post(new Runnable() {
@Override
public void run() {
if (mTarget.getVisibility() == View.VISIBLE) {
if (DEBUG) Log.v(TAG,
String.format(Locale.US, "hide:size(%d,%d)",
mTarget.getWidth(), mTarget.getHeight()));
mTarget.clearAnimation();
if (durationMs > 0) {
final ResizeAnimation collapseAnimation
= new ResizeAnimation(mTarget,
mTargetWidth, mTarget.getHeight(),
mTargetWidth, 0);
collapseAnimation.setDuration(durationMs);
collapseAnimation.setAnimationListener(mAnimationListener);
mTarget.setTag(R.id.visibility, 0);
mTarget.startAnimation(collapseAnimation);
} else {
mTarget.setVisibility(View.INVISIBLE);
}
}
}
});
}
public void setTargetWidth(final int width) {
mTargetWidth = width;
}
public void setTargetHeight(final int height) {
mTargetHeight = height;
}
/**
* ViewgetVisibility
* View#VISIBLEView0
* #isVisible
* @return
*/
public int getVisibility() {
return mTarget.getVisibility();
}
/**
* View
* Visibility==VISIBLEView0true
* @return
*/
public boolean isVisible() {
return (mTarget.getVisibility() == View.VISIBLE)
&& (mTarget.getWidth() > 0) && (mTarget.getHeight() > 0);
}
private final View.OnLayoutChangeListener mOnLayoutChangeListener
= new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(final View v,
final int left, final int top, final int right, final int bottom,
final int oldLeft, final int oldTop, final int oldRight, final int oldBottom) {
if (DEBUG) Log.v(TAG, String.format(
"onLayoutChange:%s(%d,%d - %d,%d) → (%d,%d - %d,%d)",
v.getClass().getSimpleName(),
oldLeft, oldTop, oldRight, oldBottom,
left, top, right, bottom));
if (v == mTarget) {
if (mTargetWidth <= 0) {
mTargetWidth = v.getWidth();
}
if (mTargetHeight <= 0) {
mTargetHeight = v.getHeight();
}
}
}
};
private final Animation.AnimationListener mAnimationListener
= new Animation.AnimationListener() {
@Override
public void onAnimationStart(final Animation animation) {
if (DEBUG) Log.v(TAG, "onAnimationStart:");
}
@Override
public void onAnimationEnd(final Animation animation) {
if (DEBUG) Log.v(TAG, "onAnimationEnd:");
final Object visibility = mTarget.getTag(R.id.visibility);
if ((visibility instanceof Integer) && ((Integer)visibility == 1)) {
mTarget.setTag(R.id.visibility, 0);
final Object durationObj = mTarget.getTag(R.id.auto_hide_duration);
final long duration = (durationObj instanceof Long) ? (Long)durationObj : 0;
if (duration > 0) {
mTarget.postDelayed(new Runnable() {
@Override
public void run() {
hide(DURATION_RESIZE_MS);
}
}, duration);
}
} else {
mTarget.setVisibility(View.INVISIBLE);
}
}
@Override
public void onAnimationRepeat(final Animation animation) {
if (DEBUG) Log.v(TAG, "onAnimationRepeat:");
}
};
}
|
package com.gooddata.util;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
/**
* GoodData
*
* @author zd <zd@gooddata.com>
* @version 1.0
*/
public class TestStringUtil extends TestCase {
private static Logger l = Logger.getLogger(TestStringUtil.class);
public void testformatShortName() throws Exception {
BufferedReader in = FileUtil.createBufferedUtf8Reader(getClass().getResourceAsStream("/com/gooddata/util/test1.txt"));
assertEquals(StringUtil.toIdentifier(in.readLine()),"aiiarsiarsiaeaeieaeeareisariseaiarsreuireiurieufdnfmdfdnm323232322");
assertEquals(StringUtil.toIdentifier(in.readLine()),"siarsiaeaeieaedffg");
}
}
|
package sg.ncl.common.jwt;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Te Ye
* @version 1.0
*/
public class JwtFilterTest {
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
// private Key apiKey;
private JwtFilter jwtFilter;
@Mock
private AuthenticationManager authenticationManager;
@Before
public void before() {
// apiKey = new SecretKeySpec("123".getBytes(), SignatureAlgorithm.HS256.getJcaName());
jwtFilter = new JwtFilter();
}
@Test
public void testNullAuthHeader() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
when(request.getHeader("Authorization")).thenReturn(null);
jwtFilter.doFilter(request, response, filterChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testValidAuthHeader() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
when(request.getHeader("Authorization")).thenReturn("Bearer: AAA");
jwtFilter.doFilter(request, response, filterChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
// If tests passed should not have exception
// @Test
// public void testGetPublicTeamVisibility() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String[] param = {"PUBLIC"};
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getParameterValues("visibility")).thenReturn(param);
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testGetTeamName() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String[] param = {RandomStringUtils.randomAlphabetic(8)};
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getParameterValues("name")).thenReturn(param);
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testGetUsers() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/users/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testGetAuthentication() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/authentication/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testPostRegistrationSlash() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/registrations/");
// when(request.getMethod()).thenReturn("POST");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testPostRegistration() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/registrations");
// when(request.getMethod()).thenReturn("POST");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testIsUserWhitelistEmailVerify() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/users/abc/emails/abc");
// when(request.getMethod()).thenReturn("PUT");
// when(request.getHeader("Authorization")).thenReturn(null);
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
// @Test
// public void testGetExperiment() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/experiments/experiments");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("");
// jwtFilter.doFilter(request, response, filterChain);
// assertThat(SecurityContextHolder.getContext().getAuthentication(), is(notNullValue()));
// @Test
// public void testGetExperimentUsers() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/experiments/users/" + RandomStringUtils.randomAlphabetic(20));
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetExperimentTeams() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/experiments/teams/" + RandomStringUtils.randomAlphabetic(20));
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostAddExperiment() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/experiments");
// when(request.getMethod()).thenReturn("POST");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testDeleteExperiment() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String expId = RandomStringUtils.randomAlphanumeric(20);
// String teamName = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/experiments/" + expId + "/teams/" + teamName);
// when(request.getMethod()).thenReturn("DELETE");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetRealization() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/realizations/" + id);
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetRealizationByExperimentId() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String expId = RandomStringUtils.randomAlphanumeric(20);
// String teamName = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/realizations/team" + teamName + "/experiment/" + expId);
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostStartExperiment() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String expId = RandomStringUtils.randomAlphanumeric(20);
// String teamName = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/realizations/start/team/" + teamName + "/experiment/" + expId);
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostStopExperiment() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String expId = RandomStringUtils.randomAlphanumeric(20);
// String teamName = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/realizations/stop/team/" + teamName + "/experiment/" + expId);
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostRegisterRequestToApplyTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/registrations/newTeam/" + id);
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostRegisterRequestToJoinTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/registrations/joinApplications");
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostApproveJoinRequest() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// String userId = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/registrations/teams/" + id + "/members/" + userId);
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testDeleteApproveJoinRequest() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// String userId = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/registrations/teams/" + id + "/members/" + userId);
// when(request.getMethod()).thenReturn("DELETE");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostApproveRejectJoinTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// String userId = RandomStringUtils.randomAlphabetic(8);
// when(request.getRequestURI()).thenReturn("/registrations/teams/" + id + "/owner/" + userId + "/?status=APPROVE");
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetDeterUID() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/registrations/user/" + id);
// when(request.getMethod()).thenReturn("GET");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostCreateTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetAllTeams() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetTeamById() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/teams/" + id);
// when(request.getMethod()).thenReturn("GET");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPutUpdateTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/teams/" + id);
// when(request.getMethod()).thenReturn("PUT");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostAddTeamMember() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/teams/" + id + "/members");
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPutUpdateUsers() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/users/" + id);
// when(request.getMethod()).thenReturn("PUT");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testPostUsersAddTeam() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// String id = RandomStringUtils.randomAlphanumeric(20);
// when(request.getRequestURI()).thenReturn("/users/" + id + "/teams");
// when(request.getMethod()).thenReturn("POST");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Missing or invalid Authorization header."));
// @Test
// public void testGetTeamsBadObject() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// RememberMeAuthenticationToken rememberMeAuthenticationToken = mock(RememberMeAuthenticationToken.class);
// rememberMeAuthenticationToken.setAuthenticated(true);
// Authentication authentication = mock(Authentication.class);
// final String jwt = Jwts.builder()
// .setSubject("john")
// .setIssuer("Authentication")
// .claim("roles", Arrays.asList("rubbish"))
// // sign the JWT with the given algorithm and apiKey
// .signWith(SignatureAlgorithm.HS256, apiKey)
// .compact();
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("Bearer " + jwt);
// when(authentication.isAuthenticated()).thenReturn(true);
// when(authenticationManager.authenticate(Matchers.any(RememberMeAuthenticationToken.class))).thenReturn(rememberMeAuthenticationToken);
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Failed to verify token."));
// @Test
// public void testGetTeamsInvalidRoles() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// final String jwt = Jwts.builder()
// .setSubject("john")
// .setIssuer("Authentication")
// .claim("roles", Arrays.asList(""))
// // sign the JWT with the given algorithm and apiKey
// .signWith(SignatureAlgorithm.HS256, apiKey)
// .compact();
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("Bearer " + jwt);
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Invalid roles."));
// @Test
// public void testGetTeamsValidRoles() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// RememberMeAuthenticationToken rememberMeAuthenticationToken = mock(RememberMeAuthenticationToken.class);
// rememberMeAuthenticationToken.setAuthenticated(true);
// final String jwt = Jwts.builder()
// .setSubject("john")
// .setIssuer("Authentication")
// .claim("roles", Arrays.asList(Role.USER))
// // sign the JWT with the given algorithm and apiKey
// .signWith(SignatureAlgorithm.HS256, apiKey)
// .compact();
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("Bearer " + jwt);
// when(authenticationManager.authenticate(Matchers.any(RememberMeAuthenticationToken.class))).thenReturn(rememberMeAuthenticationToken);
// jwtFilter.doFilter(request, response, filterChain);
// @Test
// public void testMalformedJwtException() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("Bearer " + "abc");
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Invalid token."));
// @Test
// public void testSignatureException() throws Exception {
// HttpServletRequest request = mock(HttpServletRequest.class);
// HttpServletResponse response = mock(HttpServletResponse.class);
// FilterChain filterChain = mock(FilterChain.class);
// RememberMeAuthenticationToken rememberMeAuthenticationToken = mock(RememberMeAuthenticationToken.class);
// final String jwt = Jwts.builder()
// .setSubject("john")
// .setIssuer("Authentication")
// .claim("roles", Arrays.asList(Role.USER))
// // sign the JWT with the given algorithm and apiKey
// .signWith(SignatureAlgorithm.HS256, new SecretKeySpec("456".getBytes(), SignatureAlgorithm.HS256.getJcaName()))
// .compact();
// when(request.getRequestURI()).thenReturn("/teams/");
// when(request.getMethod()).thenReturn("GET");
// when(request.getHeader("Authorization")).thenReturn("Bearer " + jwt);
// when(authenticationManager.authenticate(rememberMeAuthenticationToken)).thenReturn(rememberMeAuthenticationToken);
// try {
// jwtFilter.doFilter(request, response, filterChain);
// Assert.fail();
// } catch (ServletException e) {
// assertThat(e.getMessage(), is("Invalid token."));
}
|
package py4j.commands;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.logging.Logger;
import py4j.Gateway;
import py4j.JVMView;
import py4j.Protocol;
import py4j.Py4JException;
import py4j.ReturnObject;
import py4j.reflection.ReflectionEngine;
import py4j.reflection.TypeUtil;
/**
* <p>
* The ReflectionCommand is responsible for accessing packages, classes, and
* static members. This is the command invoked when using the jvm property of a
* JavaGateway on the Python side.
* </p>
*
* @author Barthelemy Dagenais
*
*/
public class ReflectionCommand extends AbstractCommand {
private final Logger logger = Logger.getLogger(ReflectionCommand.class
.getName());
public final static char GET_UNKNOWN_SUB_COMMAND_NAME = 'u';
public final static char GET_MEMBER_SUB_COMMAND_NAME = 'm';
public static final String REFLECTION_COMMAND_NAME = "r";
protected ReflectionEngine rEngine;
public ReflectionCommand() {
super();
this.commandName = REFLECTION_COMMAND_NAME;
}
@Override
public void init(Gateway gateway) {
super.init(gateway);
rEngine = gateway.getReflectionEngine();
}
@Override
public void execute(String commandName, BufferedReader reader,
BufferedWriter writer) throws Py4JException, IOException {
char subCommand = reader.readLine().charAt(0);
String returnCommand = null;
if (subCommand == GET_UNKNOWN_SUB_COMMAND_NAME) {
returnCommand = getUnknownMember(reader);
} else {
returnCommand = getMember(reader);
}
logger.info("Returning command: " + returnCommand);
writer.write(returnCommand);
writer.flush();
}
/**
* 1- Try fields. 2- If no static field, try methods. 3- If method and
* static, return method. 4- If method and not static, then class is
* impossible so return exception. 5- If no method, try class.
*
* @param reader
* @return
* @throws IOException
*/
private String getMember(BufferedReader reader) throws IOException {
String fqn = reader.readLine();
String member = reader.readLine();
reader.readLine();
String returnCommand = null;
try {
Class<?> clazz = TypeUtil.forName(fqn);
Field f = rEngine.getField(clazz, member);
if (f != null && Modifier.isStatic(f.getModifiers())) {
Object obj = rEngine.getFieldValue(null, f);
ReturnObject rObject = gateway.getReturnObject(obj);
returnCommand = Protocol.getOutputCommand(rObject);
}
if (returnCommand == null) {
Method m = rEngine.getMethod(clazz, member);
if (m != null) {
if (Modifier.isStatic(m.getModifiers())) {
returnCommand = Protocol
.getMemberOutputCommand(Protocol.METHOD_TYPE);
} else {
returnCommand = Protocol.getOutputErrorCommand("Trying to access a non-static member from a static context.");
}
}
}
if (returnCommand == null) {
Class<?> c = rEngine.getClass(clazz, member);
if (c != null) {
returnCommand = Protocol
.getMemberOutputCommand(Protocol.CLASS_TYPE);
} else {
returnCommand = Protocol.getOutputErrorCommand();
}
}
} catch (Exception e) {
returnCommand = Protocol.getOutputErrorCommand();
}
return returnCommand;
}
private String getUnknownMember(BufferedReader reader) throws IOException {
String fqn = reader.readLine();
String jvmId = reader.readLine();
JVMView view = (JVMView)Protocol.getObject(jvmId, this.gateway);
reader.readLine();
String returnCommand = null;
try {
// TODO APPEND CLASS NAME, because it might not be the fqn, but a new one because of imports!
String fullyQualifiedName = TypeUtil.forName(fqn, view).getName();
returnCommand = Protocol
.getMemberOutputCommand(Protocol.CLASS_TYPE, fullyQualifiedName);
} catch (ClassNotFoundException e) {
returnCommand = Protocol
.getMemberOutputCommand(Protocol.PACKAGE_TYPE);
} catch (Exception e) {
returnCommand = Protocol.getOutputErrorCommand(e);
}
return returnCommand;
}
}
|
package org.crunchytorch.coddy.user.api;
import com.shazam.shazamcrest.MatcherAssert;
import com.shazam.shazamcrest.matcher.Matchers;
import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.crunchytorch.coddy.Main;
import org.crunchytorch.coddy.user.data.Credential;
import org.crunchytorch.coddy.user.elasticsearch.entity.UserEntity;
import org.crunchytorch.coddy.application.data.Response;
import org.crunchytorch.coddy.application.utils.TestUtils;
import org.crunchytorch.coddy.user.data.Token;
import org.crunchytorch.coddy.user.elasticsearch.repository.UserRepository;
import java.io.IOException;
import java.util.Arrays;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
classes = Main.class)
public class UserTest {
private static final String USER_ENDPOINT = "/user";
private TestRestTemplate restTemplate = new TestRestTemplate();
@Autowired
private UserRepository repository;
@Before
public void populateDataBase() throws IOException {
UserEntity[] users = TestUtils.getObjecFromJson("user/user.database.json", UserEntity[].class);
repository.save(Arrays.asList(users));
}
@After
public void dropDatabase() {
repository.deleteAll();
}
@Test
public void testGetUserWithoutToken() {
ResponseEntity<Response> response =
restTemplate.getForEntity(TestUtils.getUrl(USER_ENDPOINT + "/napoleon"), Response.class);
Response expected = new Response("HTTP 401 Unauthorized");
Assert.assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
MatcherAssert.assertThat(response.getBody(), Matchers.sameBeanAs(expected));
}
@Test
public void testGetUserWithToken() throws IOException {
HttpEntity<String> entity = getHttpEntityWithToken("ciceron", "tutu");
ResponseEntity<UserEntity> response = restTemplate.exchange(TestUtils.getUrl(USER_ENDPOINT + "/ciceron"), HttpMethod.GET, entity, UserEntity.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
MatcherAssert.assertThat(response.getBody(), Matchers.sameBeanAs(TestUtils.getObjecFromJson("user/getUserWithTokenExpected.json", UserEntity.class)));
}
@Test
public void testDeleteUserWithToken() {
final String login = "ciceron";
HttpEntity<String> entity = getHttpEntityWithToken(login, "tutu");
ResponseEntity<String> response = restTemplate.exchange(TestUtils.getUrl(USER_ENDPOINT + "/ciceron"), HttpMethod.DELETE, entity, String.class);
Assert.assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
// check if the user is effectively deleted.
UserEntity user = repository.findByLogin(login);
Assert.assertEquals(user, null);
}
@Test
public void testDeleteWithoutToken() {
ResponseEntity<Response> response =
restTemplate.exchange(TestUtils.getUrl(USER_ENDPOINT + "/napoleon"), HttpMethod.DELETE, null, Response.class);
Response expected = new Response("HTTP 401 Unauthorized");
Assert.assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
MatcherAssert.assertThat(response.getBody(), Matchers.sameBeanAs(expected));
}
@Test
public void testAuthWithCorrectUser() {
ResponseEntity<Token> response = this.auth("ciceron", "tutu", Token.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals(true, response.getBody() != null && StringUtils.isNotEmpty(response.getBody().getToken()));
}
@Test
public void testAuthWithWrongCrendential() {
ResponseEntity<Response> response = this.auth("ciceron", "toto", Response.class);
Response expected = new Response(Response.WRONG_CREDENTIAL);
Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
MatcherAssert.assertThat(response.getBody(), Matchers.sameBeanAs(expected));
}
@Test
public void testAuthWithNonExistantUser() {
ResponseEntity<Response> response = this.auth("perlinpinpin", "toto", Response.class);
Response expected = new Response(Response.WRONG_CREDENTIAL);
Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
MatcherAssert.assertThat(response.getBody(), Matchers.sameBeanAs(expected));
}
private HttpEntity<String> getHttpEntityWithToken(final String login, final String password) {
Token token = this.auth(login, password, Token.class).getBody();
HttpHeaders headers = new HttpHeaders();
headers.add(javax.ws.rs.core.HttpHeaders.AUTHORIZATION, token.getToken());
headers.add(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_JSON);
return new HttpEntity<>("parameters", headers);
}
private <T> ResponseEntity<T> auth(final String login, final String password, Class<T> responseType) {
Credential credential = new Credential(login, password.toCharArray());
return restTemplate.postForEntity(TestUtils.getUrl(USER_ENDPOINT + "/auth"), credential, responseType);
}
}
|
// APNGReader.java
package loci.formats.in;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.zip.CRC32;
import javax.imageio.ImageIO;
import loci.common.DataTools;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.gui.AWTImageTools;
import loci.formats.meta.MetadataStore;
public class APNGReader extends BIFormatReader {
// -- Constants --
private static final byte[] PNG_SIGNATURE = new byte[] {
(byte) 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
};
// -- Fields --
private Vector<PNGBlock> blocks;
private Vector<int[]> frameCoordinates;
private byte[][] lut;
// -- Constructor --
/** Constructs a new APNGReader. */
public APNGReader() {
super("Animated PNG", "png");
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
suffixNecessary = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 8;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
byte[] signature = new byte[8];
stream.read(signature);
if (signature[0] != (byte) 0x89 || signature[1] != 0x50 ||
signature[2] != 0x4e || signature[3] != 0x47 || signature[4] != 0x0d ||
signature[5] != 0x0a || signature[6] != 0x1a || signature[7] != 0x0a)
{
return false;
}
return true;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
return lut;
}
/* @see loci.formats.IFormatReader#openPlane(int, int, int, int, int int) */
public Object openPlane(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, -1, x, y, w, h);
if (no == 0) {
in.seek(0);
DataInputStream dis =
new DataInputStream(new BufferedInputStream(in, 4096));
if (x == 0 && y == 0 && w == getSizeX() && h == getSizeY()) {
return ImageIO.read(dis);
}
return AWTImageTools.getSubimage(ImageIO.read(dis), isLittleEndian(),
x, y, w, h);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
stream.write(PNG_SIGNATURE);
boolean fdatValid = false;
int fctlCount = 0;
int[] coords = frameCoordinates.get(no);
for (PNGBlock block : blocks) {
if (!block.type.equals("IDAT") && !block.type.equals("fdAT") &&
!block.type.equals("acTL") && !block.type.equals("fcTL") &&
block.length > 0)
{
byte[] b = new byte[block.length + 12];
DataTools.unpackBytes(block.length, b, 0, 4, isLittleEndian());
byte[] typeBytes = block.type.getBytes();
System.arraycopy(typeBytes, 0, b, 4, 4);
in.seek(block.offset);
in.read(b, 8, b.length - 12);
if (block.type.equals("IHDR")) {
DataTools.unpackBytes(coords[2], b, 8, 4, isLittleEndian());
DataTools.unpackBytes(coords[3], b, 12, 4, isLittleEndian());
}
int crc = (int) computeCRC(b, b.length - 4);
DataTools.unpackBytes(crc, b, b.length - 4, 4, isLittleEndian());
stream.write(b);
b = null;
}
else if (block.type.equals("fcTL")) {
fdatValid = fctlCount == no;
fctlCount++;
}
else if (block.type.equals("fdAT")) {
in.seek(block.offset + 4);
if (fdatValid) {
byte[] b = new byte[block.length + 8];
DataTools.unpackBytes(block.length - 4, b, 0, 4, isLittleEndian());
b[4] = 'I';
b[5] = 'D';
b[6] = 'A';
b[7] = 'T';
in.read(b, 8, b.length - 12);
int crc = (int) computeCRC(b, b.length - 4);
DataTools.unpackBytes(crc, b, b.length - 4, 4, isLittleEndian());
stream.write(b);
b = null;
}
}
}
RandomAccessInputStream s =
new RandomAccessInputStream(stream.toByteArray());
DataInputStream dis = new DataInputStream(new BufferedInputStream(s, 4096));
BufferedImage b = ImageIO.read(dis);
dis.close();
BufferedImage first = (BufferedImage)
openPlane(0, 0, 0, getSizeX(), getSizeY());
// paste current image onto first image
WritableRaster firstRaster = first.getRaster();
WritableRaster currentRaster = b.getRaster();
firstRaster.setDataElements(coords[0], coords[1], currentRaster);
return new BufferedImage(first.getColorModel(), firstRaster, false, null);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
lut = null;
frameCoordinates = null;
blocks = null;
}
}
// -- Internal FormatReader methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
// check that this is a valid PNG file
byte[] signature = new byte[8];
in.read(signature);
if (signature[0] != (byte) 0x89 || signature[1] != 0x50 ||
signature[2] != 0x4e || signature[3] != 0x47 || signature[4] != 0x0d ||
signature[5] != 0x0a || signature[6] != 0x1a || signature[7] != 0x0a)
{
throw new FormatException("Invalid PNG signature.");
}
// read data chunks - each chunk consists of the following:
// 1) 32 bit length
// 2) 4 char type
// 3) 'length' bytes of data
// 4) 32 bit CRC
blocks = new Vector<PNGBlock>();
frameCoordinates = new Vector<int[]>();
while (in.getFilePointer() < in.length()) {
int length = in.readInt();
String type = in.readString(4);
PNGBlock block = new PNGBlock();
block.length = length;
block.type = type;
block.offset = in.getFilePointer();
blocks.add(block);
if (type.equals("acTL")) {
// APNG-specific chunk
core[0].imageCount = in.readInt();
int loop = in.readInt();
addGlobalMeta("Loop count", loop);
}
else if (type.equals("fcTL")) {
in.skipBytes(4);
int w = in.readInt();
int h = in.readInt();
int x = in.readInt();
int y = in.readInt();
frameCoordinates.add(new int[] {x, y, w, h});
in.skipBytes(length - 20);
}
else in.skipBytes(length);
if (in.getFilePointer() < in.length() - 4) {
in.skipBytes(4); // skip the CRC
}
}
if (core[0].imageCount == 0) core[0].imageCount = 1;
core[0].sizeZ = 1;
core[0].sizeT = getImageCount();
core[0].dimensionOrder = "XYCTZ";
core[0].interleaved = false;
RandomAccessInputStream ras = new RandomAccessInputStream(currentId);
DataInputStream dis = new DataInputStream(ras);
BufferedImage img = ImageIO.read(dis);
dis.close();
core[0].sizeX = img.getWidth();
core[0].sizeY = img.getHeight();
core[0].rgb = img.getRaster().getNumBands() > 1;
core[0].sizeC = img.getRaster().getNumBands();
core[0].pixelType = AWTImageTools.getPixelType(img);
core[0].indexed = img.getColorModel() instanceof IndexColorModel;
core[0].falseColor = false;
if (isIndexed()) {
lut = new byte[3][256];
IndexColorModel model = (IndexColorModel) img.getColorModel();
model.getReds(lut[0]);
model.getGreens(lut[1]);
model.getBlues(lut[2]);
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
MetadataTools.setDefaultCreationDate(store, id, 0);
}
// -- Helper methods --
private long computeCRC(byte[] buf, int len) {
CRC32 crc = new CRC32();
crc.update(buf, 0, len);
return crc.getValue();
}
// -- Helper class --
class PNGBlock {
public long offset;
public int length;
public String type;
}
}
|
// FakeReader.java
package loci.formats.in;
import java.io.IOException;
import java.util.Random;
import loci.common.DataTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
public class FakeReader extends FormatReader {
// -- Constants --
public static final int BOX_SIZE = 10;
private static final String TOKEN_SEPARATOR = "&";
private static final long SEED = 0xcafebabe;
// -- Fields --
/** 8-bit lookup table, if indexed color. */
private byte[][] lut8 = null;
/** 16-bit lookup table, if indexed color. */
private short[][] lut16 = null;
private int[] indexToValue = null, valueToIndex = null;
// -- Constructor --
/** Constructs a new fake reader. */
public FakeReader() { super("Simulated data", "fake"); }
// -- IFormatReader API methods --
/* @see IFormatReader#get8BitLookupTable() */
@Override
public byte[][] get8BitLookupTable() throws FormatException, IOException {
return lut8;
}
/* @see IFormatReader#get16BitLookupTable() */
@Override
public short[][] get16BitLookupTable() throws FormatException, IOException {
return lut16;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
final int series = getSeries();
final int pixelType = getPixelType();
final int bpp = FormatTools.getBytesPerPixel(pixelType);
final boolean signed = FormatTools.isSigned(pixelType);
final boolean floating = FormatTools.isFloatingPoint(pixelType);
final int rgb = getRGBChannelCount();
final boolean indexed = isIndexed();
final boolean little = isLittleEndian();
final boolean interleaved = isInterleaved();
final int[] zct = getZCTCoords(no);
final int zIndex = zct[0], cIndex = zct[1], tIndex = zct[2];
// integer types start gradient at the smallest value
long min = signed ? (long) -Math.pow(2, 8 * bpp - 1) : 0;
if (floating) min = 0; // floating point types always start at 0
for (int cOffset=0; cOffset<rgb; cOffset++) {
int channel = cIndex + cOffset;
for (int row=0; row<h; row++) {
int yy = y + row;
for (int col=0; col<w; col++) {
int xx = x + col;
// encode various information into the image plane
long pixel = min + xx;
if (yy < BOX_SIZE) {
int grid = xx / BOX_SIZE;
switch (grid) {
case 0:
pixel = series;
break;
case 1:
pixel = no;
break;
case 2:
pixel = zIndex;
break;
case 3:
pixel = channel;
break;
case 4:
pixel = tIndex;
break;
}
}
// if indexed color with non-null LUT, convert value to index
if (indexed) {
if (lut8 != null) pixel = valueToIndex[(int) (pixel % 256)];
if (lut16 != null) pixel = valueToIndex[(int) (pixel % 65536)];
}
// if floating point, convert value to raw IEEE floating point bits
switch (pixelType) {
case FormatTools.FLOAT:
pixel = Float.floatToIntBits(pixel);
break;
case FormatTools.DOUBLE:
pixel = Double.doubleToLongBits(pixel);
break;
}
// unpack pixel into byte buffer
int index;
if (interleaved) index = w * rgb * row + rgb * col + cOffset; // CXY
else index = h * w * cOffset + w * row + col; // XYC
index *= bpp;
DataTools.unpackBytes(pixel, buf, index, bpp, little);
}
}
}
return buf;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
String noExt = id.substring(0, id.lastIndexOf("."));
String[] tokens = noExt.split(TOKEN_SEPARATOR);
String name = null;
int sizeX = 512;
int sizeY = 512;
int sizeZ = 1;
int sizeC = 1;
int sizeT = 1;
int thumbSizeX = 0; // default
int thumbSizeY = 0; // default
int pixelType = FormatTools.UINT8;
int rgb = 1;
String dimOrder = "XYZCT";
boolean orderCertain = true;
boolean little = true;
boolean interleaved = false;
boolean indexed = false;
boolean falseColor = false;
boolean metadataComplete = true;
boolean thumbnail = false;
int seriesCount = 1;
int lutLength = 3;
// parse tokens from filename
for (String token : tokens) {
if (name == null) {
// first token is the image name
name = token;
continue;
}
int equals = token.indexOf("=");
if (equals < 0) {
LOGGER.warn("ignoring token: {}", token);
continue;
}
String key = token.substring(0, equals);
String value = token.substring(equals + 1);
boolean bool = value.equals("true");
int num = -1;
try { num = Integer.parseInt(value); }
catch (NumberFormatException exc) { }
if (key.equals("sizeX")) sizeX = num;
else if (key.equals("sizeY")) sizeY = num;
else if (key.equals("sizeZ")) sizeZ = num;
else if (key.equals("sizeC")) sizeC = num;
else if (key.equals("sizeT")) sizeT = num;
else if (key.equals("thumbSizeX")) thumbSizeX = num;
else if (key.equals("thumbSizeY")) thumbSizeY = num;
else if (key.equals("pixelType")) {
pixelType = FormatTools.pixelTypeFromString(value);
}
else if (key.equals("rgb")) rgb = num;
else if (key.equals("dimOrder")) dimOrder = value.toUpperCase();
else if (key.equals("orderCertain")) orderCertain = bool;
else if (key.equals("little")) little = bool;
else if (key.equals("interleaved")) interleaved = bool;
else if (key.equals("indexed")) indexed = bool;
else if (key.equals("falseColor")) falseColor = bool;
else if (key.equals("metadataComplete")) metadataComplete = bool;
else if (key.equals("thumbnail")) thumbnail = bool;
else if (key.equals("series")) seriesCount = num;
else if (key.equals("lutLength")) lutLength = num;
}
// do some sanity checks
if (sizeX < 1) throw new FormatException("Invalid sizeX: " + sizeX);
if (sizeY < 1) throw new FormatException("Invalid sizeY: " + sizeY);
if (sizeZ < 1) throw new FormatException("Invalid sizeZ: " + sizeZ);
if (sizeC < 1) throw new FormatException("Invalid sizeC: " + sizeC);
if (sizeT < 1) throw new FormatException("Invalid sizeT: " + sizeT);
if (thumbSizeX < 0) {
throw new FormatException("Invalid thumbSizeX: " + thumbSizeX);
}
if (thumbSizeY < 0) {
throw new FormatException("Invalid thumbSizeY: " + thumbSizeY);
}
if (rgb < 1 || rgb > sizeC || sizeC % rgb != 0) {
throw new FormatException("Invalid sizeC/rgb combination: " +
sizeC + "/" + rgb);
}
getDimensionOrder(dimOrder);
if (falseColor && !indexed) {
throw new FormatException("False color images must be indexed");
}
if (seriesCount < 1) {
throw new FormatException("Invalid seriesCount: " + seriesCount);
}
if (lutLength < 1) {
throw new FormatException("Invalid lutLength: " + lutLength);
}
// populate core metadata
int effSizeC = sizeC / rgb;
core = new CoreMetadata[seriesCount];
for (int s=0; s<seriesCount; s++) {
core[s] = new CoreMetadata();
core[s].sizeX = sizeX;
core[s].sizeY = sizeY;
core[s].sizeZ = sizeZ;
core[s].sizeC = sizeC;
core[s].sizeT = sizeT;
core[s].thumbSizeX = thumbSizeX;
core[s].thumbSizeY = thumbSizeY;
core[s].pixelType = pixelType;
core[s].imageCount = sizeZ * effSizeC * sizeT;
core[s].rgb = rgb > 1;
core[s].dimensionOrder = dimOrder;
core[s].orderCertain = orderCertain;
core[s].littleEndian = little;
core[s].interleaved = interleaved;
core[s].indexed = indexed;
core[s].falseColor = falseColor;
core[s].metadataComplete = metadataComplete;
core[s].thumbnail = thumbnail;
}
// populate OME metadata
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
for (int s=0; s<seriesCount; s++) {
String imageName = s > 0 ? name + " " + (s + 1) : name;
store.setImageName(imageName, s);
MetadataTools.setDefaultCreationDate(store, id, s);
}
// for indexed color images, create lookup tables
if (indexed) {
if (pixelType == FormatTools.UINT8) {
// create 8-bit LUT
final int num = 256;
createIndexMap(num);
lut8 = new byte[lutLength][num];
// linear ramp
for (int c=0; c<lutLength; c++) {
for (int index = 0; index < num; index++) {
lut8[c][index] = (byte) indexToValue[index];
}
}
}
else if (pixelType == FormatTools.UINT16) {
// create 16-bit LUT
final int num = 65536;
createIndexMap(num);
lut16 = new short[lutLength][num];
// linear ramp
for (int c=0; c<lutLength; c++) {
for (int index = 0; index < num; index++) {
lut16[c][index] = (short) indexToValue[index];
}
}
}
// NB: Other pixel types will have null LUTs.
}
}
// -- Helper methods --
/** Creates a mapping between indices and color values. */
private void createIndexMap(int num) {
// create random mapping from indices to values
indexToValue = new int[num];
for (int index = 0; index < num; index++) indexToValue[index] = index;
shuffle(indexToValue);
// create inverse mapping: values to indices
valueToIndex = new int[num];
for (int index = 0; index < num; index++) {
int value = indexToValue[index];
valueToIndex[value] = index;
}
}
/** Fisher-Yates shuffle with constant seed to ensure reproducibility. */
private static void shuffle(int[] array) {
Random r = new Random(SEED);
for (int i = array.length; i > 1; i
int j = r.nextInt(i);
int tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
}
|
// JEOLReader.java
package loci.formats.in;
import java.io.IOException;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
public class JEOLReader extends FormatReader {
// -- Fields --
private long pixelOffset;
private String parameterFile;
// -- Constructor --
/** Constructs a new JEOL reader. */
public JEOLReader() {
super("JEOL", new String[] {"dat", "img", "par"});
domains = new String[] {FormatTools.SEM_DOMAIN};
hasCompanionFiles = true;
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, "par") && open) {
String base = new Location(name).getAbsoluteFile().getAbsolutePath();
base = base.substring(0, base.lastIndexOf("."));
String id = base + ".IMG";
if (!new Location(id).exists()) {
id = base + ".DAT";
}
if (!new Location(id).exists()) {
return false;
}
return true;
}
if (checkSuffix(name, "dat") && open) {
try {
RandomAccessInputStream stream = new RandomAccessInputStream(name);
if (stream.length() == (1024 * 1024)) return true;
}
catch (IOException e) { }
return false;
}
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 2;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
String magic = stream.readString(blockLen);
return magic.equals("MG") || magic.equals("IM");
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
if (noPixels) {
return parameterFile == null ? null : new String[] {parameterFile};
}
String id = new Location(currentId).getAbsolutePath();
return parameterFile == null ? new String[] {id} :
new String[] {id, parameterFile};
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
in.seek(pixelOffset);
readPlane(in, x, y, w, h, buf);
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
pixelOffset = 0;
parameterFile = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (checkSuffix(id, "par")) {
String base = new Location(id).getAbsoluteFile().getAbsolutePath();
base = base.substring(0, base.lastIndexOf("."));
id = base + ".IMG";
if (!new Location(id).exists()) {
id = base + ".DAT";
}
if (!new Location(id).exists()) {
throw new FormatException("Could not find image file.");
}
}
super.initFile(id);
in = new RandomAccessInputStream(id);
core[0].littleEndian = true;
in.order(isLittleEndian());
parameterFile = id.substring(0, id.lastIndexOf(".")) + ".PAR";
parameterFile = new Location(parameterFile).getAbsolutePath();
if (!new Location(parameterFile).exists()) parameterFile = null;
String magic = in.readString(2);
if (magic.equals("MG")) {
in.seek(0x63c);
core[0].sizeX = in.readInt();
core[0].sizeY = in.readInt();
pixelOffset = in.getFilePointer() + 540;
}
else if (magic.equals("IM")) {
int commentLength = in.readShort();
core[0].sizeX = 1024;
pixelOffset = in.getFilePointer() + commentLength + 56;
core[0].sizeY = (int) ((in.length() - pixelOffset) / getSizeX());
}
else {
core[0].sizeX = 1024;
core[0].sizeY = 1024;
pixelOffset = 0;
}
addGlobalMeta("Pixel data offset", pixelOffset);
core[0].pixelType = FormatTools.UINT8;
core[0].sizeZ = 1;
core[0].sizeC = 1;
core[0].sizeT = 1;
core[0].imageCount = 1;
core[0].dimensionOrder = "XYZCT";
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
|
package com.ejlchina.searcher;
import com.ejlchina.searcher.util.MapUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestCase1 {
public static class SearchBean {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Test
public void test1() {
SqlExecutor sqlExecutor = new SqlExecutor() {
@Override
public <T> SqlResult<T> execute(SearchSql<T> searchSql) {
Assert.assertEquals("select name _1, id _0 from search_bean limit ?, ?", searchSql.getListSqlString());
List<Object> listParams = searchSql.getListSqlParams();
Assert.assertEquals(2, listParams.size());
Assert.assertEquals(0L, listParams.get(0));
Assert.assertEquals(15, listParams.get(1));
Assert.assertEquals("select count(*) _count from search_bean", searchSql.getClusterSqlString());
Assert.assertEquals(0, searchSql.getClusterSqlParams().size());
Assert.assertEquals("_count", searchSql.getCountAlias());
Assert.assertEquals(0, searchSql.getSummaryAliases().size());
return new SqlResult<>(searchSql);
}
};
MapSearcher mapSearcher = SearcherBuilder.mapSearcher().sqlExecutor(sqlExecutor).build();
mapSearcher.search(SearchBean.class, new HashMap<>());
mapSearcher.search(SearchBean.class, null);
BeanSearcher beanSearcher = SearcherBuilder.beanSearcher().sqlExecutor(sqlExecutor).build();
beanSearcher.search(SearchBean.class, new HashMap<>());
beanSearcher.search(SearchBean.class, null);
}
@Test
public void test2() {
SqlExecutor sqlExecutor = new SqlExecutor() {
@Override
public <T> SqlResult<T> execute(SearchSql<T> searchSql) {
System.out.println(searchSql.getListSqlString());
System.out.println(searchSql.getListSqlParams());
Assert.assertEquals("select name _1, id _0 from search_bean where (id = ?) limit ?, ?", searchSql.getListSqlString());
List<Object> listParams = searchSql.getListSqlParams();
Assert.assertEquals(3, listParams.size());
Assert.assertEquals(1, listParams.get(0));
Assert.assertEquals(0L, listParams.get(1));
Assert.assertEquals(15, listParams.get(2));
System.out.println(searchSql.getClusterSqlString());
Assert.assertEquals("select count(*) _count from search_bean where (id = ?)", searchSql.getClusterSqlString());
List<Object> clusterSqlParams = searchSql.getClusterSqlParams();
System.out.println(clusterSqlParams);
Assert.assertEquals(1, clusterSqlParams.size());
Assert.assertEquals(1, clusterSqlParams.get(0));
System.out.println(searchSql.getCountAlias());
Assert.assertEquals("_count", searchSql.getCountAlias());
System.out.println(searchSql.getSummaryAliases());
Assert.assertEquals(0, searchSql.getSummaryAliases().size());
return new SqlResult<>(searchSql);
}
};
MapSearcher mapSearcher = SearcherBuilder.mapSearcher().sqlExecutor(sqlExecutor).build();
BeanSearcher beanSearcher = SearcherBuilder.beanSearcher().sqlExecutor(sqlExecutor).build();
Map<String, Object> params1 = new HashMap<>();
params1.put("id", 1);
Map<String, Object> params2 = MapUtils.builder().field(SearchBean::getId, 1).build();
mapSearcher.search(SearchBean.class, params1);
mapSearcher.search(SearchBean.class, params2);
beanSearcher.search(SearchBean.class, params1);
beanSearcher.search(SearchBean.class, params2);
}
}
|
// APLReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.MDBService;
public class APLReader extends FormatReader {
// -- Constants --
private static final String[] METADATA_SUFFIXES =
new String[] {"apl", "tnb", "mtb" };
// -- Fields --
private String[] tiffFiles;
private String[] xmlFiles;
private MinimalTiffReader[] tiffReaders;
private Vector<String> used;
// -- Constructor --
/** Constructs a new APL reader. */
public APLReader() {
super("Olympus APL", new String[] {"apl", "tnb", "mtb", "tif"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, METADATA_SUFFIXES)) return true;
if (checkSuffix(name, "tif") && open) {
Location file = new Location(name).getAbsoluteFile();
Location parent = file.getParentFile();
if (parent != null) {
parent = parent.getParentFile();
if (parent != null) {
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, "mtb")) return true;
}
}
}
}
return false;
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
files.addAll(used);
if (getSeries() < xmlFiles.length &&
new Location(xmlFiles[getSeries()]).exists())
{
files.add(xmlFiles[getSeries()]);
}
if (!noPixels && getSeries() < tiffFiles.length &&
new Location(tiffFiles[getSeries()]).exists())
{
files.add(tiffFiles[getSeries()]);
}
return files.toArray(new String[files.size()]);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
return tiffReaders[series].openBytes(no, buf, x, y, w, h);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (tiffReaders != null) {
for (MinimalTiffReader reader : tiffReaders) {
reader.close(fileOnly);
}
}
if (!fileOnly) {
tiffReaders = null;
tiffFiles = null;
xmlFiles = null;
used = null;
}
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
return tiffReaders[getSeries()].getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return tiffReaders[getSeries()].getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
LOGGER.debug("Initializing {}", id);
// find the corresponding .mtb file
if (!checkSuffix(id, "mtb")) {
if (checkSuffix(id, METADATA_SUFFIXES)) {
int separator = id.lastIndexOf(File.separator);
if (separator < 0) separator = 0;
int underscore = id.lastIndexOf("_");
if (underscore < separator) underscore = id.lastIndexOf(".");
String mtbFile = id.substring(0, underscore) + "_d.mtb";
if (!new Location(mtbFile).exists()) {
throw new FormatException(".mtb file not found");
}
currentId = new Location(mtbFile).getAbsolutePath();
}
else {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
parent = parent.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, "mtb")) {
currentId = new Location(parent, f).getAbsolutePath();
break;
}
}
if (!checkSuffix(currentId, "mtb")) {
throw new FormatException(".mtb file not found");
}
}
}
String mtb = new Location(currentId).getAbsolutePath();
LOGGER.debug("Reading .mtb file '{}'", mtb);
MDBService mdb = null;
try {
ServiceFactory factory = new ServiceFactory();
mdb = factory.getInstance(MDBService.class);
}
catch (DependencyException de) {
throw new FormatException("MDB Tools Java library not found", de);
}
mdb.initialize(mtb);
Vector<String[]> rows = mdb.parseDatabase().get(0);
String[] columnNames = rows.get(0);
String[] tmpNames = columnNames;
columnNames = new String[tmpNames.length - 1];
System.arraycopy(tmpNames, 1, columnNames, 0, columnNames.length);
// add full table to metadata hashtable
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
for (int i=1; i<rows.size(); i++) {
String[] row = rows.get(i);
for (int q=0; q<row.length; q++) {
addGlobalMeta(columnNames[q] + " " + i, row[q]);
}
}
}
used = new Vector<String>();
used.add(mtb);
String tnb = mtb.substring(0, mtb.lastIndexOf("."));
if (tnb.lastIndexOf("_") > tnb.lastIndexOf(File.separator)) {
tnb = tnb.substring(0, tnb.lastIndexOf("_"));
}
used.add(tnb + "_1.tnb");
used.add(tnb + ".apl");
String idPath = new Location(id).getAbsolutePath();
if (!used.contains(idPath)) used.add(idPath);
// calculate indexes to relevant metadata
int calibrationUnit = DataTools.indexOf(columnNames, "Calibration Unit");
int colorChannels = DataTools.indexOf(columnNames, "Color Channels");
int frames = DataTools.indexOf(columnNames, "Frames");
int calibratedHeight = DataTools.indexOf(columnNames, "Height");
int calibratedWidth = DataTools.indexOf(columnNames, "Width");
int path = DataTools.indexOf(columnNames, "Image Path");
int filename = DataTools.indexOf(columnNames, "File Name");
int magnification = DataTools.indexOf(columnNames, "Magnification");
int width = DataTools.indexOf(columnNames, "X-Resolution");
int height = DataTools.indexOf(columnNames, "Y-Resolution");
int imageName = DataTools.indexOf(columnNames, "Image Name");
int zLayers = DataTools.indexOf(columnNames, "Z-Layers");
String parentDirectory = mtb.substring(0, mtb.lastIndexOf(File.separator));
// look for the directory that contains TIFF and XML files
LOGGER.debug("Searching {} for a directory with TIFFs", parentDirectory);
Location dir = new Location(parentDirectory);
String[] list = dir.list(true);
String topDirectory = null;
for (String f : list) {
LOGGER.debug(" '{}'", f);
Location file = new Location(dir, f);
if (file.isDirectory() && f.indexOf("_DocumentFiles") > 0) {
LOGGER.debug("Found {}", topDirectory);
topDirectory = file.getAbsolutePath();
break;
}
}
if (topDirectory == null) {
throw new FormatException("Could not find a directory with TIFF files.");
}
Vector<Integer> seriesIndexes = new Vector<Integer>();
for (int i=1; i<rows.size(); i++) {
String file = rows.get(i)[filename].trim();
if (file.equals("")) continue;
file = topDirectory + File.separator + file;
if (new Location(file).exists() && checkSuffix(file, "tif")) {
seriesIndexes.add(i);
}
}
int seriesCount = seriesIndexes.size();
core = new CoreMetadata[seriesCount];
for (int i=0; i<seriesCount; i++) {
core[i] = new CoreMetadata();
}
tiffFiles = new String[seriesCount];
xmlFiles = new String[seriesCount];
tiffReaders = new MinimalTiffReader[seriesCount];
for (int i=0; i<seriesCount; i++) {
int secondRow = seriesIndexes.get(i);
int firstRow = secondRow - 1;
String[] row2 = rows.get(firstRow);
String[] row3 = rows.get(secondRow);
core[i].sizeT = parseDimension(row3[frames]);
core[i].sizeZ = parseDimension(row3[zLayers]);
core[i].sizeC = parseDimension(row3[colorChannels]);
core[i].dimensionOrder = "XYCZT";
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
xmlFiles[i] = topDirectory + File.separator + row2[filename];
tiffFiles[i] = topDirectory + File.separator + row3[filename];
tiffReaders[i] = new MinimalTiffReader();
tiffReaders[i].setId(tiffFiles[i]);
// get core metadata from TIFF file
core[i].sizeX = tiffReaders[i].getSizeX();
core[i].sizeY = tiffReaders[i].getSizeY();
core[i].rgb = tiffReaders[i].isRGB();
core[i].pixelType = tiffReaders[i].getPixelType();
core[i].littleEndian = tiffReaders[i].isLittleEndian();
core[i].indexed = tiffReaders[i].isIndexed();
core[i].falseColor = tiffReaders[i].isFalseColor();
core[i].imageCount = tiffReaders[i].getImageCount();
if (core[i].sizeZ * core[i].sizeT * (core[i].rgb ? 1 : core[i].sizeC) !=
core[i].imageCount)
{
core[i].sizeT = core[i].imageCount / (core[i].rgb ? 1 : core[i].sizeC);
core[i].sizeZ = 1;
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
for (int i=0; i<seriesCount; i++) {
String[] row = rows.get(seriesIndexes.get(i));
// populate Image data
MetadataTools.setDefaultCreationDate(store, mtb, i);
store.setImageName(row[imageName], i);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// populate Dimensions data
// calculate physical X and Y sizes
double realWidth = Double.parseDouble(row[calibratedWidth]);
double realHeight = Double.parseDouble(row[calibratedHeight]);
String units = row[calibrationUnit];
double px = realWidth / core[i].sizeX;
double py = realHeight / core[i].sizeY;
if (units.equals("mm")) {
px *= 1000;
py *= 1000;
}
// TODO : add cases for other units
store.setPixelsPhysicalSizeX(px, i);
store.setPixelsPhysicalSizeY(py, i);
}
}
}
// -- Helper methods --
/**
* Parse an integer from the given dimension String.
*
* @return the parsed integer, or 1 if parsing failed.
*/
private int parseDimension(String dim) {
try {
return Integer.parseInt(dim);
}
catch (NumberFormatException e) {
return 1;
}
}
}
|
// LIFReader.java
package loci.formats.in;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import loci.formats.services.OMEXMLService;
import ome.xml.model.enums.DetectorType;
import ome.xml.model.enums.LaserMedium;
import ome.xml.model.enums.LaserType;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PercentFraction;
import ome.xml.model.primitives.PositiveInteger;
import org.xml.sax.SAXException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class LIFReader extends FormatReader {
// -- Constants --
public static final byte LIF_MAGIC_BYTE = 0x70;
public static final byte LIF_MEMORY_BYTE = 0x2a;
private static final HashMap<String, Integer> CHANNEL_PRIORITIES =
createChannelPriorities();
private static HashMap<String, Integer> createChannelPriorities() {
HashMap<String, Integer> h = new HashMap<String, Integer>();
h.put("red", new Integer(0));
h.put("green", new Integer(1));
h.put("blue", new Integer(2));
h.put("cyan", new Integer(3));
h.put("magenta", new Integer(4));
h.put("yellow", new Integer(5));
h.put("black", new Integer(6));
h.put("gray", new Integer(7));
h.put("", new Integer(8));
return h;
}
// -- Fields --
/** Offsets to memory blocks, paired with their corresponding description. */
private Vector<Long> offsets;
private int[][] realChannel;
private int lastChannel = 0;
private Vector<String> lutNames = new Vector<String>();
private Vector<Double> physicalSizeXs = new Vector<Double>();
private Vector<Double> physicalSizeYs = new Vector<Double>();
private String[] descriptions, microscopeModels, serialNumber;
private Double[] pinholes, zooms, zSteps, tSteps, lensNA;
private Double[][] expTimes, gains;
private Vector[] detectorOffsets;
private String[][] channelNames;
private Vector[] detectorModels, voltages;
private Integer[][] exWaves;
private Vector[] activeDetector;
private HashMap[] detectorIndexes;
private String[] immersions, corrections, objectiveModels;
private Integer[] magnification;
private Double[] posX, posY, posZ;
private Double[] refractiveIndex;
private Vector[] cutIns, cutOuts, filterModels;
private double[][] timestamps;
private Vector[] laserWavelength, laserIntensity;
private ROI[][] imageROIs;
private boolean alternateCenter = false;
private String[] imageNames;
private double[] acquiredDate;
// -- Constructor --
/** Constructs a new Leica LIF reader. */
public LIFReader() {
super("Leica Image File Format", "lif");
suffixNecessary = false;
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return getSizeY();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 1;
if (!FormatTools.validStream(stream, blockLen, true)) return false;
return stream.read() == LIF_MAGIC_BYTE;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null;
if (lastChannel < 0 || lastChannel >= 9) {
return null;
}
byte[][] lut = new byte[3][256];
for (int i=0; i<256; i++) {
switch (lastChannel) {
case 0:
// red
lut[0][i] = (byte) (i & 0xff);
break;
case 1:
// green
lut[1][i] = (byte) (i & 0xff);
break;
case 2:
// blue
lut[2][i] = (byte) (i & 0xff);
break;
case 3:
// cyan
lut[1][i] = (byte) (i & 0xff);
lut[2][i] = (byte) (i & 0xff);
break;
case 4:
// magenta
lut[0][i] = (byte) (i & 0xff);
lut[2][i] = (byte) (i & 0xff);
break;
case 5:
// yellow
lut[0][i] = (byte) (i & 0xff);
lut[1][i] = (byte) (i & 0xff);
break;
default:
// gray
lut[0][i] = (byte) (i & 0xff);
lut[1][i] = (byte) (i & 0xff);
lut[2][i] = (byte) (i & 0xff);
}
}
return lut;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null;
if (lastChannel < 0 || lastChannel >= 9) {
return null;
}
short[][] lut = new short[3][65536];
for (int i=0; i<65536; i++) {
switch (lastChannel) {
case 0:
// red
lut[0][i] = (short) (i & 0xffff);
break;
case 1:
// green
lut[1][i] = (short) (i & 0xffff);
break;
case 2:
// blue
lut[2][i] = (short) (i & 0xffff);
break;
case 3:
// cyan
lut[1][i] = (short) (i & 0xffff);
lut[2][i] = (short) (i & 0xffff);
break;
case 4:
// magenta
lut[0][i] = (short) (i & 0xffff);
lut[2][i] = (short) (i & 0xffff);
break;
case 5:
// yellow
lut[0][i] = (short) (i & 0xffff);
lut[1][i] = (short) (i & 0xffff);
break;
default:
// gray
lut[0][i] = (short) (i & 0xffff);
lut[1][i] = (short) (i & 0xffff);
lut[2][i] = (short) (i & 0xffff);
}
}
return lut;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
if (!isRGB()) {
int[] pos = getZCTCoords(no);
lastChannel = realChannel[series][pos[1]];
}
if (series >= offsets.size()) {
// truncated file; imitate LAS AF and return black planes
Arrays.fill(buf, (byte) 0);
return buf;
}
long offset = offsets.get(series).longValue();
int bytes = FormatTools.getBytesPerPixel(getPixelType());
int bpp = bytes * getRGBChannelCount();
long planeSize = (long) getSizeX() * getSizeY() * bpp;
long nextOffset = series + 1 < offsets.size() ?
offsets.get(series + 1).longValue() : in.length();
int bytesToSkip = (int) (nextOffset - offset - planeSize * getImageCount());
bytesToSkip /= getSizeY();
if ((getSizeX() % 4) == 0) bytesToSkip = 0;
if (offset + (planeSize + bytesToSkip * getSizeY()) * no >= in.length()) {
// truncated file; imitate LAS AF and return black planes
Arrays.fill(buf, (byte) 0);
return buf;
}
in.seek(offset + planeSize * no);
in.skipBytes(bytesToSkip * getSizeY() * no);
if (bytesToSkip == 0) {
readPlane(in, x, y, w, h, buf);
}
else {
in.skipBytes(y * (getSizeX() * bpp + bytesToSkip));
for (int row=0; row<h; row++) {
in.skipBytes(x * bpp);
in.read(buf, row * w * bpp, w * bpp);
in.skipBytes(bpp * (getSizeX() - w - x) + bytesToSkip);
}
}
// color planes are stored in BGR order
if (getRGBChannelCount() == 3) {
ImageTools.bgrToRgb(buf, isInterleaved(), bytes, getRGBChannelCount());
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
offsets = null;
realChannel = null;
lastChannel = 0;
lutNames.clear();
physicalSizeXs.clear();
physicalSizeYs.clear();
descriptions = microscopeModels = serialNumber = null;
pinholes = zooms = lensNA = null;
zSteps = tSteps = null;
expTimes = gains = null;
detectorOffsets = null;
channelNames = null;
detectorModels = voltages = null;
exWaves = null;
activeDetector = null;
immersions = corrections = null;
magnification = null;
objectiveModels = null;
posX = posY = posZ = null;
refractiveIndex = null;
cutIns = cutOuts = filterModels = null;
timestamps = null;
laserWavelength = laserIntensity = null;
imageROIs = null;
alternateCenter = false;
imageNames = null;
acquiredDate = null;
detectorIndexes = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
offsets = new Vector<Long>();
in.order(true);
// read the header
LOGGER.info("Reading header");
byte checkOne = in.readByte();
in.skipBytes(2);
byte checkTwo = in.readByte();
if (checkOne != LIF_MAGIC_BYTE && checkTwo != LIF_MAGIC_BYTE) {
throw new FormatException(id + " is not a valid Leica LIF file");
}
in.skipBytes(4);
// read and parse the XML description
if (in.read() != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid XML description");
}
// number of Unicode characters in the XML block
int nc = in.readInt();
String xml = DataTools.stripString(in.readString(nc * 2));
LOGGER.info("Finding image offsets");
while (in.getFilePointer() < in.length()) {
LOGGER.debug("Looking for a block at {}; {} blocks read",
in.getFilePointer(), offsets.size());
int check = in.readInt();
if (check != LIF_MAGIC_BYTE) {
throw new FormatException("Invalid Memory Block: found magic bytes " +
check + ", expected " + LIF_MAGIC_BYTE);
}
in.skipBytes(4);
check = in.read();
if (check != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid Memory Description: found magic " +
"byte " + check + ", expected " + LIF_MEMORY_BYTE);
}
long blockLength = in.readInt();
if (in.read() != LIF_MEMORY_BYTE) {
in.seek(in.getFilePointer() - 5);
blockLength = in.readLong();
check = in.read();
if (check != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid Memory Description: found magic " +
"byte " + check + ", expected " + LIF_MEMORY_BYTE);
}
}
int descrLength = in.readInt() * 2;
if (blockLength > 0) {
offsets.add(new Long(in.getFilePointer() + descrLength));
}
in.seek(in.getFilePointer() + descrLength + blockLength);
}
initMetadata(xml);
xml = null;
// correct offsets, if necessary
if (offsets.size() > getSeriesCount()) {
Long[] storedOffsets = offsets.toArray(new Long[offsets.size()]);
offsets.clear();
int index = 0;
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
long nBytes = (long) FormatTools.getPlaneSize(this) * getImageCount();
long start = storedOffsets[index];
long end = index == storedOffsets.length - 1 ? in.length() :
storedOffsets[index + 1];
while (end - start < nBytes && ((end - start) / nBytes) != 1) {
index++;
start = storedOffsets[index];
end = index == storedOffsets.length - 1 ? in.length() :
storedOffsets[index + 1];
}
offsets.add(storedOffsets[index]);
index++;
}
setSeries(0);
}
}
// -- Helper methods --
/** Parses a string of XML and puts the values in a Hashtable. */
private void initMetadata(String xml) throws FormatException, IOException {
IMetadata omexml = null;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
omexml = service.createOMEXMLMetadata();
}
catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
MetadataStore store = makeFilterMetadata();
MetadataLevel level = getMetadataOptions().getMetadataLevel();
// the XML blocks stored in a LIF file are invalid,
// because they don't have a root node
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml +
"</LEICA>";
xml = XMLTools.sanitizeXML(xml);
translateMetadata(getMetadataRoot(xml));
for (int i=0; i<imageNames.length; i++) {
setSeries(i);
addSeriesMeta("Image name", imageNames[i]);
}
setSeries(0);
// set up mapping to rearrange channels
// for instance, the green channel may be #0, and the red channel may be #1
realChannel = new int[getSeriesCount()][];
int nextLut = 0;
for (int i=0; i<getSeriesCount(); i++) {
realChannel[i] = new int[core[i].sizeC];
for (int q=0; q<core[i].sizeC; q++) {
String lut = lutNames.get(nextLut++).toLowerCase();
if (!CHANNEL_PRIORITIES.containsKey(lut)) lut = "";
realChannel[i][q] = CHANNEL_PRIORITIES.get(lut).intValue();
}
int[] sorted = new int[core[i].sizeC];
Arrays.fill(sorted, -1);
for (int q=0; q<sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n=0; n<core[i].sizeC; n++) {
if (realChannel[i][n] < min && !DataTools.containsValue(sorted, n)) {
min = realChannel[i][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
}
MetadataTools.populatePixels(store, this, true, false);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
store.setMicroscopeModel(microscopeModels[i], i);
store.setMicroscopeType(getMicroscopeType("Other"), i);
String objectiveID = MetadataTools.createLSID("Objective", i, 0);
store.setObjectiveID(objectiveID, i, 0);
store.setObjectiveLensNA(lensNA[i], i, 0);
store.setObjectiveSerialNumber(serialNumber[i], i, 0);
if (magnification[i] != null && magnification[i] > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification[i]), i, 0);
}
store.setObjectiveImmersion(getImmersion(immersions[i]), i, 0);
store.setObjectiveCorrection(getCorrection(corrections[i]), i, 0);
store.setObjectiveModel(objectiveModels[i], i, 0);
if (cutIns[i] != null) {
for (int filter=0; filter<cutIns[i].size(); filter++) {
String filterID = MetadataTools.createLSID("Filter", i, filter);
store.setFilterID(filterID, i, filter);
if (filter < filterModels[i].size()) {
store.setFilterModel(
(String) filterModels[i].get(filter), i, filter);
}
int channel = filter - (cutIns[i].size() - getEffectiveSizeC());
if (channel >= 0 && channel < getEffectiveSizeC()) {
//store.setLightPathEmissionFilterRef(filterID, i, channel, 0);
}
store.setTransmittanceRangeCutIn(
(PositiveInteger) cutIns[i].get(filter), i, filter);
store.setTransmittanceRangeCutOut(
(PositiveInteger) cutOuts[i].get(filter), i, filter);
}
}
Vector lasers = laserWavelength[i];
Vector laserIntensities = laserIntensity[i];
int nextChannel = 0;
if (lasers != null) {
int laserIndex = 0;
while (laserIndex < lasers.size()) {
if ((Integer) lasers.get(laserIndex) == 0) {
lasers.removeElementAt(laserIndex);
}
else {
laserIndex++;
}
}
for (int laser=0; laser<lasers.size(); laser++) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setLaserID(id, i, laser);
store.setLaserType(LaserType.OTHER, i, laser);
store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
Integer wavelength = (Integer) lasers.get(laser);
if (wavelength > 0) {
store.setLaserWavelength(new PositiveInteger(wavelength), i, laser);
}
}
Vector<Integer> validIntensities = new Vector<Integer>();
for (int laser=0; laser<laserIntensities.size(); laser++) {
double intensity = (Double) laserIntensities.get(laser);
if (intensity < 100) {
validIntensities.add(laser);
}
}
int start = validIntensities.size() - getEffectiveSizeC();
if (start < 0) {
start = 0;
}
boolean noNames = true;
for (String name : channelNames[i]) {
if (name != null && !name.equals("")) {
noNames = false;
break;
}
}
for (int k=start; k<validIntensities.size(); k++, nextChannel++) {
int index = validIntensities.get(k);
double intensity = (Double) laserIntensities.get(index);
int laser = index % lasers.size();
Integer wavelength = (Integer) lasers.get(laser);
if (wavelength != 0) {
while (channelNames != null && nextChannel < getEffectiveSizeC() &&
((channelNames[i][nextChannel] == null ||
channelNames[i][nextChannel].equals("")) && !noNames))
{
nextChannel++;
}
if (nextChannel < getEffectiveSizeC()) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setChannelLightSourceSettingsID(id, i, nextChannel);
store.setChannelLightSourceSettingsAttenuation(
new PercentFraction((float) intensity / 100f), i, nextChannel);
store.setChannelExcitationWavelength(
new PositiveInteger(wavelength), i, nextChannel);
}
}
}
}
store.setImageInstrumentRef(instrumentID, i);
store.setImageObjectiveSettingsID(objectiveID, i);
store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex[i], i);
store.setImageDescription(descriptions[i], i);
if (acquiredDate[i] > 0) {
store.setImageAcquiredDate(DateTools.convertDate(
(long) (acquiredDate[i] * 1000), DateTools.COBOL), i);
}
store.setImageName(imageNames[i].trim(), i);
if (physicalSizeXs.get(i) > 0) {
store.setPixelsPhysicalSizeX(
new PositiveFloat(physicalSizeXs.get(i)), i);
}
if (physicalSizeYs.get(i) > 0) {
store.setPixelsPhysicalSizeY(
new PositiveFloat(physicalSizeYs.get(i)), i);
}
if (zSteps[i] != null && zSteps[i] > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(zSteps[i]), i);
}
store.setPixelsTimeIncrement(tSteps[i], i);
Vector detectors = detectorModels[i];
if (detectors != null) {
nextChannel = 0;
for (int detector=0; detector<detectors.size(); detector++) {
String detectorID = MetadataTools.createLSID("Detector", i, detector);
store.setDetectorID(detectorID, i, detector);
store.setDetectorModel((String) detectors.get(detector), i, detector);
store.setDetectorZoom(zooms[i], i, detector);
store.setDetectorType(DetectorType.PMT, i, detector);
if (voltages[i] != null && detector < voltages[i].size()) {
store.setDetectorVoltage(
(Double) voltages[i].get(detector), i, detector);
}
if (activeDetector[i] != null) {
if (detector < activeDetector[i].size() &&
(Boolean) activeDetector[i].get(detector) &&
detectorOffsets[i] != null &&
nextChannel < detectorOffsets[i].size())
{
store.setDetectorOffset(
(Double) detectorOffsets[i].get(nextChannel++), i, detector);
}
}
}
}
Vector activeDetectors = activeDetector[i];
int firstDetector = activeDetectors == null ? 0 :
activeDetectors.size() - getEffectiveSizeC();
int nextDetector = firstDetector;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (activeDetectors != null) {
while (nextDetector >= 0 && nextDetector < activeDetectors.size() &&
!(Boolean) activeDetectors.get(nextDetector))
{
nextDetector++;
}
if (nextDetector < activeDetectors.size() && detectors != null &&
nextDetector - firstDetector < detectors.size())
{
String detectorID = MetadataTools.createLSID(
"Detector", i, nextDetector - firstDetector);
store.setDetectorSettingsID(detectorID, i, c);
nextDetector++;
if (detectorOffsets[i] != null && c < detectorOffsets[i].size()) {
store.setDetectorSettingsOffset(
(Double) detectorOffsets[i].get(c), i, c);
}
if (gains[i] != null) {
store.setDetectorSettingsGain(gains[i][c], i, c);
}
}
}
if (channelNames[i] != null) {
store.setChannelName(channelNames[i][c], i, c);
}
store.setChannelPinholeSize(pinholes[i], i, c);
if (exWaves[i] != null && exWaves[i][c] != null && exWaves[i][c] > 1) {
store.setChannelExcitationWavelength(
new PositiveInteger(exWaves[i][c]), i, c);
}
if (expTimes[i] != null) {
store.setPlaneExposureTime(expTimes[i][c], i, c);
}
}
for (int image=0; image<getImageCount(); image++) {
store.setPlanePositionX(posX[i], i, image);
store.setPlanePositionY(posY[i], i, image);
store.setPlanePositionZ(posZ[i], i, image);
if (timestamps[i] != null) {
double timestamp = timestamps[i][image];
if (timestamps[i][0] == acquiredDate[i]) {
timestamp -= acquiredDate[i];
}
else if (timestamp == acquiredDate[i] && image > 0) {
timestamp = timestamps[i][0];
}
store.setPlaneDeltaT(timestamp, i, image);
}
}
if (imageROIs[i] != null) {
for (int roi=0; roi<imageROIs[i].length; roi++) {
if (imageROIs[i][roi] != null) {
imageROIs[i][roi].storeROI(store, i, roi);
}
}
}
}
}
private Element getMetadataRoot(String xml)
throws FormatException, IOException
{
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes());
Element root = parser.parse(s).getDocumentElement();
s.close();
return root;
}
catch (ParserConfigurationException e) {
throw new FormatException(e);
}
catch (SAXException e) {
throw new FormatException(e);
}
}
private void translateMetadata(Element root) throws FormatException {
Element realRoot = (Element) root.getChildNodes().item(0);
NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master");
if (toPrune != null) {
for (int i=0; i<toPrune.getLength(); i++) {
Element prune = (Element) toPrune.item(i);
Element parent = (Element) prune.getParentNode();
parent.removeChild(prune);
}
}
NodeList imageNodes = getNodes(realRoot, "Image");
core = new CoreMetadata[imageNodes.getLength()];
acquiredDate = new double[imageNodes.getLength()];
descriptions = new String[imageNodes.getLength()];
laserWavelength = new Vector[imageNodes.getLength()];
laserIntensity = new Vector[imageNodes.getLength()];
timestamps = new double[imageNodes.getLength()][];
activeDetector = new Vector[imageNodes.getLength()];
voltages = new Vector[imageNodes.getLength()];
detectorOffsets = new Vector[imageNodes.getLength()];
serialNumber = new String[imageNodes.getLength()];
lensNA = new Double[imageNodes.getLength()];
magnification = new Integer[imageNodes.getLength()];
immersions = new String[imageNodes.getLength()];
corrections = new String[imageNodes.getLength()];
objectiveModels = new String[imageNodes.getLength()];
posX = new Double[imageNodes.getLength()];
posY = new Double[imageNodes.getLength()];
posZ = new Double[imageNodes.getLength()];
refractiveIndex = new Double[imageNodes.getLength()];
cutIns = new Vector[imageNodes.getLength()];
cutOuts = new Vector[imageNodes.getLength()];
filterModels = new Vector[imageNodes.getLength()];
microscopeModels = new String[imageNodes.getLength()];
detectorModels = new Vector[imageNodes.getLength()];
detectorIndexes = new HashMap[imageNodes.getLength()];
zSteps = new Double[imageNodes.getLength()];
tSteps = new Double[imageNodes.getLength()];
pinholes = new Double[imageNodes.getLength()];
zooms = new Double[imageNodes.getLength()];
expTimes = new Double[imageNodes.getLength()][];
gains = new Double[imageNodes.getLength()][];
channelNames = new String[imageNodes.getLength()][];
exWaves = new Integer[imageNodes.getLength()][];
imageROIs = new ROI[imageNodes.getLength()][];
imageNames = new String[imageNodes.getLength()];
for (int i=0; i<imageNodes.getLength(); i++) {
Element image = (Element) imageNodes.item(i);
setSeries(i);
translateImageNames(image, i);
translateImageNodes(image, i);
translateAttachmentNodes(image, i);
translateScannerSettings(image, i);
translateFilterSettings(image, i);
translateTimestamps(image, i);
translateLaserLines(image, i);
translateROIs(image, i);
translateSingleROIs(image, i);
translateDetectors(image, i);
Stack<String> nameStack = new Stack<String>();
HashMap<String, Integer> indexes = new HashMap<String, Integer>();
populateOriginalMetadata(image, nameStack, indexes);
indexes.clear();
}
setSeries(0);
}
private void populateOriginalMetadata(Element root, Stack<String> nameStack,
HashMap<String, Integer> indexes)
{
String name = root.getNodeName();
if (root.hasAttributes() && !name.equals("Element") &&
!name.equals("Attachment") && !name.equals("LMSDataContainerHeader"))
{
nameStack.push(name);
String suffix = root.getAttribute("Identifier");
String value = root.getAttribute("Variant");
if (suffix == null || suffix.trim().length() == 0) {
suffix = root.getAttribute("Description");
}
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
if (suffix != null && value != null && suffix.length() > 0 &&
value.length() > 0 && !suffix.equals("HighInteger") &&
!suffix.equals("LowInteger"))
{
Integer i = indexes.get(key.toString() + suffix);
String storedKey = key.toString() + suffix + " " + (i == null ? 0 : i);
indexes.put(key.toString() + suffix, i == null ? 1 : i + 1);
addSeriesMeta(storedKey, value);
}
else {
NamedNodeMap attributes = root.getAttributes();
for (int i=0; i<attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
if (!attr.getName().equals("HighInteger") &&
!attr.getName().equals("LowInteger"))
{
Integer index = indexes.get(key.toString() + attr.getName());
if (index == null) {
index = 0;
}
String storedKey = key.toString() + attr.getName() + " " + index;
indexes.put(key.toString() + attr.getName(), index + 1);
addSeriesMeta(storedKey, attr.getValue());
}
}
}
}
NodeList children = root.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Object child = children.item(i);
if (child instanceof Element) {
populateOriginalMetadata((Element) child, nameStack, indexes);
}
}
if (root.hasAttributes() && !name.equals("Element") &&
!name.equals("Attachment") && !name.equals("LMSDataContainerHeader"))
{
nameStack.pop();
}
}
private void translateImageNames(Element imageNode, int image) {
Vector<String> names = new Vector<String>();
Element parent = imageNode;
while (true) {
parent = (Element) parent.getParentNode();
if (parent == null || parent.getNodeName().equals("LEICA")) {
break;
}
if (parent.getNodeName().equals("Element")) {
names.add(parent.getAttribute("Name"));
}
}
imageNames[image] = "";
for (int i=names.size() - 2; i>=0; i
imageNames[image] += names.get(i);
if (i > 0) imageNames[image] += "/";
}
}
private void translateDetectors(Element imageNode, int image)
throws FormatException
{
NodeList definitions = getNodes(imageNode, "ATLConfocalSettingDefinition");
if (definitions == null) return;
Vector<String> channels = new Vector<String>();
int nextChannel = 0;
for (int definition=0; definition<definitions.getLength(); definition++) {
Element definitionNode = (Element) definitions.item(definition);
NodeList detectors = getNodes(definitionNode, "Detector");
if (detectors == null) return;
for (int d=0; d<detectors.getLength(); d++) {
Element detector = (Element) detectors.item(d);
NodeList multibands = getNodes(definitionNode, "MultiBand");
String v = detector.getAttribute("Gain");
Double gain =
v == null || v.trim().length() == 0 ? null : new Double(v);
v = detector.getAttribute("Offset");
Double offset =
v == null || v.trim().length() == 0 ? null : new Double(v);
boolean active = "1".equals(detector.getAttribute("IsActive"));
if (active) {
String c = detector.getAttribute("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
detectorModels[image].add(detectorIndexes[image].get(channel));
Element multiband = null;
if (multibands != null) {
for (int i=0; i<multibands.getLength(); i++) {
Element mb = (Element) multibands.item(i);
if (channel == Integer.parseInt(mb.getAttribute("Channel"))) {
multiband = mb;
break;
}
}
}
if (multiband != null) {
channels.add(multiband.getAttribute("DyeName"));
double cutIn = new Double(multiband.getAttribute("LeftWorld"));
double cutOut = new Double(multiband.getAttribute("RightWorld"));
cutIns[image].add(new PositiveInteger((int) Math.round(cutIn)));
cutOuts[image].add(new PositiveInteger((int) Math.round(cutOut)));
}
else {
channels.add("");
}
if (nextChannel < getEffectiveSizeC()) {
gains[image][nextChannel] = gain;
detectorOffsets[image].add(offset);
}
nextChannel++;
}
if (active) {
activeDetector[image].add(active);
}
}
}
for (int i=0; i<getEffectiveSizeC(); i++) {
int index = i + channels.size() - getEffectiveSizeC();
if (index >= 0 && index < channels.size()) {
channelNames[image][i] = channels.get(index);
}
}
}
private void translateROIs(Element imageNode, int image)
throws FormatException
{
NodeList rois = getNodes(imageNode, "Annotation");
if (rois == null) return;
imageROIs[image] = new ROI[rois.getLength()];
for (int r=0; r<rois.getLength(); r++) {
Element roiNode = (Element) rois.item(r);
ROI roi = new ROI();
String type = roiNode.getAttribute("type");
if (type != null) {
roi.type = Integer.parseInt(type);
}
String color = roiNode.getAttribute("color");
if (color != null) {
roi.color = Long.parseLong(color);
}
roi.name = roiNode.getAttribute("name");
roi.fontName = roiNode.getAttribute("fontName");
roi.fontSize = roiNode.getAttribute("fontSize");
roi.transX = parseDouble(roiNode.getAttribute("transTransX"));
roi.transY = parseDouble(roiNode.getAttribute("transTransY"));
roi.scaleX = parseDouble(roiNode.getAttribute("transScalingX"));
roi.scaleY = parseDouble(roiNode.getAttribute("transScalingY"));
roi.rotation = parseDouble(roiNode.getAttribute("transRotation"));
String linewidth = roiNode.getAttribute("linewidth");
if (linewidth != null) {
try {
roi.linewidth = Integer.parseInt(linewidth);
}
catch (NumberFormatException e) { }
}
roi.text = roiNode.getAttribute("text");
NodeList vertices = getNodes(roiNode, "Vertex");
if (vertices == null) {
continue;
}
for (int v=0; v<vertices.getLength(); v++) {
Element vertex = (Element) vertices.item(v);
String xx = vertex.getAttribute("x");
String yy = vertex.getAttribute("y");
if (xx != null) {
roi.x.add(parseDouble(xx));
}
if (yy != null) {
roi.y.add(parseDouble(yy));
}
}
imageROIs[image][r] = roi;
if (getNodes(imageNode, "ROI") != null) {
alternateCenter = true;
}
}
}
private void translateSingleROIs(Element imageNode, int image)
throws FormatException
{
if (imageROIs[image] != null) return;
NodeList children = getNodes(imageNode, "ROI");
if (children == null) return;
children = getNodes((Element) children.item(0), "Children");
if (children == null) return;
children = getNodes((Element) children.item(0), "Element");
if (children == null) return;
imageROIs[image] = new ROI[children.getLength()];
for (int r=0; r<children.getLength(); r++) {
NodeList rois = getNodes((Element) children.item(r), "ROISingle");
Element roiNode = (Element) rois.item(0);
ROI roi = new ROI();
String type = roiNode.getAttribute("RoiType");
if (type != null) {
roi.type = Integer.parseInt(type);
}
String color = roiNode.getAttribute("Color");
if (color != null) {
roi.color = Long.parseLong(color);
}
Element parent = (Element) roiNode.getParentNode();
parent = (Element) parent.getParentNode();
roi.name = parent.getAttribute("Name");
NodeList vertices = getNodes(roiNode, "P");
double sizeX = physicalSizeXs.get(image);
double sizeY = physicalSizeYs.get(image);
for (int v=0; v<vertices.getLength(); v++) {
Element vertex = (Element) vertices.item(v);
String xx = vertex.getAttribute("X");
String yy = vertex.getAttribute("Y");
if (xx != null) {
roi.x.add(parseDouble(xx) / sizeX);
}
if (yy != null) {
roi.y.add(parseDouble(yy) / sizeY);
}
}
Element transform = (Element) getNodes(roiNode, "Transformation").item(0);
roi.rotation = parseDouble(transform.getAttribute("Rotation"));
Element scaling = (Element) getNodes(transform, "Scaling").item(0);
roi.scaleX = parseDouble(scaling.getAttribute("XScale"));
roi.scaleY = parseDouble(scaling.getAttribute("YScale"));
Element translation =
(Element) getNodes(transform, "Translation").item(0);
roi.transX = parseDouble(translation.getAttribute("X")) / sizeX;
roi.transY = parseDouble(translation.getAttribute("Y")) / sizeY;
imageROIs[image][r] = roi;
}
}
private void translateLaserLines(Element imageNode, int image)
throws FormatException
{
NodeList aotfLists = getNodes(imageNode, "AotfList");
if (aotfLists == null) return;
laserWavelength[image] = new Vector<Integer>();
laserIntensity[image] = new Vector<Double>();
int baseIntensityIndex = 0;
for (int channel=0; channel<aotfLists.getLength(); channel++) {
Element aotf = (Element) aotfLists.item(channel);
NodeList laserLines = getNodes(aotf, "LaserLineSetting");
if (laserLines == null) return;
for (int laser=0; laser<laserLines.getLength(); laser++) {
Element laserLine = (Element) laserLines.item(laser);
String lineIndex = laserLine.getAttribute("LineIndex");
String qual = laserLine.getAttribute("Qualifier");
int index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0: Integer.parseInt(qual);
index += (2 - (qualifier / 10));
if (index < 0) index = 0;
Integer wavelength = new Integer(laserLine.getAttribute("LaserLine"));
if (index < laserWavelength[image].size()) {
laserWavelength[image].setElementAt(wavelength, index);
}
else {
for (int i=laserWavelength[image].size(); i<index; i++) {
laserWavelength[image].add(new Integer(0));
}
laserWavelength[image].add(wavelength);
}
String intensity = laserLine.getAttribute("IntensityDev");
double realIntensity = intensity == null ? 0d : new Double(intensity);
realIntensity = 100d - realIntensity;
int realIndex = baseIntensityIndex + index;
if (realIndex < laserIntensity[image].size()) {
laserIntensity[image].setElementAt(realIntensity, realIndex);
}
else {
while (realIndex < laserIntensity[image].size()) {
laserIntensity[image].add(100d);
}
laserIntensity[image].add(realIntensity);
}
}
baseIntensityIndex += laserWavelength[image].size();
}
}
private void translateTimestamps(Element imageNode, int image)
throws FormatException
{
NodeList timestampNodes = getNodes(imageNode, "TimeStamp");
if (timestampNodes == null) return;
timestamps[image] = new double[getImageCount()];
if (timestampNodes != null) {
for (int stamp=0; stamp<timestampNodes.getLength(); stamp++) {
if (stamp < getImageCount()) {
Element timestamp = (Element) timestampNodes.item(stamp);
String stampHigh = timestamp.getAttribute("HighInteger");
String stampLow = timestamp.getAttribute("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
timestamps[image][stamp] = ms / 1000.0;
}
}
}
acquiredDate[image] = timestamps[image][0];
NodeList relTimestampNodes = getNodes(imageNode, "RelTimeStamp");
if (relTimestampNodes != null) {
for (int stamp=0; stamp<relTimestampNodes.getLength(); stamp++) {
if (stamp < getImageCount()) {
Element timestamp = (Element) relTimestampNodes.item(stamp);
timestamps[image][stamp] =
new Double(timestamp.getAttribute("Time"));
}
}
}
}
private void translateFilterSettings(Element imageNode, int image)
throws FormatException
{
NodeList filterSettings = getNodes(imageNode, "FilterSettingRecord");
if (filterSettings == null) return;
activeDetector[image] = new Vector<Boolean>();
voltages[image] = new Vector<Double>();
detectorOffsets[image] = new Vector<Double>();
cutIns[image] = new Vector<PositiveInteger>();
cutOuts[image] = new Vector<PositiveInteger>();
filterModels[image] = new Vector<String>();
detectorIndexes[image] = new HashMap<Integer, String>();
for (int i=0; i<filterSettings.getLength(); i++) {
Element filterSetting = (Element) filterSettings.item(i);
String object = filterSetting.getAttribute("ObjectName");
String attribute = filterSetting.getAttribute("Attribute");
String objectClass = filterSetting.getAttribute("ClassName");
String variant = filterSetting.getAttribute("Variant");
String data = filterSetting.getAttribute("Data");
if (attribute.equals("NumericalAperture")) {
lensNA[image] = new Double(variant);
}
else if (attribute.equals("OrderNumber")) {
serialNumber[image] = variant;
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
detectorIndexes[image].put(new Integer(data), object);
activeDetector[image].add(variant.equals("Active"));
}
else if (attribute.equals("HighVoltage")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
if (channel < voltages[image].size()) {
voltages[image].setElementAt(new Double(variant), channel);
}
else {
while (channel > voltages[image].size()) {
voltages[image].add(new Double(0));
}
voltages[image].add(new Double(variant));
}
}
else if (attribute.equals("VideoOffset")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
detectorOffsets[image].add(new Double(variant));
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
magnification[image] = mag;
lensNA[image] = new Double(na);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Other";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Other";
}
}
immersions[image] = immersion;
String correction = "Other";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Other";
}
}
corrections[image] = correction;
objectiveModels[image] = model.toString().trim();
}
else if (attribute.equals("RefractionIndex")) {
refractiveIndex[image] = new Double(variant);
}
else if (attribute.equals("XPos")) {
posX[image] = new Double(variant);
}
else if (attribute.equals("YPos")) {
posY[image] = new Double(variant);
}
else if (attribute.equals("ZPos")) {
posZ[image] = new Double(variant);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
String description = filterSetting.getAttribute("Description");
if (description.endsWith("(left)")) {
filterModels[image].add(object);
if (v != null) {
cutIns[image].add(new PositiveInteger(v));
}
}
else if (description.endsWith("(right)")) {
if (v != null) {
cutOuts[image].add(new PositiveInteger(v));
}
}
}
}
}
private void translateScannerSettings(Element imageNode, int image)
throws FormatException
{
NodeList scannerSettings = getNodes(imageNode, "ScannerSettingRecord");
if (scannerSettings == null) return;
expTimes[image] = new Double[getEffectiveSizeC()];
gains[image] = new Double[getEffectiveSizeC()];
channelNames[image] = new String[getEffectiveSizeC()];
exWaves[image] = new Integer[getEffectiveSizeC()];
detectorModels[image] = new Vector<String>();
for (int i=0; i<scannerSettings.getLength(); i++) {
Element scannerSetting = (Element) scannerSettings.item(i);
String id = scannerSetting.getAttribute("Identifier");
if (id == null) id = "";
String suffix = scannerSetting.getAttribute("Identifier");
String value = scannerSetting.getAttribute("Variant");
if (id.equals("SystemType")) {
microscopeModels[image] = value;
}
else if (id.equals("dblPinhole")) {
pinholes[image] = Double.parseDouble(value) * 1000000;
}
else if (id.equals("dblZoom")) {
zooms[image] = new Double(value);
}
else if (id.equals("dblStepSize")) {
zSteps[image] = Double.parseDouble(value) * 1000000;
}
else if (id.equals("nDelayTime_s")) {
tSteps[image] = new Double(value);
}
else if (id.equals("CameraName")) {
detectorModels[image].add(value);
}
else if (id.equals("eDirectional")) {
addSeriesMeta("Reverse X orientation", value.equals("1"));
}
else if (id.equals("eDirectionalY")) {
addSeriesMeta("Reverse Y orientation", value.equals("1"));
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (c < 0 || c >= getEffectiveSizeC()) {
continue;
}
if (id.endsWith("ExposureTime")) {
expTimes[image][c] = new Double(value);
}
else if (id.endsWith("Gain")) {
gains[image][c] = new Double(value);
}
else if (id.endsWith("WaveLength")) {
Integer exWave = new Integer(value);
if (exWave > 0) {
exWaves[image][c] = exWave;
}
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
channelNames[image][c] = value;
}
}
}
}
private void translateAttachmentNodes(Element imageNode, int image)
throws FormatException
{
NodeList attachmentNodes = getNodes(imageNode, "Attachment");
if (attachmentNodes == null) return;
for (int i=0; i<attachmentNodes.getLength(); i++) {
Element attachment = (Element) attachmentNodes.item(i);
if ("ContextDescription".equals(attachment.getAttribute("Name"))) {
descriptions[image] = attachment.getAttribute("Content");
}
}
}
private void translateImageNodes(Element imageNode, int i)
throws FormatException
{
core[i] = new CoreMetadata();
core[i].orderCertain = true;
core[i].metadataComplete = true;
core[i].littleEndian = true;
core[i].falseColor = true;
NodeList channels = getChannelDescriptionNodes(imageNode);
NodeList dimensions = getDimensionDescriptionNodes(imageNode);
HashMap<Long, String> bytesPerAxis = new HashMap<Long, String>();
Double physicalSizeX = null;
Double physicalSizeY = null;
core[i].sizeC = channels.getLength();
for (int ch=0; ch<channels.getLength(); ch++) {
Element channel = (Element) channels.item(ch);
lutNames.add(channel.getAttribute("LUTName"));
String bytesInc = channel.getAttribute("BytesInc");
long bytes = bytesInc == null ? 0 : Long.parseLong(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(bytes, "C");
}
}
int extras = 1;
for (int dim=0; dim<dimensions.getLength(); dim++) {
Element dimension = (Element) dimensions.item(dim);
int id = Integer.parseInt(dimension.getAttribute("DimID"));
int len = Integer.parseInt(dimension.getAttribute("NumberOfElements"));
long nBytes = Long.parseLong(dimension.getAttribute("BytesInc"));
Double physicalLen = new Double(dimension.getAttribute("Length"));
String unit = dimension.getAttribute("Unit");
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
switch (id) {
case 1: // X axis
core[i].sizeX = len;
core[i].rgb = (nBytes % 3) == 0;
if (core[i].rgb) nBytes /= 3;
core[i].pixelType =
FormatTools.pixelTypeFromBytes((int) nBytes, false, true);
physicalSizeX = physicalLen;
break;
case 2: // Y axis
if (core[i].sizeY != 0) {
if (core[i].sizeZ == 1) {
core[i].sizeZ = len;
bytesPerAxis.put(nBytes, "Z");
}
else if (core[i].sizeT == 1) {
core[i].sizeT = len;
bytesPerAxis.put(nBytes, "T");
}
}
else {
core[i].sizeY = len;
physicalSizeY = physicalLen;
}
break;
case 3: // Z axis
if (core[i].sizeY == 0) {
// XZ scan - swap Y and Z
core[i].sizeY = len;
core[i].sizeZ = 1;
bytesPerAxis.put(nBytes, "Y");
physicalSizeY = physicalLen;
}
else {
core[i].sizeZ = len;
bytesPerAxis.put(nBytes, "Z");
}
break;
case 4: // T axis
if (core[i].sizeY == 0) {
// XT scan - swap Y and T
core[i].sizeY = len;
core[i].sizeT = 1;
bytesPerAxis.put(nBytes, "Y");
physicalSizeY = physicalLen;
}
else {
core[i].sizeT = len;
bytesPerAxis.put(nBytes, "T");
}
break;
default:
extras *= len;
}
}
physicalSizeXs.add(physicalSizeX);
physicalSizeYs.add(physicalSizeY);
if (extras > 1) {
if (core[i].sizeZ == 1) core[i].sizeZ = extras;
else {
if (core[i].sizeT == 0) core[i].sizeT = extras;
else core[i].sizeT *= extras;
}
}
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
core[i].interleaved = core[i].rgb;
core[i].indexed = !core[i].rgb;
core[i].imageCount = core[i].sizeZ * core[i].sizeT;
if (!core[i].rgb) core[i].imageCount *= core[i].sizeC;
Long[] bytes = bytesPerAxis.keySet().toArray(new Long[0]);
Arrays.sort(bytes);
core[i].dimensionOrder = "XY";
for (Long nBytes : bytes) {
String axis = bytesPerAxis.get(nBytes);
if (core[i].dimensionOrder.indexOf(axis) == -1) {
core[i].dimensionOrder += axis;
}
}
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
}
private NodeList getNodes(Element root, String nodeName) {
NodeList nodes = root.getElementsByTagName(nodeName);
if (nodes.getLength() == 0) {
NodeList children = root.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Object child = children.item(i);
if (child instanceof Element) {
NodeList childNodes = getNodes((Element) child, nodeName);
if (childNodes != null) {
return childNodes;
}
}
}
return null;
}
else return nodes;
}
private Element getImageDescription(Element root) {
return (Element) root.getElementsByTagName("ImageDescription").item(0);
}
private NodeList getChannelDescriptionNodes(Element root) {
Element imageDescription = getImageDescription(root);
Element channels =
(Element) imageDescription.getElementsByTagName("Channels").item(0);
return channels.getElementsByTagName("ChannelDescription");
}
private NodeList getDimensionDescriptionNodes(Element root) {
Element imageDescription = getImageDescription(root);
Element channels =
(Element) imageDescription.getElementsByTagName("Dimensions").item(0);
return channels.getElementsByTagName("DimensionDescription");
}
private int getChannelIndex(Element filterSetting) {
String data = filterSetting.getAttribute("data");
if (data == null || data.equals("")) {
data = filterSetting.getAttribute("Data");
}
int channel = data == null || data.equals("") ? 0 : Integer.parseInt(data);
if (channel < 0) return -1;
return channel - 1;
}
// -- Helper class --
class ROI {
// -- Constants --
public static final int TEXT = 512;
public static final int SCALE_BAR = 8192;
public static final int POLYGON = 32;
public static final int RECTANGLE = 16;
public static final int LINE = 256;
public static final int ARROW = 2;
// -- Fields --
public int type;
public Vector<Double> x = new Vector<Double>();
public Vector<Double> y = new Vector<Double>();
// center point of the ROI
public double transX, transY;
// transformation parameters
public double scaleX, scaleY;
public double rotation;
public long color;
public int linewidth;
public String text;
public String fontName;
public String fontSize;
public String name;
private boolean normalized = false;
// -- ROI API methods --
public void storeROI(MetadataStore store, int series, int roi) {
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM)
{
return;
}
// keep in mind that vertices are given relative to the center
// point of the ROI and the transX/transY values are relative to
// the center point of the image
String roiID = MetadataTools.createLSID("ROI", roi);
store.setImageROIRef(roiID, series, roi);
store.setROIID(roiID, roi);
store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0);
if (text == null) {
text = name;
}
store.setTextValue(text, roi, 0);
if (fontSize != null) {
try {
int size = (int) Double.parseDouble(fontSize);
store.setTextFontSize(new NonNegativeInteger(size), roi, 0);
}
catch (NumberFormatException e) { }
}
store.setTextStrokeWidth(new Double(linewidth), roi, 0);
if (!normalized) normalize();
double cornerX = x.get(0).doubleValue();
double cornerY = y.get(0).doubleValue();
store.setTextX(cornerX, roi, 0);
store.setTextY(cornerY, roi, 0);
int centerX = (core[series].sizeX / 2) - 1;
int centerY = (core[series].sizeY / 2) - 1;
double roiX = centerX + transX;
double roiY = centerY + transY;
if (alternateCenter) {
roiX = transX - 2 * cornerX;
roiY = transY - 2 * cornerY;
}
// TODO : rotation/scaling not populated
String shapeID = MetadataTools.createLSID("Shape", roi, 1);
switch (type) {
case POLYGON:
StringBuffer points = new StringBuffer();
for (int i=0; i<x.size(); i++) {
points.append(x.get(i).doubleValue() + roiX);
points.append(",");
points.append(y.get(i).doubleValue() + roiY);
if (i < x.size() - 1) points.append(" ");
}
store.setPolylineID(shapeID, roi, 1);
store.setPolylinePoints(points.toString(), roi, 1);
store.setPolylineClosed(Boolean.TRUE, roi, 1);
break;
case TEXT:
case RECTANGLE:
store.setRectangleID(shapeID, roi, 1);
store.setRectangleX(roiX - Math.abs(cornerX), roi, 1);
store.setRectangleY(roiY - Math.abs(cornerY), roi, 1);
double width = 2 * Math.abs(cornerX);
double height = 2 * Math.abs(cornerY);
store.setRectangleWidth(width, roi, 1);
store.setRectangleHeight(height, roi, 1);
break;
case SCALE_BAR:
case ARROW:
case LINE:
store.setLineID(shapeID, roi, 1);
store.setLineX1(roiX + x.get(0), roi, 1);
store.setLineY1(roiY + y.get(0), roi, 1);
store.setLineX2(roiX + x.get(1), roi, 1);
store.setLineY2(roiY + y.get(1), roi, 1);
break;
}
}
// -- Helper methods --
/**
* Vertices and transformation values are not stored in pixel coordinates.
* We need to convert them from physical coordinates to pixel coordinates
* so that they can be stored in a MetadataStore.
*/
private void normalize() {
if (normalized) return;
// coordinates are in meters
transX *= 1000000;
transY *= 1000000;
transX *= 1;
transY *= 1;
for (int i=0; i<x.size(); i++) {
double coordinate = x.get(i).doubleValue() * 1000000;
coordinate *= 1;
x.setElementAt(coordinate, i);
}
for (int i=0; i<y.size(); i++) {
double coordinate = y.get(i).doubleValue() * 1000000;
coordinate *= 1;
y.setElementAt(coordinate, i);
}
normalized = true;
}
}
private double parseDouble(String number) {
if (number != null) {
number = number.replaceAll(",", ".");
try {
return Double.parseDouble(number);
}
catch (NumberFormatException e) { }
}
return 0;
}
}
|
package io.moquette.spi.impl;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import io.moquette.server.ConnectionDescriptor;
import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.ClientSession;
import io.moquette.spi.IMatchingCondition;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore;
import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import io.moquette.spi.impl.subscriptions.Subscription;
import static io.moquette.parser.netty.Utils.VERSION_3_1;
import static io.moquette.parser.netty.Utils.VERSION_3_1_1;
import io.moquette.proto.messages.AbstractMessage;
import io.moquette.proto.messages.AbstractMessage.QOSType;
import io.moquette.proto.messages.ConnAckMessage;
import io.moquette.proto.messages.ConnectMessage;
import io.moquette.proto.messages.PubAckMessage;
import io.moquette.proto.messages.PubCompMessage;
import io.moquette.proto.messages.PubRecMessage;
import io.moquette.proto.messages.PubRelMessage;
import io.moquette.proto.messages.PublishMessage;
import io.moquette.proto.messages.SubAckMessage;
import io.moquette.proto.messages.SubscribeMessage;
import io.moquette.proto.messages.UnsubAckMessage;
import io.moquette.proto.messages.UnsubscribeMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class responsible to handle the logic of MQTT protocol it's the director of
* the protocol execution.
*
* Used by the front facing class SimpleMessaging.
*
* @author andrea
*/
public class ProtocolProcessor {
static final class WillMessage {
private final String topic;
private final ByteBuffer payload;
private final boolean retained;
private final QOSType qos;
public WillMessage(String topic, ByteBuffer payload, boolean retained, QOSType qos) {
this.topic = topic;
this.payload = payload;
this.retained = retained;
this.qos = qos;
}
public String getTopic() {
return topic;
}
public ByteBuffer getPayload() {
return payload;
}
public boolean isRetained() {
return retained;
}
public QOSType getQos() {
return qos;
}
}
private static final Logger LOG = LoggerFactory.getLogger(ProtocolProcessor.class);
protected ConcurrentMap<String, ConnectionDescriptor> m_clientIDs;
private SubscriptionsStore subscriptions;
private boolean allowAnonymous;
private IAuthorizator m_authorizator;
private IMessagesStore m_messagesStore;
private ISessionsStore m_sessionsStore;
private IAuthenticator m_authenticator;
private BrokerInterceptor m_interceptor;
private String allowedTopic = null;
private AbstractMessage.QOSType allowedQos = null;
//maps clientID to Will testament, if specified on CONNECT
private ConcurrentMap<String, WillMessage> m_willStore = new ConcurrentHashMap<>();
ProtocolProcessor() {}
/**
* @param subscriptions the subscription store where are stored all the existing
* clients subscriptions.
* @param storageService the persistent store to use for save/load of messages
* for QoS1 and QoS2 handling.
* @param sessionsStore the clients sessions store, used to persist subscriptions.
* @param authenticator the authenticator used in connect messages.
* @param allowAnonymous true connection to clients without credentials.
* @param authorizator used to apply ACL policies to publishes and subscriptions.
* @param interceptor to notify events to an intercept handler
*/
void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
ISessionsStore sessionsStore,
IAuthenticator authenticator,
boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor) {
init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, authorizator, interceptor, null, null);
}
void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
ISessionsStore sessionsStore,
IAuthenticator authenticator,
boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor, String allowedTopic, AbstractMessage.QOSType allowedQos) {
this.m_clientIDs = new ConcurrentHashMap<>();
this.m_interceptor = interceptor;
this.subscriptions = subscriptions;
this.allowAnonymous = allowAnonymous;
this.allowedTopic = allowedTopic;
this.allowedQos = allowedQos;
m_authorizator = authorizator;
LOG.trace("subscription tree on init {}", subscriptions.dumpTree());
m_authenticator = authenticator;
m_messagesStore = storageService;
m_sessionsStore = sessionsStore;
}
public void processConnect(Channel channel, ConnectMessage msg) {
LOG.debug("CONNECT for client <{}>", msg.getClientID());
if (msg.getProtocolVersion() != VERSION_3_1 && msg.getProtocolVersion() != VERSION_3_1_1) {
ConnAckMessage badProto = new ConnAckMessage();
badProto.setReturnCode(ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION);
LOG.warn("processConnect sent bad proto ConnAck");
channel.writeAndFlush(badProto);
channel.close();
return;
}
if (msg.getClientID() == null || msg.getClientID().length() == 0) {
ConnAckMessage okResp = new ConnAckMessage();
okResp.setReturnCode(ConnAckMessage.IDENTIFIER_REJECTED);
channel.writeAndFlush(okResp);
m_interceptor.notifyClientConnected(msg);
return;
}
//handle user authentication
if (msg.isUserFlag()) {
byte[] pwd = null;
if (msg.isPasswordFlag()) {
pwd = msg.getPassword();
} else if (!this.allowAnonymous) {
failedCredentials(channel);
return;
}
byte validationResultCode = m_authenticator.checkValid(msg);
if (validationResultCode != ConnAckMessage.CONNECTION_ACCEPTED) {
ConnAckMessage okResp = new ConnAckMessage();
okResp.setReturnCode(validationResultCode);
channel.writeAndFlush(okResp);
channel.close();
return;
}
NettyUtils.userName(channel, msg.getUsername());
} else if (!this.allowAnonymous) {
failedCredentials(channel);
return;
}
//if an old client with the same ID already exists close its session.
if (m_clientIDs.containsKey(msg.getClientID())) {
LOG.info("Found an existing connection with same client ID <{}>, forcing to close", msg.getClientID());
disconnectClient(msg.getClientID(), "{\"status\":401,\"error\":\"duplicate_connection\"}");
}
ConnectionDescriptor connDescr = new ConnectionDescriptor(msg.getClientID(), channel, msg.isCleanSession());
m_clientIDs.put(msg.getClientID(), connDescr);
int keepAlive = msg.getKeepAlive();
LOG.debug("Connect with keepAlive {} s", keepAlive);
NettyUtils.keepAlive(channel, keepAlive);
//session.attr(NettyUtils.ATTR_KEY_CLEANSESSION).set(msg.isCleanSession());
NettyUtils.cleanSession(channel, msg.isCleanSession());
//used to track the client in the subscription and publishing phases.
//session.attr(NettyUtils.ATTR_KEY_CLIENTID).set(msg.getClientID());
NettyUtils.clientID(channel, msg.getClientID());
LOG.debug("Connect create session <{}>", channel);
setIdleTime(channel.pipeline(), Math.round(keepAlive * 1.5f));
//Handle will flag
if (msg.isWillFlag()) {
AbstractMessage.QOSType willQos = AbstractMessage.QOSType.valueOf(msg.getWillQos());
byte[] willPayload = msg.getWillMessage();
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip();
//save the will testament in the clientID store
WillMessage will = new WillMessage(msg.getWillTopic(), bb, msg.isWillRetain(),willQos );
m_willStore.put(msg.getClientID(), will);
}
ConnAckMessage okResp = new ConnAckMessage();
okResp.setReturnCode(ConnAckMessage.CONNECTION_ACCEPTED);
ClientSession clientSession = m_sessionsStore.sessionForClient(msg.getClientID());
boolean isSessionAlreadyStored = clientSession != null;
if (!msg.isCleanSession() && isSessionAlreadyStored) {
okResp.setSessionPresent(true);
}
if (isSessionAlreadyStored) {
clientSession.cleanSession(msg.isCleanSession());
}
channel.writeAndFlush(okResp);
m_interceptor.notifyClientConnected(msg);
if (!isSessionAlreadyStored) {
LOG.info("Create persistent session for clientID <{}>", msg.getClientID());
clientSession = m_sessionsStore.createNewSession(msg.getClientID(), msg.isCleanSession());
}
clientSession.activate();
if (msg.isCleanSession()) {
clientSession.cleanSession();
}
LOG.info("Connected client ID <{}> with clean session {}", msg.getClientID(), msg.isCleanSession());
if (!msg.isCleanSession()) {
//force the republish of stored QoS1 and QoS2
republishStoredInSession(clientSession);
}
LOG.info("CONNECT processed");
}
private void setIdleTime(ChannelPipeline pipeline, int idleTime) {
if (pipeline.names().contains("idleStateHandler")) {
pipeline.remove("idleStateHandler");
}
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, idleTime));
}
private void failedCredentials(Channel session) {
ConnAckMessage okResp = new ConnAckMessage();
okResp.setReturnCode(ConnAckMessage.BAD_USERNAME_OR_PASSWORD);
session.writeAndFlush(okResp);
}
/**
* Republish QoS1 and QoS2 messages stored into the session for the clientID.
* */
private void republishStoredInSession(ClientSession clientSession) {
LOG.trace("republishStoredInSession for client <{}>", clientSession);
List<IMessagesStore.StoredMessage> publishedEvents = clientSession.storedMessages();
if (publishedEvents.isEmpty()) {
LOG.info("No stored messages for client <{}>", clientSession.clientID);
return;
}
LOG.info("republishing stored messages to client <{}>", clientSession.clientID);
for (IMessagesStore.StoredMessage pubEvt : publishedEvents) {
//TODO put in flight zone
directSend(clientSession, pubEvt.getTopic(), pubEvt.getQos(),
pubEvt.getMessage(), false, pubEvt.getMessageID());
clientSession.removeEnqueued(pubEvt.getGuid());
}
}
public void processPubAck(Channel session, PubAckMessage msg) {
String clientID = NettyUtils.clientID(session);
int messageID = msg.getMessageID();
//Remove the message from message store
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
verifyToActivate(clientID, targetSession);
targetSession.inFlightAcknowledged(messageID);
m_interceptor.notifyTopicPubacked(msg, clientID);
}
private void verifyToActivate(String clientID, ClientSession targetSession) {
if (m_clientIDs.containsKey(clientID)) {
targetSession.activate();
}
}
private static IMessagesStore.StoredMessage asStoredMessage(PublishMessage msg) {
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(msg.getPayload().array(), msg.getQos(), msg.getTopicName());
stored.setRetained(msg.isRetainFlag());
stored.setMessageID(msg.getMessageID());
return stored;
}
private static IMessagesStore.StoredMessage asStoredMessage(WillMessage will) {
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(will.getPayload().array(), will.getQos(), will.getTopic());
pub.setRetained(will.isRetained());
return pub;
}
public void processPublish(Channel session, PublishMessage msg) {
LOG.debug("allowedQos is {}; received Qos is {}", allowedQos, msg.getQos());
LOG.debug("allowedTopic is {}; received Topic is {}", allowedTopic, msg.getTopicName());
if ((allowedQos != null && msg.getQos() != allowedQos) || (allowedTopic != null && !msg.getTopicName().equals(allowedTopic))) {
String clientID = NettyUtils.clientID(session);
Integer messageID = msg.getMessageID();
if (msg.getQos() == QOSType.EXACTLY_ONCE) sendPubRec(clientID, messageID);
else if (msg.getQos() == QOSType.LEAST_ONE) sendPubAck(clientID, messageID);
return;
}
LOG.trace("PUB --PUBLISH--> SRV executePublish invoked with {}", msg);
String clientID = NettyUtils.clientID(session);
final String topic = msg.getTopicName();
//check if the topic can be wrote
String user = NettyUtils.userName(session);
if (!m_authorizator.canWrite(topic, user, clientID)) {
LOG.debug("topic {} doesn't have write credentials", topic);
return;
}
final AbstractMessage.QOSType qos = msg.getQos();
final Integer messageID = msg.getMessageID();
LOG.info("PUBLISH from clientID <{}> on topic <{}> with QoS {}", clientID, topic, qos);
String guid = null;
IMessagesStore.StoredMessage toStoreMsg = asStoredMessage(msg);
toStoreMsg.setClientID(clientID);
if (qos == AbstractMessage.QOSType.MOST_ONE) { //QoS0
route2Subscribers(toStoreMsg);
} else if (qos == AbstractMessage.QOSType.LEAST_ONE) { //QoS1
route2Subscribers(toStoreMsg);
sendPubAck(clientID, messageID);
LOG.debug("replying with PubAck to MSG ID {}", messageID);
} else if (qos == AbstractMessage.QOSType.EXACTLY_ONCE) { //QoS2
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
sendPubRec(clientID, messageID);
//Next the client will send us a pub rel
//NB publish to subscribers for QoS 2 happen upon PUBREL from publisher
}
if (msg.isRetainFlag()) {
if (qos == AbstractMessage.QOSType.MOST_ONE) {
//QoS == 0 && retain => clean old retained
m_messagesStore.cleanRetained(topic);
} else {
if (!msg.getPayload().hasRemaining()) {
m_messagesStore.cleanRetained(topic);
} else {
if (guid == null) {
//before wasn't stored
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
}
m_messagesStore.storeRetained(topic, guid);
}
}
}
m_interceptor.notifyTopicPublished(msg, clientID);
}
public void internalPublishToClient(String clientId, String message) {
LOG.info("Sending to {} message <{}>", clientId, message);
ClientSession targetSession = m_sessionsStore.sessionForClient(clientId);
verifyToActivate(clientId, targetSession);
ByteBuffer payload = ByteBuffer.wrap(message.getBytes());
directSend(targetSession, "grouvi_client", QOSType.LEAST_ONE, payload, false, targetSession.nextPacketId());
}
public void disconnectClient(String clientId, String error) {
LOG.info("Forcing client with id <{}> to close", clientId);
//clean the subscriptions if the old used a cleanSession = true
Channel channel = m_clientIDs.get(clientId).channel;
ClientSession clientSession = m_sessionsStore.sessionForClient(clientId);
if (error != null) {
LOG.info("Sending error message {} to client with id {}", error, clientId);
ByteBuffer payload = ByteBuffer.wrap(error.getBytes());
directSend(clientSession, "grouvi_client", QOSType.MOST_ONE, payload, false, null);
}
clientSession.disconnect();
NettyUtils.sessionStolen(channel, true);
channel.close();
LOG.debug("Connection with client ID <{}> is forced to close", clientId);
}
/**
* Intended usage is only for embedded versions of the broker, where the hosting application want to use the
* broker to send a publish message.
* Inspired by {@link #processPublish} but with some changes to avoid security check, and the handshake phases
* for Qos1 and Qos2.
* It also doesn't notifyTopicPublished because using internally the owner should already know where
* it's publishing.
* */
public void internalPublish(PublishMessage msg) {
final AbstractMessage.QOSType qos = msg.getQos();
final String topic = msg.getTopicName();
LOG.info("embedded PUBLISH on topic <{}> with QoS {}", topic, qos);
String guid = null;
IMessagesStore.StoredMessage toStoreMsg = asStoredMessage(msg);
toStoreMsg.setClientID("BROKER_SELF");
toStoreMsg.setMessageID(1);
if (qos == AbstractMessage.QOSType.EXACTLY_ONCE) { //QoS2
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
}
route2Subscribers(toStoreMsg);
if (!msg.isRetainFlag()) {
return;
}
if (qos == AbstractMessage.QOSType.MOST_ONE || !msg.getPayload().hasRemaining()) {
//QoS == 0 && retain => clean old retained
m_messagesStore.cleanRetained(topic);
return;
}
if (guid == null) {
//before wasn't stored
guid = m_messagesStore.storePublishForFuture(toStoreMsg);
}
m_messagesStore.storeRetained(topic, guid);
}
/**
* Specialized version to publish will testament message.
*/
private void forwardPublishWill(WillMessage will, String clientID) {
//it has just to publish the message downstream to the subscribers
//NB it's a will publish, it needs a PacketIdentifier for this conn, default to 1
Integer messageId = null;
if (will.getQos() != AbstractMessage.QOSType.MOST_ONE) {
messageId = m_sessionsStore.nextPacketID(clientID);
}
IMessagesStore.StoredMessage tobeStored = asStoredMessage(will);
tobeStored.setClientID(clientID);
tobeStored.setMessageID(messageId);
route2Subscribers(tobeStored);
}
/**
* Flood the subscribers with the message to notify. MessageID is optional and should only used for QoS 1 and 2
* */
void route2Subscribers(IMessagesStore.StoredMessage pubMsg) {
final String topic = pubMsg.getTopic();
final AbstractMessage.QOSType publishingQos = pubMsg.getQos();
final ByteBuffer origMessage = pubMsg.getMessage();
LOG.debug("route2Subscribers republishing to existing subscribers that matches the topic {}", topic);
if (LOG.isTraceEnabled()) {
LOG.trace("content <{}>", DebugUtils.payload2Str(origMessage));
LOG.trace("subscription tree {}", subscriptions.dumpTree());
}
//if QoS 1 or 2 store the message
String guid = null;
if (publishingQos == QOSType.EXACTLY_ONCE || publishingQos == QOSType.LEAST_ONE) {
guid = m_messagesStore.storePublishForFuture(pubMsg);
}
for (final Subscription sub : subscriptions.matches(topic)) {
AbstractMessage.QOSType qos = publishingQos;
if (qos.byteValue() > sub.getRequestedQos().byteValue()) {
qos = sub.getRequestedQos();
}
ClientSession targetSession = m_sessionsStore.sessionForClient(sub.getClientId());
verifyToActivate(sub.getClientId(), targetSession);
LOG.debug("Broker republishing to client <{}> topic <{}> qos <{}>, active {}",
sub.getClientId(), sub.getTopicFilter(), qos, targetSession.isActive());
ByteBuffer message = origMessage.duplicate();
if (qos == AbstractMessage.QOSType.MOST_ONE && targetSession.isActive()) {
//QoS 0
directSend(targetSession, topic, qos, message, false, null);
} else {
//QoS 1 or 2
//if the target subscription is not clean session and is not connected => store it
if (!targetSession.isCleanSession() && !targetSession.isActive()) {
//store the message in targetSession queue to deliver
targetSession.enqueueToDeliver(guid);
} else {
//publish
if (targetSession.isActive()) {
int messageId = targetSession.nextPacketId();
targetSession.inFlightAckWaiting(guid, messageId);
directSend(targetSession, topic, qos, message, false, messageId);
}
}
}
}
}
protected void directSend(ClientSession clientsession, String topic, AbstractMessage.QOSType qos, ByteBuffer message, boolean retained, Integer messageID) {
String clientId = clientsession.clientID;
LOG.debug("directSend invoked clientId <{}> on topic <{}> QoS {} retained {} messageID {}", clientId, topic, qos, retained, messageID);
PublishMessage pubMessage = new PublishMessage();
pubMessage.setRetainFlag(retained);
pubMessage.setTopicName(topic);
pubMessage.setQos(qos);
pubMessage.setPayload(message);
LOG.info("send publish message to <{}> on topic <{}>", clientId, topic);
if (LOG.isDebugEnabled()) {
LOG.debug("content <{}>", DebugUtils.payload2Str(message));
}
//set the PacketIdentifier only for QoS > 0
if (pubMessage.getQos() != AbstractMessage.QOSType.MOST_ONE) {
pubMessage.setMessageID(messageID);
} else {
if (messageID != null) {
throw new RuntimeException("Internal bad error, trying to forwardPublish a QoS 0 message with PacketIdentifier: " + messageID);
}
}
if (m_clientIDs == null) {
throw new RuntimeException("Internal bad error, found m_clientIDs to null while it should be initialized, somewhere it's overwritten!!");
}
LOG.debug("clientIDs are {}", m_clientIDs);
if (m_clientIDs.get(clientId) == null) {
//TODO while we were publishing to the target client, that client disconnected,
// could happen is not an error HANDLE IT
throw new RuntimeException(String.format("Can't find a ConnectionDescriptor for client <%s> in cache <%s>", clientId, m_clientIDs));
}
Channel channel = m_clientIDs.get(clientId).channel;
LOG.debug("Session for clientId {} is {}", clientId, channel);
channel.writeAndFlush(pubMessage);
}
private void sendPubRec(String clientID, int messageID) {
LOG.trace("PUB <--PUBREC-- SRV sendPubRec invoked for clientID {} with messageID {}", clientID, messageID);
PubRecMessage pubRecMessage = new PubRecMessage();
pubRecMessage.setMessageID(messageID);
m_clientIDs.get(clientID).channel.writeAndFlush(pubRecMessage);
}
private void sendPubAck(String clientId, int messageID) {
LOG.trace("sendPubAck invoked");
PubAckMessage pubAckMessage = new PubAckMessage();
pubAckMessage.setMessageID(messageID);
try {
if (m_clientIDs == null) {
throw new RuntimeException("Internal bad error, found m_clientIDs to null while it should be initialized, somewhere it's overwritten!!");
}
LOG.debug("clientIDs are {}", m_clientIDs);
if (m_clientIDs.get(clientId) == null) {
throw new RuntimeException(String.format("Can't find a ConnectionDescriptor for client %s in cache %s", clientId, m_clientIDs));
}
m_clientIDs.get(clientId).channel.writeAndFlush(pubAckMessage);
} catch(Throwable t) {
LOG.error(null, t);
}
}
/**
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish
* to all interested subscribers.
* */
public void processPubRel(Channel channel, PubRelMessage msg) {
LOG.debug("allowedQos is {}", allowedQos);
if (allowedQos != null && QOSType.EXACTLY_ONCE != allowedQos) {
sendPubComp(NettyUtils.clientID(channel), msg.getMessageID());
return;
}
String clientID = NettyUtils.clientID(channel);
int messageID = msg.getMessageID();
LOG.debug("PUB --PUBREL--> SRV processPubRel invoked for clientID {} ad messageID {}", clientID, messageID);
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
verifyToActivate(clientID, targetSession);
IMessagesStore.StoredMessage evt = targetSession.storedMessage(messageID);
route2Subscribers(evt);
if (evt.isRetained()) {
final String topic = evt.getTopic();
if (!evt.getMessage().hasRemaining()) {
m_messagesStore.cleanRetained(topic);
} else {
m_messagesStore.storeRetained(topic, evt.getGuid());
}
}
sendPubComp(clientID, messageID);
}
private void sendPubComp(String clientID, int messageID) {
LOG.debug("PUB <--PUBCOMP-- SRV sendPubComp invoked for clientID {} ad messageID {}", clientID, messageID);
PubCompMessage pubCompMessage = new PubCompMessage();
pubCompMessage.setMessageID(messageID);
m_clientIDs.get(clientID).channel.writeAndFlush(pubCompMessage);
}
public void processPubRec(Channel channel, PubRecMessage msg) {
String clientID = NettyUtils.clientID(channel);
int messageID = msg.getMessageID();
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
verifyToActivate(clientID, targetSession);
//remove from the inflight and move to the QoS2 second phase queue
targetSession.inFlightAcknowledged(messageID);
targetSession.secondPhaseAckWaiting(messageID);
//once received a PUBREC reply with a PUBREL(messageID)
LOG.debug("\t\tSRV <--PUBREC-- SUB processPubRec invoked for clientID {} ad messageID {}", clientID, messageID);
PubRelMessage pubRelMessage = new PubRelMessage();
pubRelMessage.setMessageID(messageID);
pubRelMessage.setQos(AbstractMessage.QOSType.LEAST_ONE);
channel.writeAndFlush(pubRelMessage);
}
public void processPubComp(Channel channel, PubCompMessage msg) {
String clientID = NettyUtils.clientID(channel);
int messageID = msg.getMessageID();
LOG.debug("\t\tSRV <--PUBCOMP-- SUB processPubComp invoked for clientID {} ad messageID {}", clientID, messageID);
//once received the PUBCOMP then remove the message from the temp memory
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
verifyToActivate(clientID, targetSession);
targetSession.secondPhaseAcknowledged(messageID);
}
public void processDisconnect(Channel channel) throws InterruptedException {
String clientID = NettyUtils.clientID(channel);
boolean cleanSession = NettyUtils.cleanSession(channel);
LOG.info("DISCONNECT client <{}> with clean session {}", clientID, cleanSession);
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
clientSession.disconnect();
m_clientIDs.remove(clientID);
channel.close();
//cleanup the will store
m_willStore.remove(clientID);
m_interceptor.notifyClientDisconnected(clientID);
LOG.info("DISCONNECT client <{}> finished", clientID, cleanSession);
}
public void processConnectionLost(String clientID, boolean sessionStolen, Channel channel) {
m_interceptor.notifyConnectionLost(clientID);
ConnectionDescriptor oldConnDescr = new ConnectionDescriptor(clientID, channel, true);
m_clientIDs.remove(clientID, oldConnDescr);
//If already removed a disconnect message was already processed for this clientID
if (sessionStolen) {
//de-activate the subscriptions for this ClientID
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
clientSession.deactivate();
LOG.info("Lost connection with client <{}>", clientID);
}
//publish the Will message (if any) for the clientID
if (!sessionStolen && m_willStore.containsKey(clientID)) {
WillMessage will = m_willStore.get(clientID);
forwardPublishWill(will, clientID);
m_willStore.remove(clientID);
}
}
/**
* Remove the clientID from topic subscription, if not previously subscribed,
* doesn't reply any error
*/
public void processUnsubscribe(Channel channel, UnsubscribeMessage msg) {
List<String> topics = msg.topicFilters();
int messageID = msg.getMessageID();
String clientID = NettyUtils.clientID(channel);
LOG.debug("UNSUBSCRIBE subscription on topics {} for clientID <{}>", topics, clientID);
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
verifyToActivate(clientID, clientSession);
for (String topic : topics) {
boolean validTopic = SubscriptionsStore.validate(topic);
if (!validTopic) {
//close the connection, not valid topicFilter is a protocol violation
channel.close();
LOG.warn("UNSUBSCRIBE found an invalid topic filter <{}> for clientID <{}>", topic, clientID);
return;
}
subscriptions.removeSubscription(topic, clientID);
clientSession.unsubscribeFrom(topic);
m_interceptor.notifyTopicUnsubscribed(topic, clientID);
}
//ack the client
UnsubAckMessage ackMessage = new UnsubAckMessage();
ackMessage.setMessageID(messageID);
LOG.info("replying with UnsubAck to MSG ID {}", messageID);
channel.writeAndFlush(ackMessage);
}
public void processSubscribe(Channel channel, SubscribeMessage msg) {
String clientID = NettyUtils.clientID(channel);
LOG.debug("SUBSCRIBE client <{}> packetID {}", clientID, msg.getMessageID());
//ack the client
SubAckMessage ackMessage = new SubAckMessage();
ackMessage.setMessageID(msg.getMessageID());
ackMessage.addType(msg.getQos());
channel.writeAndFlush(ackMessage);
return;
}
private boolean subscribeSingleTopic(final Subscription newSubscription) {
subscriptions.add(newSubscription.asClientTopicCouple());
//scans retained messages to be published to the new subscription
//TODO this is ugly, it does a linear scan on potential big dataset
Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() {
public boolean match(String key) {
return SubscriptionsStore.matchTopics(key, newSubscription.getTopicFilter());
}
});
ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId());
verifyToActivate(newSubscription.getClientId(), targetSession);
for (IMessagesStore.StoredMessage storedMsg : messages) {
//fire the as retained the message
LOG.debug("send publish message for topic {}", newSubscription.getTopicFilter());
//forwardPublishQoS0(newSubscription.getClientId(), storedMsg.getTopic(), storedMsg.getQos(), storedMsg.getPayload(), true);
Integer packetID = storedMsg.getQos() == QOSType.MOST_ONE ? null :
targetSession.nextPacketId();
directSend(targetSession, storedMsg.getTopic(), storedMsg.getQos(), storedMsg.getPayload(), true, packetID);
}
//notify the Observables
m_interceptor.notifyTopicSubscribed(newSubscription);
return true;
}
}
|
package com.intellij.ui.content.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.UIBundle;
import com.intellij.ui.content.*;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.util.ArrayList;
import java.util.List;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class ContentManagerImpl implements ContentManager {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.content.impl.ContentManagerImpl");
private ContentUI myUI;
private ArrayList<Content> myContents;
private EventListenerList myListeners;
private Content mySelectedContent;
private boolean myCanCloseContents;
private final Project myProject;
private final ProjectManagerAdapter myProjectManagerListener;
private boolean myListenerAdded;
public ContentManagerImpl(ContentUI contentUI, boolean canCloseContents, Project project) {
myCanCloseContents = canCloseContents;
myContents = new ArrayList<Content>();
myListeners = new EventListenerList();
myUI = contentUI;
myUI.setManager(this);
myProject = project;
myProjectManagerListener = new ProjectManagerAdapter() {
public void projectClosed(Project project) {
if (project == myProject) {
Content[] contents = myContents.toArray(new Content[myContents.size()]);
for (Content content : contents) {
removeContent(content);
}
}
}
};
}
public boolean canCloseContents() {
return myCanCloseContents;
}
public JComponent getComponent() {
return myUI.getComponent();
}
public void addContent(Content content) {
try {
((ContentImpl)content).setManager(this);
myContents.add(content);
fireContentAdded(content, myContents.size() - 1);
if (mySelectedContent == null) {
setSelectedContent(content);
}
} finally {
addProjectManagerListener();
}
}
// [Valentin] Q: throw exception when failed?
public boolean removeContent(Content content) {
try {
int selectedIndex = myContents.indexOf(mySelectedContent);
int indexToBeRemoved = myContents.indexOf(content);
if (indexToBeRemoved < 0) {
return false;
}
if (!fireContentRemoveQuery(content, indexToBeRemoved)) {
return false;
}
if (!content.isValid()) {
return false; // the content has already been invalidated by another thread or something
}
boolean wasSelected = content == mySelectedContent;
int indexToSelect = -1;
if (wasSelected) {
int i = indexToBeRemoved - 1;
if (i >= 0) {
indexToSelect = i;
}
else if (getContentCount() > 1) {
indexToSelect = 0;
}
}
else if (selectedIndex > indexToBeRemoved) {
indexToSelect = selectedIndex - 1;
}
myContents.remove(content);
int newSize = myContents.size();
if (newSize > 0) {
if (indexToSelect > -1) {
setSelectedContent(myContents.get(indexToSelect));
}
}
else {
setSelectedContent(null);
}
fireContentRemoved(content, indexToBeRemoved);
((ContentImpl)content).setManager(null);
final Disposable disposer = content.getDisposer();
if (disposer != null) {
Disposer.dispose(disposer);
}
return true;
} finally {
removeProjectManagerListener();
}
}
private void addProjectManagerListener() {
if (!myListenerAdded && myContents.size() > 0) {
ProjectManager.getInstance().addProjectManagerListener(myProjectManagerListener);
myListenerAdded = true;
}
}
private void removeProjectManagerListener() {
if (myContents.size() == 0) {
myUI.getComponent().updateUI(); //cleanup visibleComponent from Alloy...TabbedPaneUI
if (myListenerAdded) {
ProjectManager.getInstance().removeProjectManagerListener(myProjectManagerListener);
myListenerAdded = false;
}
}
}
public void removeAllContents() {
Content[] contents = getContents();
for (Content content : contents) {
removeContent(content);
}
}
public int getContentCount() {
return myContents.size();
}
public Content[] getContents() {
return myContents.toArray(new ContentImpl[myContents.size()]);
}
//TODO[anton,vova] is this method needed?
public Content findContent(String displayName) {
for (Content content : myContents) {
if (content.getDisplayName().equals(displayName)) {
return content;
}
}
return null;
}
public Content getContent(int index) {
return myContents.get(index);
}
public Content getContent(JComponent component) {
Content[] contents = getContents();
for (Content content : contents) {
if (Comparing.equal(component, content.getComponent())) {
return content;
}
}
return null;
}
public int getIndexOfContent(Content content) {
return myContents.indexOf(content);
}
public String getCloseActionName() {
return UIBundle.message("tabbed.pane.close.tab.action.name");
}
public String getCloseAllButThisActionName() {
return UIBundle.message("tabbed.pane.close.all.tabs.but.this.action.name");
}
public List<AnAction> getAdditionalPopupActions(final Content content) {
return null;
}
public boolean canCloseAllContents() {
return getContentCount() > 0 && canCloseContents();
}
public Content getSelectedContent() {
return mySelectedContent;
}
public void setSelectedContent(Content content) {
int index;
if (content != null) {
index = getIndexOfContent(content);
if (index == -1) {
throw new IllegalArgumentException("content not found: " + content);
}
}
else {
index = -1;
}
if (mySelectedContent != content) {
mySelectedContent = content;
fireSelectionChanged(content, index);
}
}
public void selectPreviousContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index - 1 + contentCount) % contentCount;
setSelectedContent(getContent(index));
}
public void selectNextContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index + 1) % contentCount;
setSelectedContent(getContent(index));
}
public void addContentManagerListener(ContentManagerListener l) {
myListeners.add(ContentManagerListener.class, l);
}
public void removeContentManagerListener(ContentManagerListener l) {
myListeners.remove(ContentManagerListener.class, l);
}
protected void fireContentAdded(Content content, int newIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, newIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentAdded(event);
}
}
protected void fireContentRemoved(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoved(event);
}
}
protected void fireSelectionChanged(Content content, int index) {
ContentManagerEvent event = new ContentManagerEvent(this, content, index);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.selectionChanged(event);
}
}
protected boolean fireContentRemoveQuery(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoveQuery(event);
if (event.isConsumed()) {
return false;
}
}
return true;
}
}
|
package edu.cmu.sv.ws.ssnoc.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.sql.Timestamp;
import java.util.List;
import javax.ws.rs.core.Response;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.cmu.sv.ws.ssnoc.dto.Message;
import edu.cmu.sv.ws.ssnoc.dto.User;
import edu.cmu.sv.ws.ssnoc.rest.MessageService;
import edu.cmu.sv.ws.ssnoc.rest.MessagesService;
import edu.cmu.sv.ws.ssnoc.rest.UserService;
public class WallMessageTest {
@Before
public void setUp() throws Exception {
User user = new User();
user.setUserName("foo");
user.setPassword("1234");
UserService userService = new UserService();
userService.addUser(user);
Message msg = new Message();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSendMessageToPublicWall() {
Message msg = new Message();
msg.setAuthor("foo");
Timestamp postedAt = new Timestamp(1234);
msg.setPostedAt(postedAt);
msg.setContent("test test lloyd owes a me a beer");
MessageService msgService = new MessageService();
Response response = msgService.addWallMessage("foo", msg);
assertEquals(((Message)response.getEntity()).getContent(), "test test lloyd owes a me a beer");
}
@Test
public void testGetAllMessagesFromPublicWall() {
Message msg = new Message();
MessagesService msgsService = new MessagesService();
MessageService msgService = new MessageService();
//Add atleast 1 message
msg.setAuthor("foo");
Timestamp postedAt = new Timestamp(1234);
msg.setPostedAt(postedAt);
msg.setContent("test test lloyd owes a me a beer");
Response response = msgService.addWallMessage("foo", msg);
List<Message> messages = (List<Message>) msgsService.loadWallMessages();
assertTrue(messages.size() != 0);
for (Message m : messages) {
assertTrue(m instanceof Message);
}
}
}
|
package com.rultor.base;
import java.util.concurrent.ConcurrentHashMap;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link SecretMap}.
* @author Bharath Bolisetty (bharathbolisetty@gmail.com)
* @version $Id$
*/
public final class SecretMapTest {
/**
* SecretMap can do basic operations.
*/
@Test
public void basicOperations() {
final ConcurrentHashMap<String, Object> map =
new ConcurrentHashMap<String, Object>(2);
final SecretMap secretmap = new SecretMap(map);
MatcherAssert.assertThat(secretmap.isEmpty(), Matchers.is(true));
MatcherAssert.assertThat(secretmap.size(), Matchers.is(0));
MatcherAssert.assertThat(secretmap.get("a"), Matchers.nullValue());
MatcherAssert.assertThat(
secretmap.containsKey("b"), Matchers.is(false)
);
final String value = "1";
map.put("c", value);
final SecretMap smap = new SecretMap(map);
MatcherAssert.assertThat(smap.isEmpty(), Matchers.is(false));
MatcherAssert.assertThat(smap.size(), Matchers.is(1));
MatcherAssert.assertThat(
smap.containsValue(value), Matchers.is(true)
);
}
/**
* SecretMap toString prints how many pairs it has.
*/
@Test
public void canPrintBasedOnsize() {
final ConcurrentHashMap<String, Object> map =
new ConcurrentHashMap<String, Object>(2);
final SecretMap secretmap = new SecretMap(map);
MatcherAssert.assertThat(secretmap.toString(), Matchers.is("{}"));
map.put("d", "2");
final SecretMap smap = new SecretMap(map);
MatcherAssert.assertThat(
smap.toString(), Matchers.is("{1 pair(s)}")
);
map.put("e", "3");
final SecretMap scmap = new SecretMap(map);
MatcherAssert.assertThat(
scmap.toString(), Matchers.is("{2 pair(s)}")
);
}
}
|
package org.xins.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.NullEnumeration;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.collections.BasicPropertyReader;
import org.xins.util.collections.PropertiesPropertyReader;
import org.xins.util.collections.PropertyReader;
import org.xins.util.collections.ProtectedPropertyReader;
import org.xins.util.io.FileWatcher;
import org.xins.util.servlet.ServletConfigPropertyReader;
/**
* HTTP servlet that forwards requests to an <code>API</code>.
*
* <p>This servlet supports the following HTTP request methods:
*
* <ul>
* <li>GET
* <li>POST
* <li>HEAD
* <li>OPTIONS
* </ul>
*
* <p>A method with any other request method will make this servlet return:
* <blockquote><code>405 Method Not Allowed</code></blockquote>
*
* <p>If no matching function is found, then this servlet will return:
* <blockquote><code>404 Not Found</code></blockquote>
*
* <p>If the state is not <em>ready</em>, then depending on the state, an HTTP
* response code will be returned:
*
* <table class="APIServlet_HTTP_response_codes">
* <tr>
* <th>State</th>
* <th>HTTP response code</th>
* </tr>
* <tr>
* <td>Initial</td>
* <td>503 Service Unavailable</td>
* </tr>
* <tr>
* <td>Bootstrapping framework</td>
* <td>503 Service Unavailable</td>
* </tr>
* <tr>
* <td>Framework bootstrap failed</td>
* <td>500 Internal Server Error</td>
* </tr>
* <tr>
* <td>Constructing API</td>
* <td>503 Service Unavailable</td>
* </tr>
* <tr>
* <td>API construction failed</td>
* <td>500 Internal Server Error</td>
* </tr>
* <tr>
* <td>Bootstrapping API</td>
* <td>503 Service Unavailable</td>
* </tr>
* <tr>
* <td>API bootstrap failed</td>
* <td>500 Internal Server Error</td>
* </tr>
* <tr>
* <td>Initializing API</td>
* <td>503 Service Unavailable</td>
* </tr>
* <tr>
* <td>API initialization failed</td>
* <td>500 Internal Server Error</td>
* </tr>
* <tr>
* <td>Disposing</td>
* <td>500 Internal Server Error</td>
* </tr>
* <tr>
* <td>Disposed</td>
* <td>500 Internal Server Error</td>
* </tr>
* <table>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public final class APIServlet
extends HttpServlet {
// Class fields
/**
* The <em>INITIAL</em> state.
*/
private static final State INITIAL = new State("INITIAL");
/**
* The <em>BOOTSTRAPPING_FRAMEWORK</em> state.
*/
private static final State BOOTSTRAPPING_FRAMEWORK = new State("BOOTSTRAPPING_FRAMEWORK");
/**
* The <em>FRAMEWORK_BOOTSTRAP_FAILED</em> state.
*/
private static final State FRAMEWORK_BOOTSTRAP_FAILED = new State("FRAMEWORK_BOOTSTRAP_FAILED");
/**
* The <em>CONSTRUCTING_API</em> state.
*/
private static final State CONSTRUCTING_API = new State("CONSTRUCTING_API");
/**
* The <em>API_CONSTRUCTION_FAILED</em> state.
*/
private static final State API_CONSTRUCTION_FAILED = new State("API_CONSTRUCTION_FAILED");
/**
* The <em>BOOTSTRAPPING_API</em> state.
*/
private static final State BOOTSTRAPPING_API = new State("BOOTSTRAPPING_API");
/**
* The <em>API_BOOTSTRAP_FAILED</em> state.
*/
private static final State API_BOOTSTRAP_FAILED = new State("API_BOOTSTRAP_FAILED");
/**
* The <em>INITIALIZING_API</em> state.
*/
private static final State INITIALIZING_API = new State("INITIALIZING_API");
/**
* The <em>API_INITIALIZATION_FAILED</em> state.
*/
private static final State API_INITIALIZATION_FAILED = new State("API_INITIALIZATION_FAILED");
/**
* The <em>READY</em> state.
*/
private static final State READY = new State("READY");
/**
* The <em>DISPOSING</em> state.
*/
private static final State DISPOSING = new State("DISPOSING");
/**
* The <em>DISPOSED</em> state.
*/
private static final State DISPOSED = new State("DISPOSED");
/**
* The expected version of the Java Servlet Specification, major part.
*/
private static final int EXPECTED_SERVLET_VERSION_MAJOR = 2;
/**
* The expected version of the Java Servlet Specification, minor part.
*/
private static final int EXPECTED_SERVLET_VERSION_MINOR = 3;
/**
* The name of the system property that specifies the location of the
* configuration file.
*/
public static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config";
/**
* The name of the configuration property that specifies the interval
* for the configuration file modification checks, in seconds.
*/
public static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload";
/**
* The default configuration file modification check interval, in seconds.
*/
public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60;
/**
* The name of the build property that specifies the name of the
* API class to load.
*/
public static final String API_CLASS_PROPERTY = "org.xins.api.class";
// Class functions
// Constructors
/**
* Constructs a new <code>APIServlet</code> object.
*/
public APIServlet() {
_stateLock = new Object();
_state = INITIAL;
_configFileListener = new ConfigurationFileListener();
}
// Fields
/**
* The current state.
*/
private State _state;
/**
* Lock for <code>_state</code>
*/
private final Object _stateLock;
/**
* The stored servlet configuration object.
*/
private ServletConfig _servletConfig;
/**
* The name of the configuration file.
*/
private String _configFile;
/**
* The API that this servlet forwards requests to.
*/
private API _api;
/**
* Description of the current error, if any. Will be returned by
* {@link #service(HttpServletRequest,HttpServletResponse)} if and only if
* the state is not {@link #READY}.
*/
private String _error;
/**
* The listener that is notified when the configuration file changes. Only
* one instance is created ever.
*/
private final ConfigurationFileListener _configFileListener;
/**
* Configuration file watcher.
*/
private FileWatcher _configFileWatcher;
// Methods
/**
* Gets the current state. This method first synchronizes on
* {@link #_stateLock} and then returns the value of {@link #_state}.
*
* @return
* the current state, cannot be <code>null</code>.
*/
private State getState() {
synchronized (_stateLock) {
return _state;
}
}
/**
* Initializes this servlet using the specified configuration. The
* (required) {@link ServletConfig} argument is stored internally and is
* returned from {@link #getServletConfig()}.
*
* <p>The initialization procedure will take required information from 3
* sources, initially:
*
* <dl>
* <dt><strong>1. Build-time settings</strong></dt>
* <dd>The application package contains a <code>web.xml</code> file with
* build-time settings. Some of these settings are required in order
* for the XINS/Java Server Framework to start up, while others are
* optional. These build-time settings are passed to the servlet by
* the application server as a {@link ServletConfig} object. See
* {@link #init(ServletConfig)}.
* <br />The servlet configuration is the responsibility of the
* <em>assembler</em>.</dd>
*
* <dt><strong>2. System properties</strong></dt>
* <dd>The location of the configuration file must be passed to the
* Java VM at startup, as a system property.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example:
* <br /><code>java -Dorg.xins.server.config=`pwd`/conf/xins.properties orion.jar</code></dd>
*
* <dt><strong>3. Configuration file</strong></dt>
* <dd>The configuration file should contain runtime configuration
* settings, like the settings for the logging subsystem.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example contents for a configuration file:
* <blockquote><code>log4j.rootLogger=DEBUG, console
* <br />log4j.appender.console=org.apache.log4j.ConsoleAppender
* <br />log4j.appender.console.layout=org.apache.log4j.PatternLayout
* <br />log4j.appender.console.layout.ConversionPattern=%d %-5p [%c] %m%n</code></blockquote>
* </dl>
*
* @param config
* the {@link ServletConfig} object which contains build properties for
* this servlet, as specified by the <em>assembler</em>, cannot be
* <code>null</code>.
*
* @throws ServletException
* if <code>config == null</code>, if this servlet is not uninitialized
* or if the initialization failed for some other reason.
*/
public void init(ServletConfig config) {
// Checks and preparations //
// Make sure the Library class is initialized
String version = Library.getVersion();
// Get a reference to the appropriate logger
Logger log = Library.BOOTSTRAP_LOG;
// Check preconditions
synchronized (_stateLock) {
if (_state != INITIAL) {
String message = "Application server malfunction detected. Cannot initialize servlet. State is " + _state + " instead of " + INITIAL + '.';
// This is not fatal, but an error, since the framework is already
// initialized.
log.error(message);
throw new Error(message);
} else if (config == null) {
String message = "Application server malfunction detected. Cannot initialize servlet. No servlet configuration object passed.";
log.fatal(message);
throw new Error(message);
}
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
String message = "Application server malfunction detected. Cannot initialize servlet. No servlet context available.";
log.fatal(message);
throw new Error(message);
}
// Check the expected vs implemented Java Servlet API version
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != EXPECTED_SERVLET_VERSION_MAJOR || minor != EXPECTED_SERVLET_VERSION_MINOR) {
log.warn("Application server implements Java Servlet API version " + major + '.' + minor + " instead of the expected version " + EXPECTED_SERVLET_VERSION_MAJOR + '.' + EXPECTED_SERVLET_VERSION_MINOR + ". The application may or may not work correctly.");
}
// Store the ServletConfig object, per the Servlet API Spec, see:
// http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#getServletConfig()
_servletConfig = config;
// Bootstrap framework //
// Proceed to first actual stage
_state = BOOTSTRAPPING_FRAMEWORK;
log.debug("Bootstrapping XINS/Java Server Framework.");
// Determine configuration file location
try {
_configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY);
} catch (SecurityException exception) {
_state = FRAMEWORK_BOOTSTRAP_FAILED;
_error = "System administration issue detected. Unable to get system property \"" + CONFIG_FILE_SYSTEM_PROPERTY + "\" due to a security restriction.";
log.error(_error, exception);
return;
}
// Property value must be set
// NOTE: Don't trim the configuration file name, since it may start
// with a space or other whitespace character.
if (_configFile == null || _configFile.length() < 1) {
_state = FRAMEWORK_BOOTSTRAP_FAILED;
_error = "System administration issue detected. System property \"" + CONFIG_FILE_SYSTEM_PROPERTY + "\" is not set.";
log.error(_error);
return;
}
// Apply the properties to the framework
PropertyReader runtimeProperties = applyConfigFile(log);
// Construct API //
// Proceed to next stage
_state = CONSTRUCTING_API;
log.debug("Constructing API.");
// Determine the API class
String apiClassName = config.getInitParameter(API_CLASS_PROPERTY);
if (apiClassName == null || apiClassName.trim().length() < 1) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. API class name not set in build property \"" + API_CLASS_PROPERTY + "\".";
log.fatal(_error);
return;
}
// Load the API class
Class apiClass;
try {
apiClass = Class.forName(apiClassName);
} catch (Throwable exception) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. Failed to load API class \"" + apiClassName + "\", as set in build property \"" + API_CLASS_PROPERTY + "\" due to unexpected " + exception.getClass().getName() + '.';
log.fatal(_error);
return;
}
// Check that the loaded API class is derived from the API base class
if (! API.class.isAssignableFrom(apiClass)) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. The \"" + apiClassName + "\" is not derived from class " + API.class.getName() + '.';
log.fatal(_error);
return;
}
// Get the SINGLETON field
Field singletonField;
try {
singletonField = apiClass.getDeclaredField("SINGLETON");
} catch (Exception exception) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. Failed to lookup class field SINGLETON in API class \"" + apiClassName + "\" due to unexpected " + exception.getClass().getName() + '.';
log.fatal(_error, exception);
return;
}
// Get the value of the SINGLETON field
try {
_api = (API) singletonField.get(null);
} catch (Exception exception) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. Failed to get value of the SINGLETON field of API class \"" + apiClassName + "\". Caught unexpected " + exception.getClass().getName() + '.';
log.fatal(_error, exception);
return;
}
// Make sure that the field is an instance of that same class
if (_api == null) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. The value of the SINGLETON field of API class \"" + apiClassName + "\" is null.";
log.fatal(_error);
return;
} else if (_api.getClass() != apiClass) {
_state = API_CONSTRUCTION_FAILED;
_error = "Invalid application package. The value of the SINGLETON field of API class \"" + apiClassName + "\" is not an instance of that class.";
log.fatal(_error);
return;
}
// Get the name of the API
String apiName = _api.getName();
log.debug("Constructed " + apiName + " API.");
// Bootstrap API //
// Proceed to next stage
_state = BOOTSTRAPPING_API;
log.debug("Bootstrapping " + apiName + " API.");
try {
_api.bootstrap(new ServletConfigPropertyReader(config));
} catch (Throwable exception) {
_state = API_BOOTSTRAP_FAILED;
_error = "Application package may be invalid. Unable to bootstrap \"" + apiName + "\" API due to unexpected " + exception.getClass().getName() + '.';
log.fatal(_error, exception);
return;
}
log.info("Bootstrapped " + apiName + " API.");
// Initialize the API //
initAPI(runtimeProperties);
// Watch the config file //
// Get the runtime property
String s = runtimeProperties.get(CONFIG_RELOAD_INTERVAL_PROPERTY);
int interval;
// If the property is set, parse it
if (s != null && s.length() >= 1) {
try {
interval = Integer.parseInt(s);
if (interval < 1) {
log.error("System administration issue detected. Configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is less than 1. Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
} else {
log.debug("Using configuration file check interval of " + interval + " second(s) as specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\".");
}
} catch (NumberFormatException nfe) {
log.error("System administration issue detected. Unable to parse configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\". Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
// Otherwise, if the property is not set, use the default
} else {
log.debug("Property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is not set. Using fallback default configuration file reload interval of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
// Create a file watch thread and start it
_configFileWatcher = new FileWatcher(_configFile, interval, _configFileListener);
log.info("Using config file \"" + _configFile + "\". Checking for modifications every " + interval + " second(s).");
_configFileWatcher.start();
}
}
/**
* Initializes the API using the specified runtime settings.
*
* @param runtimeProperties
* the runtime settings, guaranteed not to be <code>null</code>.
*/
private final void initAPI(PropertyReader runtimeProperties) {
// TODO: Check state and lock on state
_state = INITIALIZING_API;
try {
_api.init(runtimeProperties);
} catch (Throwable e) {
_state = API_INITIALIZATION_FAILED;
_error = "Failed to initialize " + _api.getName() + " API.";
Library.INIT_LOG.error(_error, e);
return;
}
_state = READY;
}
private PropertyReader applyConfigFile(Logger log)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("log", log);
Properties properties = new Properties();
PropertyReader pr = new ProtectedPropertyReader(new Object());
try {
FileInputStream in = new FileInputStream(_configFile);
properties.load(in);
pr = new PropertiesPropertyReader(properties);
Library.configure(log, properties);
} catch (FileNotFoundException exception) {
log.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened.");
} catch (SecurityException exception) {
log.error("System administration issue detected. Access denied while loading configuration file \"" + _configFile + "\".");
} catch (IOException exception) {
log.error("System administration issue detected. Unable to read configuration", exception);
}
return pr;
}
/**
* Returns the <code>ServletConfig</code> object which contains the
* build properties for this servlet. The returned {@link ServletConfig}
* object is the one passed to the {@link #init(ServletConfig)} method.
*
* @return
* the {@link ServletConfig} object that was used to initialize this
* servlet, not <code>null</code> if this servlet is indeed already
* initialized.
*/
public ServletConfig getServletConfig() {
return _servletConfig;
}
/**
* Handles a request to this servlet.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws ServletException
* if the state of this servlet is not <em>ready</em>, or
* if <code>request == null || response == null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Determine current time
long start = System.currentTimeMillis();
// Check arguments
if (request == null || response == null) {
String message = "Application server malfunction detected. ";
if (request == null && response == null) {
message += "Both request and response are null.";
} else if (request == null) {
message += "Request is null.";
} else {
message += "Response is null.";
}
Library.RUNTIME_LOG.error(message);
throw new ServletException(message);
}
// Check the HTTP request method
String method = request.getMethod();
boolean sendOutput = "GET".equals(method) || "POST".equals(method);
if (!sendOutput) {
if ("OPTIONS".equals(method)) {
response.setContentLength(0);
response.setHeader("Accept", "GET, HEAD, POST");
response.setStatus(HttpServletResponse.SC_OK);
return;
} else if ("HEAD".equals(method)) {
response.setContentLength(0);
// If the method is not recognized, return '405 Method Not Allowed'
} else {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
}
// TODO: Use OutputStream instead of Writer, for improved performance
// Call the API if the state is READY
CallResult result;
State state = getState();
if (state == READY) {
try {
result = _api.handleCall(start, request);
// If no matching function is found, return '404 Not Found'
} catch (NoSuchFunctionException exception) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Otherwise return an appropriate 50x HTTP response code
} else if (state == INITIAL
|| state == BOOTSTRAPPING_FRAMEWORK
|| state == CONSTRUCTING_API
|| state == BOOTSTRAPPING_API
|| state == INITIALIZING_API) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Send the output only if GET or POST
if (sendOutput) {
// Determine the XSLT to link to
String xslt = request.getParameter("_xslt");
// Send the XML output to the stream and flush
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
CallResultOutputter.output(out, result, xslt);
out.flush();
}
}
/**
* Returns information about this servlet, as plain text.
*
* @return
* textual description of this servlet, not <code>null</code> and not an
* empty character string.
*/
public String getServletInfo() {
return "XINS/Java Server Framework " + Library.getVersion();
}
/**
* Destroys this servlet. A best attempt will be made to release all
* resources.
*
* <p>After this method has finished, it will set the state to
* <em>disposed</em>. In that state no more requests will be handled.
*/
public void destroy() {
Library.SHUTDOWN_LOG.debug("Shutting down XINS/Java Server Framework.");
// Set the state temporarily to DISPOSING
synchronized (_stateLock) {
_state = DISPOSING;
}
// Destroy the API
if (_api != null) {
try {
_api.deinit();
} catch (Throwable t) {
Library.SHUTDOWN_LOG.error("Caught exception while deinitializing API.", t);
}
}
// Set the state to DISPOSED
synchronized (_state) {
_state = DISPOSED;
}
Library.SHUTDOWN_LOG.info("XINS/Java Server Framework shutdown completed.");
}
// Inner classes
/**
* State of an <code>APIServlet</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private static final class State extends Object {
// Constructors
private State(String name) throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("name", name);
_name = name;
}
// Fields
/**
* The name of this state. Cannot be <code>null</code>.
*/
private final String _name;
// Methods
/**
* Returns the name of this state.
*
* @return
* the name of this state, cannot be <code>null</code>.
*/
String getName() {
return _name;
}
/**
* Returns a textual representation of this object.
*
* @return
* the name of this state, never <code>null</code>.
*/
public String toString() {
return _name;
}
}
/**
* Listener that reloads the configuration file if it changes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private final class ConfigurationFileListener
extends Object
implements FileWatcher.Listener {
// Constructors
/**
* Constructs a new <code>ConfigurationFileListener</code> object.
*/
private ConfigurationFileListener() {
// empty
}
// Fields
// Methods
public void fileModified() {
Logger log = Library.INIT_LOG;
log.info("Configuration file \"" + _configFile + "\" is modified. Re-initializing XINS/Java Server Framework.");
// Apply the new runtime settings to the logging subsystem
PropertyReader runtimeProperties = applyConfigFile(log);
// Re-initialize the API
initAPI(runtimeProperties);
// Determine the interval
String s = runtimeProperties.get(CONFIG_RELOAD_INTERVAL_PROPERTY);
int interval;
// If the property is set, parse it
if (s != null && s.length() >= 1) {
try {
interval = Integer.parseInt(s);
if (interval < 1) {
log.error("System administration issue detected. Configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is less than 1. Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
} else {
log.debug("Using configuration file check interval of " + interval + " second(s) as specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\".");
}
} catch (NumberFormatException nfe) {
log.error("System administration issue detected. Unable to parse configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\". Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
// Otherwise, if the property is not set, use the default
} else {
log.debug("Property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is not set. Using fallback default configuration file reload interval of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s).");
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
// Update the file watch interval
_configFileWatcher.setInterval(interval);
log.info("Using config file \"" + _configFile + "\". Checking for modifications every " + interval + " second(s).");
log.info("XINS/Java Server Framework re-initialized.");
}
public void fileNotFound() {
Library.INIT_LOG.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened.");
}
public void fileNotModified() {
Library.INIT_LOG.debug("Configuration file \"" + _configFile + "\" is not modified.");
}
public void securityException(SecurityException exception) {
Library.INIT_LOG.error("System administration issue detected. Access denied while reading file \"" + _configFile + "\".");
}
}
}
|
package net.runelite.api;
// Note: This class is not complete: these animations were manually gathered
// through getAnimation(). Please add animations as you happen to use them.
public final class AnimationID
{
public static final int IDLE = -1;
public static final int WOODCUTTING_BRONZE = 879;
public static final int WOODCUTTING_IRON = 877;
public static final int WOODCUTTING_STEEL = 875;
public static final int WOODCUTTING_BLACK = 873;
public static final int WOODCUTTING_MITHRIL = 871;
public static final int WOODCUTTING_ADAMANT = 869;
public static final int WOODCUTTING_RUNE = 867;
public static final int WOODCUTTING_DRAGON = 2846;
public static final int WOODCUTTING_INFERNAL = 2117;
public static final int CONSUMING = 829; // consuming consumables
public static final int FIREMAKING = 733;
public static final int COOKING_FIRE = 897;
public static final int COOKING_RANGE = 896;
public static final int FLETCHING_BOW_CUTTING = 1248;
public static final int HUNTER_LAY_BOXTRAP_BIRDSNARE = 5208; //same for laying bird snares and box traps
public static final int HUNTER_LAY_DEADFALLTRAP = 5212; //setting up deadfall trap
public static final int HUNTER_LAY_NETTRAP = 5215; //setting up net trap
public static final int HUNTER_LAY_MANIACAL_MONKEY_BOULDER_TRAP = 7259; // setting up maniacal monkey boulder trap
public static final int HUNTER_CHECK_BIRD_SNARE = 5207;
public static final int HUNTER_CHECK_BOX_TRAP = 5212;
public static final int HERBLORE_MAKE_TAR = 5249;
public static final int FLETCHING_STRING_NORMAL_SHORTBOW = 6678;
public static final int FLETCHING_STRING_NORMAL_LONGBOW = 6684;
public static final int FLETCHING_STRING_OAK_SHORTBOW = 6679;
public static final int FLETCHING_STRING_OAK_LONGBOW = 6685;
public static final int FLETCHING_STRING_WILLOW_SHORTBOW = 6680;
public static final int FLETCHING_STRING_WILLOW_LONGBOW = 6686;
public static final int FLETCHING_STRING_MAPLE_SHORTBOW = 6681;
public static final int FLETCHING_STRING_MAPLE_LONGBOW = 6687;
public static final int FLETCHING_STRING_YEW_SHORTBOW = 6682;
public static final int FLETCHING_STRING_YEW_LONGBOW = 6688;
public static final int FLETCHING_STRING_MAGIC_SHORTBOW = 6683;
public static final int FLETCHING_STRING_MAGIC_LONGBOW = 6689;
public static final int GEM_CUTTING_OPAL = 890;
public static final int GEM_CUTTING_JADE = 891;
public static final int GEM_CUTTING_REDTOPAZ = 892;
public static final int GEM_CUTTING_SAPPHIRE = 888;
public static final int GEM_CUTTING_EMERALD = 889;
public static final int GEM_CUTTING_RUBY = 887;
public static final int GEM_CUTTING_DIAMOND = 886;
public static final int CRAFTING_LEATHER = 1249; // unknown if the anim is the same for all leathers
public static final int CRAFTING_GLASSBLOWING = 884;
public static final int CRAFTING_SPINNING = 894;
public static final int SMITHING_SMELTING = 899;
public static final int SMITHING_CANNONBALL = 827; //cball smithing uses this and SMITHING_SMELTING
public static final int SMITHING_ANVIL = 898;
public static final int FISHING_BIG_NET = 620;
public static final int FISHING_NET = 621;
public static final int FISHING_POLE_CAST = 623; // pole is in the water
public static final int FISHING_CAGE = 619;
public static final int FISHING_HARPOON = 618;
public static final int FISHING_BARBTAIL_HARPOON = 5108;
public static final int FISHING_DRAGON_HARPOON = 7401;
public static final int FISHING_INFERNAL_HARPOON = 7402;
public static final int FISHING_OILY_ROD = 622;
public static final int FISHING_KARAMBWAN = 1193;
public static final int FISHING_CRUSHING_INFERNAL_EELS = 7553;
public static final int FISHING_BAREHAND = 6709;
public static final int MINING_BRONZE_PICKAXE = 625;
public static final int MINING_IRON_PICKAXE = 626;
public static final int MINING_STEEL_PICKAXE = 627;
public static final int MINING_BLACK_PICKAXE = 3873;
public static final int MINING_MITHRIL_PICKAXE = 629;
public static final int MINING_ADAMANT_PICKAXE = 628;
public static final int MINING_RUNE_PICKAXE = 624;
public static final int MINING_DRAGON_PICKAXE = 7139;
public static final int MINING_DRAGON_PICKAXE_ORN = 642;
public static final int MINING_INFERNAL_PICKAXE = 4482;
public static final int MINING_MOTHERLODE_BRONZE = 6753;
public static final int MINING_MOTHERLODE_IRON = 6754;
public static final int MINING_MOTHERLODE_STEEL = 6755;
public static final int MINING_MOTHERLODE_BLACK = 3866;
public static final int MINING_MOTHERLODE_MITHRIL = 6757;
public static final int MINING_MOTHERLODE_ADAMANT = 6756;
public static final int MINING_MOTHERLODE_RUNE = 6752;
public static final int MINING_MOTHERLODE_DRAGON = 6758;
public static final int MINING_MOTHERLODE_DRAGON_ORN = 335;
public static final int MINING_MOTHERLODE_INFERNAL = 4481;
public static final int HERBLORE_POTIONMAKING = 363; //used for both herb and secondary
public static final int MAGIC_CHARGING_ORBS = 726;
public static final int BURYING_BONES = 827;
public static final int LOOKING_INTO = 832;
public static final int DIG = 830;
// NPC animations
public static final int TZTOK_JAD_MAGIC_ATTACK = 2656;
public static final int TZTOK_JAD_RANGE_ATTACK = 2652;
// Farming
public static final int FARMING_HARVEST_FRUIT_TREE = 2280;
public static final int FARMING_HARVEST_BUSH = 2281;
public static final int FARMING_HARVEST_HERB = 2282;
public static final int FARMING_USE_COMPOST = 2283;
public static final int FARMING_CURE_WITH_POTION = 2288;
public static final int FARMING_PLANT_SEED = 2291;
public static final int FARMING_HARVEST_FLOWER = 2292;
// Lunar spellbook
public static final int MAGIC_LUNAR_FERTILE_SOIL = 4413;
public static final int MAGIC_LUNAR_CURE_PLANT = 4432;
public static final int MAGIC_LUNAR_GEOMANCY = 7118;
// Arceuus spellbook
public static final int MAGIC_ARCEUUS_RESURRECT_CROPS = 7118;
}
|
package org.xins.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.NDC;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.NullEnumeration;
import org.xins.logdoc.LogCentral;
import org.xins.logdoc.UnsupportedLocaleException;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.collections.BasicPropertyReader;
import org.xins.util.collections.InvalidPropertyValueException;
import org.xins.util.collections.MissingRequiredPropertyException;
import org.xins.util.collections.PropertiesPropertyReader;
import org.xins.util.collections.PropertyReader;
import org.xins.util.collections.ProtectedPropertyReader;
import org.xins.util.io.FileWatcher;
import org.xins.util.manageable.BootstrapException;
import org.xins.util.manageable.InitializationException;
import org.xins.util.servlet.ServletConfigPropertyReader;
import org.xins.util.text.FastStringBuffer;
/**
* HTTP servlet that forwards requests to an <code>API</code>.
*
* <p>This servlet supports the following HTTP request methods:
*
* <ul>
* <li>GET
* <li>POST
* <li>HEAD
* <li>OPTIONS
* </ul>
*
* <p>A method with any other request method will make this servlet return:
* <blockquote><code>405 Method Not Allowed</code></blockquote>
*
* <p>If no matching function is found, then this servlet will return:
* <blockquote><code>404 Not Found</code></blockquote>
*
* <p>If the state is not <em>ready</em>, then depending on the state, an HTTP
* response code will be returned:
*
* <table class="APIServlet_HTTP_response_codes">
* <tr><th>State</th> <th>HTTP response code</th> </tr>
* <tr><td>Initial</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>Bootstrapping framework</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>Framework bootstrap failed</td><td>500 Internal Server Error</td></tr>
* <tr><td>Constructing API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API construction failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Bootstrapping API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API bootstrap failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Initializing API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API initialization failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Disposing</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Disposed</td> <td>500 Internal Server Error</td></tr>
* <table>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public final class APIServlet
extends HttpServlet {
// Class fields
/**
* The <em>INITIAL</em> state.
*/
private static final State INITIAL = new State("INITIAL");
/**
* The <em>BOOTSTRAPPING_FRAMEWORK</em> state.
*/
private static final State BOOTSTRAPPING_FRAMEWORK = new State("BOOTSTRAPPING_FRAMEWORK");
/**
* The <em>FRAMEWORK_BOOTSTRAP_FAILED</em> state.
*/
private static final State FRAMEWORK_BOOTSTRAP_FAILED = new State("FRAMEWORK_BOOTSTRAP_FAILED");
/**
* The <em>CONSTRUCTING_API</em> state.
*/
private static final State CONSTRUCTING_API = new State("CONSTRUCTING_API");
/**
* The <em>API_CONSTRUCTION_FAILED</em> state.
*/
private static final State API_CONSTRUCTION_FAILED = new State("API_CONSTRUCTION_FAILED");
/**
* The <em>BOOTSTRAPPING_API</em> state.
*/
private static final State BOOTSTRAPPING_API = new State("BOOTSTRAPPING_API");
/**
* The <em>API_BOOTSTRAP_FAILED</em> state.
*/
private static final State API_BOOTSTRAP_FAILED = new State("API_BOOTSTRAP_FAILED");
/**
* The <em>INITIALIZING_API</em> state.
*/
private static final State INITIALIZING_API = new State("INITIALIZING_API");
/**
* The <em>API_INITIALIZATION_FAILED</em> state.
*/
private static final State API_INITIALIZATION_FAILED = new State("API_INITIALIZATION_FAILED");
/**
* The <em>READY</em> state.
*/
private static final State READY = new State("READY");
/**
* The <em>DISPOSING</em> state.
*/
private static final State DISPOSING = new State("DISPOSING");
/**
* The <em>DISPOSED</em> state.
*/
private static final State DISPOSED = new State("DISPOSED");
/**
* The expected version of the Java Servlet Specification, major part.
*/
private static final int EXPECTED_SERVLET_VERSION_MAJOR = 2;
/**
* The expected version of the Java Servlet Specification, minor part.
*/
private static final int EXPECTED_SERVLET_VERSION_MINOR = 3;
/**
* The name of the system property that specifies the location of the
* configuration file.
*/
public static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config";
/**
* The name of the runtime property that specifies the interval
* for the configuration file modification checks, in seconds.
*/
public static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload";
/**
* The default configuration file modification check interval, in seconds.
*/
public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60;
/**
* The name of the build property that specifies the name of the
* API class to load.
*/
public static final String API_CLASS_PROPERTY = "org.xins.api.class";
/**
* The name of the runtime property that specifies the locale for the log
* messages.
*/
public static final String LOG_LOCALE_PROPERTY = "org.xins.server.log.locale";
// Class functions
/**
* Initializes the loggers to log to the console using a simple format
* and no threshold.
*/
static {
configureLoggerFallback();
}
/**
* Initializes the logging subsystem with fallback default settings.
*/
private static final void configureLoggerFallback() {
Properties settings = new Properties();
settings.setProperty("log4j.rootLogger", "ALL, console");
settings.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
settings.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
settings.setProperty("log4j.appender.console.layout.ConversionPattern", "%-4c{1} %-6p %m%n");
PropertyConfigurator.configure(settings);
}
// Constructors
/**
* Constructs a new <code>APIServlet</code> object.
*/
public APIServlet() {
_stateLock = new Object();
_state = INITIAL;
_configFileListener = new ConfigurationFileListener();
}
// Fields
/**
* The current state.
*/
private State _state;
/**
* Lock for <code>_state</code>
*/
private final Object _stateLock;
/**
* The stored servlet configuration object.
*/
private ServletConfig _servletConfig;
/**
* The name of the configuration file.
*/
private String _configFile;
/**
* The API that this servlet forwards requests to.
*/
private API _api;
/**
* The listener that is notified when the configuration file changes. Only
* one instance is created ever.
*/
private final ConfigurationFileListener _configFileListener;
/**
* Configuration file watcher.
*/
private FileWatcher _configFileWatcher;
// Methods
/**
* Gets the current state. This method first synchronizes on
* {@link #_stateLock} and then returns the value of {@link #_state}.
*
* @return
* the current state, cannot be <code>null</code>.
*/
private State getState() {
synchronized (_stateLock) {
return _state;
}
}
/**
* Changes the current state. This method first synchronizes on
* {@link #_stateLock} and then sets the value of {@link #_state}.
*
* @param newState
* the new state, cannot be <code>null</code>.
*/
private void setState(State newState)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("newState", newState);
// TODO: Check state
State oldState;
synchronized (_stateLock) {
// Short-circuit if the current is the new state
if (_state == newState) {
return;
}
// Store the old state
oldState = _state;
// Change the current state
_state = newState;
}
Log.log_1000(oldState._name, newState._name);
}
/**
* Determines the interval for checking the runtime properties file for
* modifications.
*
* @param properties
* the runtime properties to read from, should not be <code>null</code>.
*
* @return
* the interval to use, always >= 1.
*/
private final int determineConfigReloadInterval(PropertyReader properties) {
// Get the runtime property
String s = properties.get(CONFIG_RELOAD_INTERVAL_PROPERTY);
int interval = -1;
// If the property is set, parse it
if (s != null && s.length() >= 1) {
Log.log_4009(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
try {
interval = Integer.parseInt(s);
if (interval < 1) {
Log.log_4010(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
} else {
Log.log_4011(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
}
} catch (NumberFormatException nfe) {
Log.log_4010(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
}
// Otherwise, if the property is not set, use the default
} else {
Log.log_4008(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY);
}
// If the interval is not set, using the default
if (interval < 0) {
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
return interval;
}
/**
* Returns information about this servlet, as plain text.
*
* @return
* textual description of this servlet, not <code>null</code> and not an
* empty character string.
*/
public String getServletInfo() {
return "XINS/Java Server Framework " + Library.getVersion();
}
/**
* Initializes this servlet using the specified configuration. The
* (required) {@link ServletConfig} argument is stored internally and is
* returned from {@link #getServletConfig()}.
*
* <p>The initialization procedure will take required information from 3
* sources, initially:
*
* <dl>
* <dt><strong>1. Build-time settings</strong></dt>
* <dd>The application package contains a <code>web.xml</code> file with
* build-time settings. Some of these settings are required in order
* for the XINS/Java Server Framework to start up, while others are
* optional. These build-time settings are passed to the servlet by
* the application server as a {@link ServletConfig} object. See
* {@link #init(ServletConfig)}.
* <br />The servlet configuration is the responsibility of the
* <em>assembler</em>.</dd>
*
* <dt><strong>2. System properties</strong></dt>
* <dd>The location of the configuration file must be passed to the
* Java VM at startup, as a system property.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example:
* <br /><code>java -Dorg.xins.server.config=`pwd`/conf/xins.properties orion.jar</code></dd>
*
* <dt><strong>3. Configuration file</strong></dt>
* <dd>The configuration file should contain runtime configuration
* settings, like the settings for the logging subsystem.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example contents for a configuration file:
* <blockquote><code>log4j.rootLogger=DEBUG, console
* <br />log4j.appender.console=org.apache.log4j.ConsoleAppender
* <br />log4j.appender.console.layout=org.apache.log4j.PatternLayout
* <br />log4j.appender.console.layout.ConversionPattern=%d %-5p [%c] %m%n</code></blockquote>
* </dl>
*
* @param config
* the {@link ServletConfig} object which contains build properties for
* this servlet, as specified by the <em>assembler</em>, cannot be
* <code>null</code>.
*
* @throws ServletException
* if the servlet could not be initialized.
*/
public void init(ServletConfig config)
throws ServletException {
Log.log_2000();
// Checks and preparations //
// Make sure the Library class is initialized
String version = Library.getVersion();
// Check preconditions
synchronized (_stateLock) {
if (_state != INITIAL && _state != FRAMEWORK_BOOTSTRAP_FAILED
&& _state != API_CONSTRUCTION_FAILED && _state != API_BOOTSTRAP_FAILED
&& _state != API_INITIALIZATION_FAILED) {
Log.log_2001(_state == null ? null : _state._name);
throw new ServletException();
} else if (config == null) {
Log.log_2002("config == null");
throw new ServletException();
}
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
Log.log_2002("config.getServletContext() == null");
throw new ServletException();
}
// Check the expected vs implemented Java Servlet API version
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != EXPECTED_SERVLET_VERSION_MAJOR || minor != EXPECTED_SERVLET_VERSION_MINOR) {
String expected = "" + EXPECTED_SERVLET_VERSION_MAJOR + '.' + EXPECTED_SERVLET_VERSION_MINOR;
String actual = "" + major + '.' + minor;
Log.log_2003(actual, expected);
}
// Store the ServletConfig object, per the Servlet API Spec, see:
// http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#getServletConfig()
_servletConfig = config;
// Bootstrap framework //
// Proceed to first actual stage
setState(BOOTSTRAPPING_FRAMEWORK);
// Determine configuration file location
try {
_configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY);
} catch (SecurityException exception) {
Log.log_2004(exception, CONFIG_FILE_SYSTEM_PROPERTY);
setState(FRAMEWORK_BOOTSTRAP_FAILED);
throw new ServletException();
}
// Property value must be set
// NOTE: Don't trim the configuration file name, since it may start
// with a space or other whitespace character.
if (_configFile == null || _configFile.length() < 1) {
Log.log_2005(CONFIG_FILE_SYSTEM_PROPERTY);
setState(FRAMEWORK_BOOTSTRAP_FAILED);
throw new ServletException();
}
// Initialize the logging subsystem
PropertyReader runtimeProperties = readRuntimeProperties();
// Construct API //
// Proceed to next stage
setState(CONSTRUCTING_API);
// Determine the API class
String apiClassName = config.getInitParameter(API_CLASS_PROPERTY);
apiClassName = (apiClassName == null) ? apiClassName : apiClassName.trim();
if (apiClassName == null || apiClassName.length() < 1) {
Log.log_2006(API_CLASS_PROPERTY);
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Load the API class
Class apiClass;
try {
apiClass = Class.forName(apiClassName);
} catch (Throwable exception) {
Log.log_2007(exception, API_CLASS_PROPERTY, apiClassName);
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Check that the loaded API class is derived from the API base class
if (! API.class.isAssignableFrom(apiClass)) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, API.class.getName() + ".class.isAssignableFrom(apiClass) == false");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Get the SINGLETON field and the value of it
Field singletonField;
try {
singletonField = apiClass.getDeclaredField("SINGLETON");
_api = (API) singletonField.get(null);
} catch (Throwable exception) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, exception.getClass().getName());
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Make sure that the field is an instance of that same class
if (_api == null) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, "apiClass.getDeclaredField(\"SINGLETON\").get(null) == null");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
} else if (_api.getClass() != apiClass) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, "apiClass.getDeclaredField(\"SINGLETON\").get(null).getClass() != apiClass");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Bootstrap API //
// Proceed to next stage
setState(BOOTSTRAPPING_API);
// Bootstrap the API
boolean succeeded = false;
try {
_api.bootstrap(new ServletConfigPropertyReader(config));
succeeded = true;
} catch (MissingRequiredPropertyException exception) {
Log.log_2009(exception.getPropertyName());
} catch (InvalidPropertyValueException exception) {
Log.log_2010(exception.getPropertyName(), exception.getPropertyValue());
} catch (BootstrapException exception) {
Log.log_2011(exception.getMessage());
} catch (Throwable exception) {
Log.log_2012(exception);
} finally {
if (succeeded == false) {
setState(API_BOOTSTRAP_FAILED);
throw new ServletException();
}
}
// Initialize the API //
initAPI(runtimeProperties);
// Watch the config file //
int interval = determineConfigReloadInterval(runtimeProperties);
// Create and start a file watch thread
_configFileWatcher = new FileWatcher(_configFile, interval, _configFileListener);
Log.log_4012(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, interval);
_configFileWatcher.start();
}
}
/**
* Initializes the API using the specified runtime settings.
*
* @param runtimeProperties
* the runtime settings, guaranteed not to be <code>null</code>.
*/
private final void initAPI(PropertyReader runtimeProperties) {
setState(INITIALIZING_API);
boolean succeeded = false;
try {
_api.init(runtimeProperties);
succeeded = true;
} catch (MissingRequiredPropertyException exception) {
Log.log_4013(exception.getPropertyName());
} catch (InvalidPropertyValueException exception) {
Log.log_4014(exception.getPropertyName(), exception.getPropertyValue());
} catch (InitializationException exception) {
Log.log_4015(exception.getMessage());
} catch (Throwable exception) {
Log.log_4016(exception);
} finally {
if (succeeded) {
setState(READY);
Log.log_4018();
} else {
setState(API_INITIALIZATION_FAILED);
return;
}
}
}
/**
* Reads the runtime properties file, initializes the logging subsystem
* with the read properties and then returns those properties. If the
* properties cannot be read from the file for any reason, then an empty
* set of properties is returned.
*
* @return
* the properties read from the config file, never <code>null</code>.
*/
private PropertyReader readRuntimeProperties() {
Log.log_3000();
Properties properties = new Properties();
try {
// Open the file
FileInputStream in = new FileInputStream(_configFile);
// Load the properties
properties.load(in);
} catch (FileNotFoundException exception) {
Log.log_3001(exception, _configFile);
} catch (SecurityException exception) {
Log.log_3002(exception, _configFile);
} catch (IOException exception) {
Log.log_3003(exception, _configFile);
}
// TODO: Should we reset the logging subsystem if the Log4J
// TODO properties have been removed from the xins.properties file?
// TODO Determine the current behaviour and make a decision.
// Attempt to configure Log4J
PropertyConfigurator.configure(properties);
// Determine if Log4J is properly initialized
Enumeration appenders = LogManager.getLoggerRepository().getRootLogger().getAllAppenders();
if (appenders instanceof NullEnumeration) {
Log.log_3004(_configFile);
configureLoggerFallback();
} else {
Log.log_3005();
}
// Determine the log locale
String newLocale = properties.getProperty(LOG_LOCALE_PROPERTY);
// If the log locale is set, apply it
if (newLocale != null) {
String currentLocale = Log.getTranslationBundle().getName();
if (currentLocale.equals(newLocale) == false) {
Log.log_3006(currentLocale, newLocale);
try {
LogCentral.setLocale(newLocale);
Log.log_3007(currentLocale, newLocale);
} catch (UnsupportedLocaleException exception) {
Log.log_3008(currentLocale, newLocale);
}
}
}
return new PropertiesPropertyReader(properties);
}
/**
* Returns the <code>ServletConfig</code> object which contains the
* build properties for this servlet. The returned {@link ServletConfig}
* object is the one passed to the {@link #init(ServletConfig)} method.
*
* @return
* the {@link ServletConfig} object that was used to initialize this
* servlet, not <code>null</code> if this servlet is indeed already
* initialized.
*/
public ServletConfig getServletConfig() {
return _servletConfig;
}
/**
* Handles a request to this servlet (wrapper method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Determine diagnostic context ID
String contextID = request.getParameter("_context");
// If there is a diagnostic context ID, then apply it and perform the
// request...
boolean haveContextID = (contextID != null) && (contextID.length() > 0);
if (haveContextID) {
NDC.push(contextID);
try {
doService(request, response);
} finally {
NDC.pop();
}
// ...otherwise just perform the request.
} else {
doService(request, response);
}
// TODO: Document _context somewhere
}
/**
* Handles a request to this servlet (implementation method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* <p>This method is called from
* {@link #service(HttpServletRequest,HttpServletResponse)}. The latter
* first determines the <em>nested diagnostic context</em> and then
* forwards the call to this method.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
private void doService(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Determine current time
long start = System.currentTimeMillis();
// Determine the remote IP address and the query string
String ip = request.getRemoteAddr();
String queryString = request.getQueryString();
// Check the HTTP request method
String method = request.getMethod();
boolean sendOutput = "GET".equals(method) || "POST".equals(method);
if (!sendOutput) {
if ("OPTIONS".equals(method)) {
Log.log_5001(ip, method, queryString);
response.setContentLength(0);
response.setHeader("Accept", "GET, HEAD, POST");
response.setStatus(HttpServletResponse.SC_OK);
return;
} else if ("HEAD".equals(method)) {
response.setContentLength(0);
// If the method is not recognized, return '405 Method Not Allowed'
} else {
Log.log_5000(ip, method, queryString);
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
}
Log.log_5001(ip, method, queryString);
// XXX: Consider using OutputStream instead of Writer, for improved
// XXX: performance
// Call the API if the state is READY
CallResult result;
State state = getState();
if (state == READY) {
try {
result = _api.handleCall(start, request);
// If access is denied, return '403 Forbidden'
} catch (AccessDeniedException exception) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
// If no matching function is found, return '404 Not Found'
} catch (NoSuchFunctionException exception) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Otherwise return an appropriate 50x HTTP response code
} else if (state == INITIAL
|| state == BOOTSTRAPPING_FRAMEWORK
|| state == CONSTRUCTING_API
|| state == BOOTSTRAPPING_API
|| state == INITIALIZING_API) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Send the output only if GET or POST
if (sendOutput) {
// Determine the XSLT to link to
String xslt = request.getParameter("_xslt");
// Send the XML output to the stream and flush
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
CallResultOutputter.output(out, result, xslt);
out.flush();
}
}
/**
* Destroys this servlet. A best attempt will be made to release all
* resources.
*
* <p>After this method has finished, it will set the state to
* <em>disposed</em>. In that state no more requests will be handled.
*/
public void destroy() {
Log.log_6000();
// Set the state temporarily to DISPOSING
setState(DISPOSING);
// Destroy the API
if (_api != null) {
try {
_api.deinit();
} catch (Throwable exception) {
Log.log_6001(exception);
}
}
// Set the state to DISPOSED
setState(DISPOSED);
Log.log_6002();
}
// Inner classes
/**
* State of an <code>APIServlet</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private static final class State extends Object {
// Constructors
private State(String name) throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("name", name);
_name = name;
}
// Fields
/**
* The name of this state. Cannot be <code>null</code>.
*/
private final String _name;
// Methods
/**
* Returns the name of this state.
*
* @return
* the name of this state, cannot be <code>null</code>.
*/
String getName() {
return _name;
}
/**
* Returns a textual representation of this object.
*
* @return
* the name of this state, never <code>null</code>.
*/
public String toString() {
return _name;
}
}
/**
* Listener that reloads the configuration file if it changes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private final class ConfigurationFileListener
extends Object
implements FileWatcher.Listener {
// Constructors
/**
* Constructs a new <code>ConfigurationFileListener</code> object.
*/
private ConfigurationFileListener() {
// empty
}
// Fields
// Methods
public void fileModified() {
Log.log_4007(_configFile);
// Apply the new runtime settings to the logging subsystem
PropertyReader runtimeProperties = readRuntimeProperties();
// Determine the interval
int newInterval = determineConfigReloadInterval(runtimeProperties);
// Update the file watch interval
int oldInterval = _configFileWatcher.getInterval();
if (oldInterval != newInterval) {
_configFileWatcher.setInterval(newInterval);
Log.log_4003(_configFile, oldInterval, newInterval);
}
// Re-initialize the API
initAPI(runtimeProperties);
}
public void fileNotFound() {
Log.log_4000(_configFile);
}
public void fileNotModified() {
Log.log_4002(_configFile);
}
public void securityException(SecurityException exception) {
Log.log_4001(exception, _configFile);
}
}
}
|
package org.xins.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.NDC;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.NullEnumeration;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.collections.BasicPropertyReader;
import org.xins.util.collections.InvalidPropertyValueException;
import org.xins.util.collections.MissingRequiredPropertyException;
import org.xins.util.collections.PropertiesPropertyReader;
import org.xins.util.collections.PropertyReader;
import org.xins.util.collections.ProtectedPropertyReader;
import org.xins.util.io.FileWatcher;
import org.xins.util.manageable.BootstrapException;
import org.xins.util.manageable.InitializationException;
import org.xins.util.servlet.ServletConfigPropertyReader;
import org.xins.util.text.FastStringBuffer;
/**
* HTTP servlet that forwards requests to an <code>API</code>.
*
* <p>This servlet supports the following HTTP request methods:
*
* <ul>
* <li>GET
* <li>POST
* <li>HEAD
* <li>OPTIONS
* </ul>
*
* <p>A method with any other request method will make this servlet return:
* <blockquote><code>405 Method Not Allowed</code></blockquote>
*
* <p>If no matching function is found, then this servlet will return:
* <blockquote><code>404 Not Found</code></blockquote>
*
* <p>If the state is not <em>ready</em>, then depending on the state, an HTTP
* response code will be returned:
*
* <table class="APIServlet_HTTP_response_codes">
* <tr><th>State</th> <th>HTTP response code</th> </tr>
* <tr><td>Initial</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>Bootstrapping framework</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>Framework bootstrap failed</td><td>500 Internal Server Error</td></tr>
* <tr><td>Constructing API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API construction failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Bootstrapping API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API bootstrap failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Initializing API</td> <td>503 Service Unavailable</td> </tr>
* <tr><td>API initialization failed</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Disposing</td> <td>500 Internal Server Error</td></tr>
* <tr><td>Disposed</td> <td>500 Internal Server Error</td></tr>
* <table>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public final class APIServlet
extends HttpServlet {
// Class fields
/**
* The <em>INITIAL</em> state.
*/
private static final State INITIAL = new State("INITIAL");
/**
* The <em>BOOTSTRAPPING_FRAMEWORK</em> state.
*/
private static final State BOOTSTRAPPING_FRAMEWORK = new State("BOOTSTRAPPING_FRAMEWORK");
/**
* The <em>FRAMEWORK_BOOTSTRAP_FAILED</em> state.
*/
private static final State FRAMEWORK_BOOTSTRAP_FAILED = new State("FRAMEWORK_BOOTSTRAP_FAILED");
/**
* The <em>CONSTRUCTING_API</em> state.
*/
private static final State CONSTRUCTING_API = new State("CONSTRUCTING_API");
/**
* The <em>API_CONSTRUCTION_FAILED</em> state.
*/
private static final State API_CONSTRUCTION_FAILED = new State("API_CONSTRUCTION_FAILED");
/**
* The <em>BOOTSTRAPPING_API</em> state.
*/
private static final State BOOTSTRAPPING_API = new State("BOOTSTRAPPING_API");
/**
* The <em>API_BOOTSTRAP_FAILED</em> state.
*/
private static final State API_BOOTSTRAP_FAILED = new State("API_BOOTSTRAP_FAILED");
/**
* The <em>INITIALIZING_API</em> state.
*/
private static final State INITIALIZING_API = new State("INITIALIZING_API");
/**
* The <em>API_INITIALIZATION_FAILED</em> state.
*/
private static final State API_INITIALIZATION_FAILED = new State("API_INITIALIZATION_FAILED");
/**
* The <em>READY</em> state.
*/
private static final State READY = new State("READY");
/**
* The <em>DISPOSING</em> state.
*/
private static final State DISPOSING = new State("DISPOSING");
/**
* The <em>DISPOSED</em> state.
*/
private static final State DISPOSED = new State("DISPOSED");
/**
* The expected version of the Java Servlet Specification, major part.
*/
private static final int EXPECTED_SERVLET_VERSION_MAJOR = 2;
/**
* The expected version of the Java Servlet Specification, minor part.
*/
private static final int EXPECTED_SERVLET_VERSION_MINOR = 3;
/**
* The name of the system property that specifies the location of the
* configuration file.
*/
public static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config";
/**
* The name of the runtime property that specifies the interval
* for the configuration file modification checks, in seconds.
*/
public static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload";
/**
* The default configuration file modification check interval, in seconds.
*/
public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60;
/**
* The name of the build property that specifies the name of the
* API class to load.
*/
public static final String API_CLASS_PROPERTY = "org.xins.api.class";
/**
* The name of the runtime property that specifies the locale for the log
* messages.
*/
public static final String LOG_LOCALE_PROPERTY = "org.xins.server.log.locale";
// Class functions
/**
* Creates a string for use in an error message in case an unexpected
* exception is caught.
*
* @param exception
* the caught exception, cannot be <code>null</code>.
*
* @return
* the character string to use in an error message, never
* <code>null</code>, always starts with <code>"due to
* unexpected"</code> and always ends with a full stop character
* (<code>'.'</code>).
*/
static final String dueToUnexpected(Throwable exception)
throws NullPointerException {
// TODO: Remove this function
FastStringBuffer buffer = new FastStringBuffer(4014);
buffer.append("due to unexpected ");
buffer.append(exception.getClass().getName());
String message = exception.getMessage();
if (message == null || message.length() < 1) {
buffer.append(" with no message.");
} else {
buffer.append(" with message \"");
buffer.append(message);
buffer.append("\".");
}
return buffer.toString();
}
/**
* Initializes the loggers to log to the console using a simple format
* and no threshold.
*/
static {
configureLoggerFallback();
}
/**
* Initializes the logging subsystem with fallback default settings.
*/
private static final void configureLoggerFallback() {
Properties settings = new Properties();
settings.setProperty("log4j.rootLogger", "ALL, console");
settings.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
settings.setProperty("log4j.appender.console.layout", "org.apache.log4j.SimpleLayout");
PropertyConfigurator.configure(settings);
}
// Constructors
/**
* Constructs a new <code>APIServlet</code> object.
*/
public APIServlet() {
_stateLock = new Object();
_state = INITIAL;
_configFileListener = new ConfigurationFileListener();
}
// Fields
/**
* The current state.
*/
private State _state;
/**
* Lock for <code>_state</code>
*/
private final Object _stateLock;
/**
* The stored servlet configuration object.
*/
private ServletConfig _servletConfig;
/**
* The name of the configuration file.
*/
private String _configFile;
/**
* The API that this servlet forwards requests to.
*/
private API _api;
/**
* The listener that is notified when the configuration file changes. Only
* one instance is created ever.
*/
private final ConfigurationFileListener _configFileListener;
/**
* Configuration file watcher.
*/
private FileWatcher _configFileWatcher;
// Methods
/**
* Gets the current state. This method first synchronizes on
* {@link #_stateLock} and then returns the value of {@link #_state}.
*
* @return
* the current state, cannot be <code>null</code>.
*/
private State getState() {
synchronized (_stateLock) {
return _state;
}
}
/**
* Changes the current state. This method first synchronizes on
* {@link #_stateLock} and then sets the value of {@link #_state}.
*
* @param newState
* the new state, cannot be <code>null</code>.
*/
private void setState(State newState)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("newState", newState);
// TODO: Check state
State oldState;
synchronized (_stateLock) {
// Short-circuit if the current is the new state
if (_state == newState) {
return;
}
// Store the old state
oldState = _state;
// Change the current state
_state = newState;
}
Log.log_1000(oldState._name, newState._name);
}
/**
* Determines the interval for checking the runtime properties file for
* modifications.
*
* @param properties
* the runtime properties to read from, should not be <code>null</code>.
*
* @return
* the interval to use, always >= 1.
*/
private final int determineConfigReloadInterval(PropertyReader properties) {
// Get the runtime property
String s = properties.get(CONFIG_RELOAD_INTERVAL_PROPERTY);
int interval = -1;
// If the property is set, parse it
if (s != null && s.length() >= 1) {
Log.log_4009(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
try {
interval = Integer.parseInt(s);
if (interval < 1) {
Log.log_4010(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
} else {
Log.log_4011(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
}
} catch (NumberFormatException nfe) {
Log.log_4010(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, s);
}
// Otherwise, if the property is not set, use the default
} else {
Log.log_4008(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY);
}
// If the interval is not set, using the default
if (interval < 0) {
interval = DEFAULT_CONFIG_RELOAD_INTERVAL;
}
return interval;
}
/**
* Returns information about this servlet, as plain text.
*
* @return
* textual description of this servlet, not <code>null</code> and not an
* empty character string.
*/
public String getServletInfo() {
return "XINS/Java Server Framework " + Library.getVersion();
}
/**
* Initializes this servlet using the specified configuration. The
* (required) {@link ServletConfig} argument is stored internally and is
* returned from {@link #getServletConfig()}.
*
* <p>The initialization procedure will take required information from 3
* sources, initially:
*
* <dl>
* <dt><strong>1. Build-time settings</strong></dt>
* <dd>The application package contains a <code>web.xml</code> file with
* build-time settings. Some of these settings are required in order
* for the XINS/Java Server Framework to start up, while others are
* optional. These build-time settings are passed to the servlet by
* the application server as a {@link ServletConfig} object. See
* {@link #init(ServletConfig)}.
* <br />The servlet configuration is the responsibility of the
* <em>assembler</em>.</dd>
*
* <dt><strong>2. System properties</strong></dt>
* <dd>The location of the configuration file must be passed to the
* Java VM at startup, as a system property.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example:
* <br /><code>java -Dorg.xins.server.config=`pwd`/conf/xins.properties orion.jar</code></dd>
*
* <dt><strong>3. Configuration file</strong></dt>
* <dd>The configuration file should contain runtime configuration
* settings, like the settings for the logging subsystem.
* <br />System properties are the responsibility of the
* <em>system administrator</em>.
* <br />Example contents for a configuration file:
* <blockquote><code>log4j.rootLogger=DEBUG, console
* <br />log4j.appender.console=org.apache.log4j.ConsoleAppender
* <br />log4j.appender.console.layout=org.apache.log4j.PatternLayout
* <br />log4j.appender.console.layout.ConversionPattern=%d %-5p [%c] %m%n</code></blockquote>
* </dl>
*
* @param config
* the {@link ServletConfig} object which contains build properties for
* this servlet, as specified by the <em>assembler</em>, cannot be
* <code>null</code>.
*
* @throws ServletException
* if the servlet could not be initialized.
*/
public void init(ServletConfig config)
throws ServletException {
Log.log_2000();
// Checks and preparations //
// Make sure the Library class is initialized
String version = Library.getVersion();
// Check preconditions
synchronized (_stateLock) {
if (_state != INITIAL && _state != FRAMEWORK_BOOTSTRAP_FAILED
&& _state != API_CONSTRUCTION_FAILED && _state != API_BOOTSTRAP_FAILED
&& _state != API_INITIALIZATION_FAILED) {
Log.log_2001(_state == null ? null : _state._name);
throw new ServletException();
} else if (config == null) {
Log.log_2002("config == null");
throw new ServletException();
}
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
Log.log_2002("config.getServletContext() == null");
throw new ServletException();
}
// Check the expected vs implemented Java Servlet API version
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != EXPECTED_SERVLET_VERSION_MAJOR || minor != EXPECTED_SERVLET_VERSION_MINOR) {
String expected = "" + EXPECTED_SERVLET_VERSION_MAJOR + '.' + EXPECTED_SERVLET_VERSION_MINOR;
String actual = "" + major + '.' + minor;
Log.log_2003(actual, expected);
}
// Store the ServletConfig object, per the Servlet API Spec, see:
// http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#getServletConfig()
_servletConfig = config;
// Bootstrap framework //
// Proceed to first actual stage
setState(BOOTSTRAPPING_FRAMEWORK);
// Determine configuration file location
try {
_configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY);
} catch (SecurityException exception) {
Log.log_2004(CONFIG_FILE_SYSTEM_PROPERTY, exception.getClass().getName(), exception.getMessage());
setState(FRAMEWORK_BOOTSTRAP_FAILED);
throw new ServletException();
}
// Property value must be set
// NOTE: Don't trim the configuration file name, since it may start
// with a space or other whitespace character.
if (_configFile == null || _configFile.length() < 1) {
Log.log_2005(CONFIG_FILE_SYSTEM_PROPERTY);
setState(FRAMEWORK_BOOTSTRAP_FAILED);
throw new ServletException();
}
// Initialize the logging subsystem
PropertyReader runtimeProperties = readRuntimeProperties();
// Construct API //
// Proceed to next stage
setState(CONSTRUCTING_API);
// Determine the API class
String apiClassName = config.getInitParameter(API_CLASS_PROPERTY);
apiClassName = (apiClassName == null) ? apiClassName : apiClassName.trim();
if (apiClassName == null || apiClassName.length() < 1) {
Log.log_2006(API_CLASS_PROPERTY);
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Load the API class
Class apiClass;
try {
apiClass = Class.forName(apiClassName);
} catch (Throwable exception) {
Log.log_2007(API_CLASS_PROPERTY, apiClassName, exception.getClass().getName(), exception.getMessage());
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Check that the loaded API class is derived from the API base class
if (! API.class.isAssignableFrom(apiClass)) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, API.class.getName() + ".class.isAssignableFrom(apiClass) == false");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Get the SINGLETON field and the value of it
Field singletonField;
try {
singletonField = apiClass.getDeclaredField("SINGLETON");
_api = (API) singletonField.get(null);
} catch (Throwable exception) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, exception.getClass().getName());
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Make sure that the field is an instance of that same class
if (_api == null) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, "apiClass.getDeclaredField(\"SINGLETON\").get(null) == null");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
} else if (_api.getClass() != apiClass) {
Log.log_2008(API_CLASS_PROPERTY, apiClassName, "apiClass.getDeclaredField(\"SINGLETON\").get(null).getClass() != apiClass");
setState(API_CONSTRUCTION_FAILED);
throw new ServletException();
}
// Bootstrap API //
// Proceed to next stage
setState(BOOTSTRAPPING_API);
// Bootstrap the API
boolean succeeded = false;
try {
_api.bootstrap(new ServletConfigPropertyReader(config));
succeeded = true;
} catch (MissingRequiredPropertyException exception) {
Log.log_2009(exception.getPropertyName());
} catch (InvalidPropertyValueException exception) {
Log.log_2010(exception.getPropertyName(), exception.getPropertyValue());
} catch (BootstrapException exception) {
Log.log_2011(exception.getMessage());
} catch (Throwable exception) {
Log.log_2012(exception.getClass().getName(), exception.getMessage());
} finally {
if (succeeded == false) {
setState(API_BOOTSTRAP_FAILED);
throw new ServletException();
}
}
// Initialize the API //
initAPI(runtimeProperties);
// Watch the config file //
int interval = determineConfigReloadInterval(runtimeProperties);
// Create and start a file watch thread
_configFileWatcher = new FileWatcher(_configFile, interval, _configFileListener);
Log.log_4012(_configFile, CONFIG_RELOAD_INTERVAL_PROPERTY, interval);
_configFileWatcher.start();
}
}
/**
* Initializes the API using the specified runtime settings.
*
* @param runtimeProperties
* the runtime settings, guaranteed not to be <code>null</code>.
*/
private final void initAPI(PropertyReader runtimeProperties) {
setState(INITIALIZING_API);
boolean succeeded = false;
try {
_api.init(runtimeProperties);
succeeded = true;
} catch (MissingRequiredPropertyException exception) {
Log.log_4013(exception.getPropertyName());
} catch (InvalidPropertyValueException exception) {
Log.log_4014(exception.getPropertyName(), exception.getPropertyValue());
} catch (InitializationException exception) {
Log.log_4015(exception.getMessage());
} catch (Throwable exception) {
Log.log_4016(exception.getClass().getName(), exception.getMessage());
} finally {
if (succeeded) {
setState(READY);
Log.log_4018();
} else {
setState(API_INITIALIZATION_FAILED);
return;
}
}
}
/**
* Reads the runtime properties file, initializes the logging subsystem
* with the read properties and then returns those properties. If the
* properties cannot be read from the file for any reason, then an empty
* set of properties is returned.
*
* @return
* the properties read from the config file, never <code>null</code>.
*/
private PropertyReader readRuntimeProperties() {
Log.log_3000();
Properties properties = new Properties();
try {
// Open the file
FileInputStream in = new FileInputStream(_configFile);
// Load the properties
properties.load(in);
} catch (FileNotFoundException exception) {
Log.log_3001(_configFile, exception.getClass().getName(), exception.getMessage());
} catch (SecurityException exception) {
Log.log_3002(_configFile, exception.getClass().getName(), exception.getMessage());
} catch (IOException exception) {
Log.log_3003(_configFile, exception.getClass().getName(), exception.getMessage());
}
// TODO: Should we reset the logging subsystem if the Log4J
// TODO properties have been removed from the xins.properties file?
// TODO Determine the current behaviour and make a decision.
// Attempt to configure Log4J
PropertyConfigurator.configure(properties);
// Determine if Log4J is properly initialized
Enumeration appenders = LogManager.getLoggerRepository().getRootLogger().getAllAppenders();
if (appenders instanceof NullEnumeration) {
Log.log_3004(_configFile);
configureLoggerFallback();
} else {
Log.log_3005();
}
// Determine the log locale
String newLocale = properties.getProperty(LOG_LOCALE_PROPERTY);
// If the log locale is set, apply it
if (newLocale != null) {
String currentLocale = Log.getTranslationBundle().getName();
if (currentLocale.equals(newLocale) == false) {
Log.log_3006(currentLocale, newLocale);
try {
Log.setTranslationBundle(newLocale);
Log.log_3007(currentLocale, newLocale);
} catch (NoSuchTranslationBundleException exception) {
Log.log_3008(currentLocale, newLocale);
}
}
}
return new PropertiesPropertyReader(properties);
}
/**
* Returns the <code>ServletConfig</code> object which contains the
* build properties for this servlet. The returned {@link ServletConfig}
* object is the one passed to the {@link #init(ServletConfig)} method.
*
* @return
* the {@link ServletConfig} object that was used to initialize this
* servlet, not <code>null</code> if this servlet is indeed already
* initialized.
*/
public ServletConfig getServletConfig() {
return _servletConfig;
}
/**
* Handles a request to this servlet (wrapper method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Determine context ID
String contextID = request.getParameter("_context");
boolean haveContextID = (contextID != null) && (contextID.length() > 0);
if (haveContextID) {
NDC.push(contextID);
try {
doService(request, response);
} finally {
NDC.pop();
}
} else {
doService(request, response);
}
// TODO: Document _context somewhere
}
/**
* Handles a request to this servlet (implementation method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* <p>This method is called from
* {@link #service(HttpServletRequest,HttpServletResponse}. The latter
* first determines the <em>nested diagnostic context</em> and then
* forwards the call to this method.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
private void doService(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Determine current time
long start = System.currentTimeMillis();
// Determine the remote IP address
String ip = request.getRemoteAddr();
// Check the HTTP request method
String method = request.getMethod();
boolean sendOutput = "GET".equals(method) || "POST".equals(method);
if (!sendOutput) {
if ("OPTIONS".equals(method)) {
Log.log_5001(ip, method);
response.setContentLength(0);
response.setHeader("Accept", "GET, HEAD, POST");
response.setStatus(HttpServletResponse.SC_OK);
return;
} else if ("HEAD".equals(method)) {
response.setContentLength(0);
// If the method is not recognized, return '405 Method Not Allowed'
} else {
Log.log_5000(ip, method);
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
}
Log.log_5001(ip, method);
// XXX: Consider using OutputStream instead of Writer, for improved performance
// Call the API if the state is READY
CallResult result;
State state = getState();
if (state == READY) {
try {
result = _api.handleCall(start, request);
// If access is denied, return '403 Forbidden'
} catch (AccessDeniedException exception) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
// If no matching function is found, return '404 Not Found'
} catch (NoSuchFunctionException exception) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Otherwise return an appropriate 50x HTTP response code
} else if (state == INITIAL
|| state == BOOTSTRAPPING_FRAMEWORK
|| state == CONSTRUCTING_API
|| state == BOOTSTRAPPING_API
|| state == INITIALIZING_API) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Send the output only if GET or POST
if (sendOutput) {
// Determine the XSLT to link to
String xslt = request.getParameter("_xslt");
// Send the XML output to the stream and flush
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
CallResultOutputter.output(out, result, xslt);
out.flush();
}
}
/**
* Destroys this servlet. A best attempt will be made to release all
* resources.
*
* <p>After this method has finished, it will set the state to
* <em>disposed</em>. In that state no more requests will be handled.
*/
public void destroy() {
Log.log_6000();
// Set the state temporarily to DISPOSING
setState(DISPOSING);
// Destroy the API
if (_api != null) {
try {
_api.deinit();
} catch (Throwable exception) {
Log.log_6001(exception.getClass().getName(), exception.getMessage());
}
}
// Set the state to DISPOSED
setState(DISPOSED);
Log.log_6002();
}
// Inner classes
/**
* State of an <code>APIServlet</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private static final class State extends Object {
// Constructors
private State(String name) throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("name", name);
_name = name;
}
// Fields
/**
* The name of this state. Cannot be <code>null</code>.
*/
private final String _name;
// Methods
/**
* Returns the name of this state.
*
* @return
* the name of this state, cannot be <code>null</code>.
*/
String getName() {
return _name;
}
/**
* Returns a textual representation of this object.
*
* @return
* the name of this state, never <code>null</code>.
*/
public String toString() {
return _name;
}
}
/**
* Listener that reloads the configuration file if it changes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
private final class ConfigurationFileListener
extends Object
implements FileWatcher.Listener {
// Constructors
/**
* Constructs a new <code>ConfigurationFileListener</code> object.
*/
private ConfigurationFileListener() {
// empty
}
// Fields
// Methods
public void fileModified() {
Log.log_4007(_configFile);
// Apply the new runtime settings to the logging subsystem
PropertyReader runtimeProperties = readRuntimeProperties();
// Determine the interval
int newInterval = determineConfigReloadInterval(runtimeProperties);
// Update the file watch interval
int oldInterval = _configFileWatcher.getInterval();
if (oldInterval != newInterval) {
_configFileWatcher.setInterval(newInterval);
Log.log_4003(_configFile, oldInterval, newInterval);
}
// Re-initialize the API
initAPI(runtimeProperties);
}
public void fileNotFound() {
Log.log_4000(_configFile);
}
public void fileNotModified() {
Log.log_4002(_configFile);
}
public void securityException(SecurityException exception) {
Log.log_4001(_configFile, exception.getClass().getName(), exception.getMessage());
}
}
}
|
package okapi;
import org.folio.okapi.MainVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.folio.okapi.common.OkapiLogger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@java.lang.SuppressWarnings({"squid:S1192"})
@RunWith(VertxUnitRunner.class)
public class OkapiPerformance {
private final Logger logger = OkapiLogger.get();
private Vertx vertx;
private Async async;
private String locationTenant;
private String locationSample;
private String locationSample2;
private String locationSample3;
private String locationAuth;
private String okapiToken;
private final String okapiTenant = "roskilde";
private long startTime;
private int repeatPostRunning;
private HttpClient httpClient;
private static final String LS = System.lineSeparator();
private int port = 9230;
@Before
public void setUp(TestContext context) {
vertx = Vertx.vertx();
JsonObject conf = new JsonObject()
.put("port", Integer.toString(port));
DeploymentOptions opt = new DeploymentOptions()
.setConfig(conf);
vertx.deployVerticle(MainVerticle.class.getName(),
opt, context.asyncAssertSuccess());
httpClient = vertx.createHttpClient();
}
@After
public void tearDown(TestContext context) {
async = context.async();
td(context);
}
public void td(TestContext context) {
if (locationAuth != null) {
httpClient.delete(port, "localhost", locationAuth, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationAuth = null;
td(context);
});
}).end();
return;
}
if (locationSample != null) {
httpClient.delete(port, "localhost", locationSample, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSample = null;
td(context);
});
}).end();
return;
}
if (locationSample2 != null) {
httpClient.delete(port, "localhost", locationSample2, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSample2 = null;
td(context);
});
}).end();
return;
}
if (locationSample3 != null) {
httpClient.delete(port, "localhost", locationSample3, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSample3 = null;
td(context);
});
}).end();
return;
}
vertx.close(x -> {
async.complete();
});
}
@Test(timeout = 600000)
public void testSample(TestContext context) {
async = context.async();
declareAuth(context);
}
public void declareAuth(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"auth-1.0.0\"," + LS
+ " \"name\" : \"authmodule\"," + LS
+ " \"filters\" : [ {" + LS
+ " \"methods\" : [ \"*\" ]," + LS
+ " \"path\" : \"/s\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " }, {"
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/authn/login\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/modules", response -> {
logger.debug("declareAuth: " + response.statusCode() + " " + response.statusMessage());
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
deployAuth(context);
});
}).end(doc);
}
public void deployAuth(TestContext context) {
final String doc = "{" + LS
+ " \"srvcId\" : \"auth-1.0.0\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-auth-module/target/okapi-test-auth-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
httpClient.post(port, "localhost", "/_/deployment/modules", response -> {
logger.debug("deployAuth: " + response.statusCode() + " " + response.statusMessage());
context.assertEquals(201, response.statusCode());
locationAuth = response.getHeader("Location");
context.assertNotNull(locationAuth);
response.endHandler(x -> {
declareSample(context);
});
}).end(doc);
}
public void declareSample(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module-1.0.0\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"filters\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/modules", response -> {
context.assertEquals(201, response.statusCode());
response.handler(body -> {
context.assertEquals(doc, body.toString());
});
response.endHandler(x -> {
deploySample(context);
});
}).end(doc);
}
public void deploySample(TestContext context) {
final String doc = "{" + LS
+ " \"srvcId\" : \"sample-module-1.0.0\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
httpClient.post(port, "localhost", "/_/deployment/modules", response -> {
context.assertEquals(201, response.statusCode());
locationSample = response.getHeader("Location");
Assert.assertNotNull(locationSample);
response.handler(body -> {
});
response.endHandler(x -> {
createTenant(context);
});
}).end(doc);
}
public void createTenant(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/tenants", response -> {
context.assertEquals(201, response.statusCode());
locationTenant = response.getHeader("Location");
response.handler(body -> {
context.assertEquals(doc, body.toString());
});
response.endHandler(x -> {
tenantEnableModuleAuth(context);
});
}).end(doc);
}
public void tenantEnableModuleAuth(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"auth\"" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/tenants/" + okapiTenant + "/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
tenantEnableModuleSample(context);
});
}).end(doc);
}
public void tenantEnableModuleSample(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/tenants/" + okapiTenant + "/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
doLogin(context);
});
}).end(doc);
}
public void doLogin(TestContext context) {
String doc = "{" + LS
+ " \"tenant\" : \"t1\"," + LS
+ " \"username\" : \"peter\"," + LS
+ " \"password\" : \"peter-password\"" + LS
+ "}";
HttpClientRequest req = httpClient.post(port, "localhost", "/authn/login", response -> {
context.assertEquals(200, response.statusCode());
String headers = response.headers().entries().toString();
okapiToken = response.getHeader("X-Okapi-Token");
response.endHandler(x -> {
useItWithGet(context);
});
});
req.putHeader("X-Okapi-Tenant", okapiTenant);
req.end(doc);
}
public void useItWithGet(TestContext context) {
HttpClientRequest req = httpClient.get(port, "localhost", "/testb", response -> {
context.assertEquals(200, response.statusCode());
String headers = response.headers().entries().toString();
response.handler(x -> {
context.assertEquals("It works", x.toString());
});
response.endHandler(x -> {
useItWithPost(context);
});
});
req.headers().add("X-Okapi-Token", okapiToken);
req.putHeader("X-Okapi-Tenant", okapiTenant);
req.end();
}
public void useItWithPost(TestContext context) {
Buffer body = Buffer.buffer();
HttpClientRequest req = httpClient.post(port, "localhost", "/testb", response -> {
context.assertEquals(200, response.statusCode());
String headers = response.headers().entries().toString();
response.handler(x -> {
body.appendBuffer(x);
});
response.endHandler(x -> {
context.assertEquals("Hello (XML) Okapi", body.toString());
declareSample2(context);
});
});
req.headers().add("X-Okapi-Token", okapiToken);
req.putHeader("X-Okapi-Tenant", okapiTenant);
req.putHeader("Content-Type", "text/xml");
req.end("Okapi");
}
public void declareSample2(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module2-1.0.0\"," + LS
+ " \"name\" : \"sample2\"," + LS
+ " \"filters\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"31\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
deploySample2(context);
});
}).end(doc);
}
public void deploySample2(TestContext context) {
final String doc = "{" + LS
+ " \"instId\" : \"sample2-inst\"," + LS
+ " \"srvcId\" : \"sample-module2-1.0.0\"," + LS
+ " \"url\" : \"http://localhost:9232\"" + LS + "}";
httpClient.post(port, "localhost", "/_/discovery/modules", response -> {
context.assertEquals(201, response.statusCode());
locationSample2 = response.getHeader("Location");
response.endHandler(x -> {
tenantEnableModuleSample2(context);
});
}).end(doc);
}
public void tenantEnableModuleSample2(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/tenants/" + okapiTenant + "/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
// deleteTenant(context);
declareSample3(context);
});
}).end(doc);
}
public void declareSample3(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module3-1.0.0\"," + LS
+ " \"name\" : \"sample3\"," + LS
+ " \"filters\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/sample\"," + LS
+ " \"level\" : \"05\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/sample\"," + LS
+ " \"level\" : \"45\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/sample\"," + LS
+ " \"level\" : \"33\"," + LS
+ " \"type\" : \"request-only\"" + LS
+ " } ]" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
deploySample3(context);
});
}).end(doc);
}
public void deploySample3(TestContext context) {
final String doc = "{" + LS
+ " \"instId\" : \"sample3-inst\"," + LS
+ " \"srvcId\" : \"sample-module3-1.0.0\"," + LS
+ " \"url\" : \"http://localhost:9232\"" + LS + "}";
httpClient.post(port, "localhost", "/_/discovery/modules", response -> {
context.assertEquals(201, response.statusCode());
locationSample3 = response.getHeader("Location");
response.endHandler(x -> {
tenantEnableModuleSample3(context);
});
}).end(doc);
}
public void tenantEnableModuleSample3(TestContext context) {
final String doc = "{" + LS
+ " \"id\" : \"sample-module3-1.0.0\"" + LS
+ "}";
httpClient.post(port, "localhost", "/_/proxy/tenants/" + okapiTenant + "/modules", response -> {
context.assertEquals(201, response.statusCode());
response.endHandler(x -> {
repeatPostInit(context);
});
}).end(doc);
}
public void repeatPostInit(TestContext context) {
repeatPostRunning = 0;
// 10 is enough for regular testing, but the performance improves up to 50k
final int iterations = 10;
//final int iterations = 50000;
final int parallels = 10;
for (int i = 0; i < parallels; i++) {
repeatPostRun(context, 0, iterations, parallels);
}
}
public void repeatPostRun(TestContext context,
int cnt, int max, int parallels) {
final String msg = "Okapi" + cnt;
if (cnt == max) {
if (--repeatPostRunning == 0) {
long timeDiff = (System.nanoTime() - startTime) / 1000000;
logger.info("repeatPost " + timeDiff + " elapsed ms. " + 1000 * max * parallels / timeDiff + " req/sec");
vertx.setTimer(1, x -> deleteTenant(context));
}
return;
} else if (cnt == 0) {
if (repeatPostRunning == 0) {
startTime = System.nanoTime();
}
repeatPostRunning++;
logger.debug("repeatPost " + max + " iterations");
}
Buffer body = Buffer.buffer();
HttpClientRequest req = httpClient.post(port, "localhost", "/testb", response -> {
context.assertEquals(200, response.statusCode());
String headers = response.headers().entries().toString();
response.handler(x -> {
body.appendBuffer(x);
});
response.endHandler(x -> {
context.assertEquals("Hello Hello " + msg, body.toString());
repeatPostRun(context, cnt + 1, max, parallels);
});
response.exceptionHandler(e -> {
context.fail(e);
});
});
req.headers().add("X-Okapi-Token", okapiToken);
req.putHeader("X-Okapi-Tenant", okapiTenant);
req.end(msg);
}
public void deleteTenant(TestContext context) {
httpClient.delete(port, "localhost", locationTenant, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
done(context);
});
}).end();
}
public void done(TestContext context) {
async.complete();
}
}
|
// $Id: ConfObjRegistry.java,v 1.9 2004/03/05 02:40:18 eric Exp $
package com.threerings.admin.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Iterator;
import com.samskivert.io.ByteArrayOutInputStream;
import com.samskivert.util.Config;
import com.samskivert.util.StringUtil;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import com.threerings.presents.dobj.AttributeChangeListener;
import com.threerings.presents.dobj.AttributeChangedEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.EntryAddedEvent;
import com.threerings.presents.dobj.EntryRemovedEvent;
import com.threerings.presents.dobj.EntryUpdatedEvent;
import com.threerings.presents.dobj.SetListener;
import com.threerings.admin.Log;
import com.threerings.presents.dobj.ObjectAccessException;
/**
* Provides a registry of configuration distributed objects. Using
* distributed object to store runtime configuration data can be
* exceptionally useful in that clients (with admin privileges) can view
* and update the running server's configuration parameters on the fly.
*
* <p> Users of the service are responsible for creating their own
* configuration objects which are then registered via this class. The
* config object registry then performs a few functions:
*
* <ul>
* <li> It populates the config object with values from the persistent
* configuration information (see {@link Config} for more information on
* how that works).
* <li> It mirrors object updates out to the persistent configuration
* repository.
* <li> It makes the set of registered objects available for inspection
* and modification via the admin client interface.
* </ul>
*
* <p> Users of this service will want to use {@link AccessController}s on
* their configuration distributed objects to prevent non-administrators
* from subscribing to or modifying the objects.
*/
public class ConfObjRegistry
{
/**
* Registers the supplied configuration object with the system.
*
* @param key a string that identifies this object. These are
* generally hierarchical in nature (of the form
* <code>system.subsystem</code>), for example:
* <code>yohoho.crew</code>.
* @param path The the path in the persistent configuration repository
* (see {@link Config} for more info).
* @param object the object to be registered.
*/
public static void registerObject (String key, String path, DObject object)
{
// create a new config record for this object
_configs.put(key, new ConfObjRecord(path, object));
}
/**
* Returns the config object mapped to the specified key, or null if
* none exists for that key.
*/
public static DObject getObject (String key)
{
ConfObjRecord record = (ConfObjRecord)_configs.get(key);
return (record == null) ? null : record.confObj;
}
/**
* Returns an array containing the keys of all registered
* configuration objects.
*/
public static String[] getKeys ()
{
String[] keys = new String[_configs.size()];
Iterator iter = _configs.keySet().iterator();
for (int ii = 0; iter.hasNext(); ii++) {
keys[ii] = (String)iter.next();
}
return keys;
}
/**
* Contains all necessary info for a configuration object
* registration.
*/
protected static class ConfObjRecord
implements AttributeChangeListener, SetListener
{
public DObject confObj;
public Config config;
public ConfObjRecord (String path, DObject confObj)
{
this.config = new Config(path);
this.confObj = confObj;
// read in the initial configuration settings from the
// persistent configuration repository
Class cclass = confObj.getClass();
try {
Field[] fields = cclass.getFields();
for (int ii = 0; ii < fields.length; ii++) {
int mods = fields[ii].getModifiers();
if ((mods & Modifier.STATIC) != 0 ||
(mods & Modifier.PUBLIC) == 0 ||
(mods & Modifier.TRANSIENT) != 0) {
continue;
}
initField(fields[ii]);
}
// listen for attribute updates
confObj.addListener(this);
} catch (SecurityException se) {
Log.warning("Unable to reflect on " + cclass.getName() + ": " +
se + ". Refusing to monitor object.");
}
}
// documentation inherited
public void entryAdded (EntryAddedEvent event)
{
serializeAttribute(event.getName());
}
// documentation inherited
public void entryUpdated (EntryUpdatedEvent event)
{
serializeAttribute(event.getName());
}
// documentation inherited
public void entryRemoved (EntryRemovedEvent event)
{
serializeAttribute(event.getName());
}
public void attributeChanged (AttributeChangedEvent event)
{
// mirror this configuration update to the on-disk config
String key = fieldToKey(event.getName());
Object value = event.getValue();
if (value instanceof Integer) {
config.setValue(key, ((Integer)value).intValue());
} else if (value instanceof Long) {
config.setValue(key, ((Long)value).longValue());
} else if (value instanceof Float) {
config.setValue(key, ((Float)value).floatValue());
} else if (value instanceof Boolean) {
config.setValue(key, ((Boolean)value).booleanValue());
} else if (value instanceof String) {
config.setValue(key, (String)value);
} else if (value instanceof float[]) {
config.setValue(key, (float[])value);
} else if (value instanceof int[]) {
config.setValue(key, (int[])value);
} else if (value instanceof String[]) {
config.setValue(key, (String[])value);
} else {
Log.info("Unable to flush config object change " +
"[cobj=" + confObj.getClass().getName() +
", key=" + key +
", type=" + value.getClass().getName() +
", value=" + value + "].");
}
}
/** Initializes a single field of a config distributed object from
* its corresponding value in the associated config repository. */
protected void initField (Field field)
{
String key = fieldToKey(field.getName());
Class type = field.getType();
try {
if (type.equals(Boolean.TYPE)) {
boolean defval = field.getBoolean(confObj);
field.setBoolean(confObj, config.getValue(key, defval));
} else if (type.equals(Integer.TYPE)) {
int defval = field.getInt(confObj);
field.setInt(confObj, config.getValue(key, defval));
} else if (type.equals(Long.TYPE)) {
long defval = field.getLong(confObj);
field.setLong(confObj, config.getValue(key, defval));
} else if (type.equals(Float.TYPE)) {
float defval = field.getFloat(confObj);
field.setFloat(confObj, config.getValue(key, defval));
} else if (type.equals(String.class)) {
String defval = (String)field.get(confObj);
field.set(confObj, config.getValue(key, defval));
} else if (type.equals(INT_ARRAY_PROTO.getClass())) {
int[] defval = (int[])field.get(confObj);
field.set(confObj, config.getValue(key, defval));
} else if (type.equals(FLOAT_ARRAY_PROTO.getClass())) {
float[] defval = (float[])field.get(confObj);
field.set(confObj, config.getValue(key, defval));
} else if (type.equals(STRING_ARRAY_PROTO.getClass())) {
String[] defval = (String[])field.get(confObj);
field.set(confObj, config.getValue(key, defval));
} else if (Streamable.class.isAssignableFrom(type)) {
// don't freak out if the conf is blank.
String value = config.getValue(key, "");
if (StringUtil.blank(value)) {
return;
}
try {
ByteArrayInputStream bin = new ByteArrayInputStream(
StringUtil.unhexlate(value));
ObjectInputStream oin = new ObjectInputStream(bin);
field.set(confObj, oin.readObject());
} catch (Exception e) {
Log.warning("Failure decoding config value [type=" +
type + ", field=" + field + ", exception=" +
e + "].");
}
} else {
Log.warning("Can't init field of unknown type " +
"[cobj=" + confObj.getClass().getName() +
", key=" + key +
", type=" + type.getName() + "].");
}
} catch (IllegalAccessException iae) {
Log.warning("Can't set field " +
"[cobj=" + confObj.getClass().getName() +
", key=" + key + ", error=" + iae + "].");
}
}
/**
* Converts a mixed case field name (for example,
* <code>millisPerTick</code>) to a lower case, underscored key
* name (in this case, <code>millis_per_tick</code>).
*/
protected String fieldToKey (String fieldName)
{
StringBuffer key = new StringBuffer();
int flength = fieldName.length();
boolean seenLower = false;
for (int ii = 0; ii < flength; ii++) {
char c = fieldName.charAt(ii);
if (Character.isUpperCase(c)) {
if (seenLower) {
key.append("_");
}
key.append(Character.toLowerCase(c));
seenLower = false;
} else {
key.append(c);
seenLower = true;
}
}
return key.toString();
}
/**
* Get the specified attribute from the configuration object, and
* serialize it.
*/
protected void serializeAttribute (String attributeName)
{
String key = fieldToKey(attributeName);
Object value;
try {
value = confObj.getAttribute(attributeName);
} catch (ObjectAccessException oae) {
Log.warning("Exception getting dset [setname=" + attributeName +
"exception=" + oae + "].");
return;
}
if (value instanceof Streamable) {
serialize(key, value);
} else {
Log.info("Unable to flush config object change " +
"[cobj=" + confObj.getClass().getName() +
", key=" + key +
", type=" + value.getClass().getName() +
", value=" + value + "].");
}
}
/**
* Save the specified object as serialized data associated with
* the specified key.
*/
protected void serialize (String key, Object value)
{
ByteArrayOutInputStream out = new ByteArrayOutInputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
try {
oout.writeObject(value);
oout.flush();
config.setValue(key, StringUtil.hexlate(out.toByteArray()));
} catch (IOException ioe) {
Log.info("Error serializing value " + value);
}
}
protected static final int[] INT_ARRAY_PROTO = new int[0];
protected static final float[] FLOAT_ARRAY_PROTO = new float[0];
protected static final String[] STRING_ARRAY_PROTO = new String[0];
}
/** A mapping from identifying key to config object. */
protected static HashMap _configs = new HashMap();
}
|
package se.citerus.dddsample.domain;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ItineraryTest extends TestCase {
private final Location shanghai = new Location(new UnLocode("CN", "SHA"), "Shanghai");
private final Location rotterdam = new Location(new UnLocode("NL", "RTM"), "Rotterdam");
private final Location goteborg = new Location(new UnLocode("SE", "GOT"), "Goteborg");
private final Location hangzhou = new Location(new UnLocode("CN", "HGH"), "Hangzhou");
private final Location nyc = new Location(new UnLocode("US", "NYC"), "New York");
private final Location longBeach = new Location(new UnLocode("US", "LGB"), "Long Beach");
private final CarrierMovement abc = new CarrierMovement(new CarrierMovementId("ABC"), shanghai, rotterdam);
private final CarrierMovement def = new CarrierMovement(new CarrierMovementId("DEF"), rotterdam, goteborg);
private final CarrierMovement ghi = new CarrierMovement(new CarrierMovementId("GHI"), rotterdam, nyc);
private final CarrierMovement jkl = new CarrierMovement(new CarrierMovementId("JKL"), shanghai, longBeach);
public void testCargoOnTrack() throws Exception {
Cargo cargo = new Cargo(new TrackingId("CARGO1")); //Immutable things go into the constructor
//Mutable things in setters
cargo.setOrigin(shanghai);
cargo.setDestination(goteborg);
Itinerary itinerary = new Itinerary(
new Leg(new CarrierMovementId("ABC"), shanghai, rotterdam),
new Leg(new CarrierMovementId("DEF"), rotterdam, goteborg)
);
//Happy path
HandlingEvent event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.RECEIVE, shanghai);
assertTrue(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.LOAD, shanghai, abc);
assertTrue(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.UNLOAD, rotterdam, abc);
assertTrue(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.LOAD, rotterdam, def);
assertTrue(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.UNLOAD, goteborg, def);
assertTrue(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.CLAIM, goteborg);
assertTrue(itinerary.isExpected(event));
//Customs event changes nothing
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.CUSTOMS, goteborg);
assertTrue(itinerary.isExpected(event));
//Received at the wrong location
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.RECEIVE, hangzhou);
assertFalse(itinerary.isExpected(event));
//Loaded to onto the wrong ship, correct location
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.LOAD, rotterdam, ghi);
assertFalse(itinerary.isExpected(event));
//Unloaded from the wrong ship in the wrong location
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.UNLOAD, longBeach, jkl);
assertFalse(itinerary.isExpected(event));
event = new HandlingEvent(cargo, new Date(), new Date(), HandlingEvent.Type.CLAIM, rotterdam);
assertFalse(itinerary.isExpected(event));
}
public void testNextExpectedEvent() throws Exception {
}
public void testCreateItinerary() throws Exception {
//An empty legs list is not OK:
try {
new Itinerary();
fail("An empty itinerary is not OK");
} catch (IllegalArgumentException iae) {
//Expected
}
try {
new Itinerary(new ArrayList<Leg>());
fail("An empty itinerary is not OK");
} catch (IllegalArgumentException iae) {
//Expected
}
try {
List<Leg> legs = null;
new Itinerary(legs);
fail("Null itinerary is not OK");
} catch (IllegalArgumentException iae) {
//Expected
}
}
}
|
package fr.paris.lutece.portal.service.init;
/**
* this class provides informations about application version
*/
public final class AppInfo
{
/** Defines the current version of the application */
private static final String APP_VERSION = "7.0.5";
static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n"
+ "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n"
+ "|____| \\___/ |_| |___| \\___| |___| /_/ ";
static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n"
+ "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n"
+ "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n"
+ "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\";
/**
* Creates a new AppInfo object.
*/
private AppInfo( )
{
}
/**
* Returns the current version of the application
*
* @return APP_VERSION The current version of the application
*/
public static String getVersion( )
{
return APP_VERSION;
}
}
|
package gnu.expr;
import gnu.bytecode.*;
import gnu.mapping.*;
import gnu.text.*;
public class BindingInitializer extends Initializer
{
Declaration decl;
Expression value;
/** Create a BindingInitializer and link it into the correct
* initializer chain. */
public static void create (Declaration decl, Expression value,
Compilation comp)
{
BindingInitializer init = new BindingInitializer(decl, value);
if (decl.field != null ? decl.field.getStaticFlag() : decl.isStatic())
{
init.next = comp.clinitChain;
comp.clinitChain = init;
}
else
{
init.next = comp.mainLambda.initChain; // FIXME why mainLambda?
comp.mainLambda.initChain = init;
}
}
public BindingInitializer(Declaration decl, Expression value)
{
this.decl = decl;
this.value = value;
this.field = decl.field;
}
public void emit(Compilation comp)
{
if (decl.ignorable())
{
if (value != null)
value.compile(comp, Target.Ignore);
return;
}
CodeAttr code = comp.getCode();
if (value instanceof QuoteExp)
{
Object val = ((QuoteExp) value).getValue();
if (val != null && ! (val instanceof String))
{
Literal lit = comp.litTable.findLiteral(val);
if (lit.field == this.field)
return;
}
}
int line = decl.getLineNumber();
SourceMessages messages = comp.getMessages();
SourceLocator saveLoc = messages.swapSourceLocator(decl);
if (line > 0)
code.putLineNumber(decl.getFileName(), line);
if (field != null && ! field.getStaticFlag())
code.emitPushThis();
if (value == null)
{
boolean func = comp.getLanguage().hasSeparateFunctionNamespace();
Object property
= func && decl.isProcedureDecl() ? EnvironmentKey.FUNCTION : null;
Object name = decl.getSymbol();
if (decl.getFlag(Declaration.IS_UNKNOWN|Declaration.IS_DYNAMIC))
{
if (name instanceof String)
name = Namespace.EmptyNamespace.getSymbol((String) name);
comp.compileConstant(name, Target.pushObject);
if (property == null)
code.emitPushNull();
else
comp.compileConstant(property, Target.pushObject);
code.emitInvokeStatic(typeThreadLocation.getDeclaredMethod("getInstance", 2));
}
else if (decl.isFluid())
{
// This is basically an optimization, since if we don't initialize
// to an anonymous ThreadLocation, then a fluid-let will lazily
// do it - in NamedLocation.setWithSave.
Type[] atypes = new Type[1];
atypes[0] = name instanceof Symbol ? Compilation.typeSymbol
: Type.toStringType;
comp.compileConstant(name, Target.pushObject);
Method m = typeThreadLocation
.getDeclaredMethod("makeAnonymous", atypes);
code.emitInvokeStatic(m);
}
else
{
comp.compileConstant(name, Target.pushObject);
code.emitInvokeStatic(makeLocationMethod(name));
}
}
else
{
Type type = field == null ? decl.getType() : field.getType();
value.compileWithPosition(comp, StackTarget.getInstance(type));
}
// Optimization of Declaration.compileStore, to avoid swap.
if (field == null)
{
Variable var = decl.getVariable();
if (var == null)
var = decl.allocateVariable(code);
code.emitStore(var);
}
else if (field.getStaticFlag())
code.emitPutStatic(field);
else
code.emitPutField(field);
messages.swapSourceLocator(saveLoc);
}
static final ClassType typeThreadLocation =
ClassType.make("gnu.mapping.ThreadLocation");
public static Method makeLocationMethod (Object name)
{
Type[] atypes = new Type[1];
if (name instanceof Symbol)
atypes[0] = Compilation.typeSymbol;
else
atypes[0] = Type.javalangStringType;
return Compilation.typeLocation.getDeclaredMethod("make", atypes);
}
}
|
/*
* Class LineBreakpoint
* @author Jeka
*/
package com.intellij.debugger.ui.breakpoints;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.xdebugger.ui.DebuggerIcons;
import com.sun.jdi.*;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.request.BreakpointRequest;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
public class LineBreakpoint extends BreakpointWithHighlighter {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.LineBreakpoint");
// icons
public static Icon ICON = DebuggerIcons.ENABLED_BREAKPOINT_ICON;
public static final Icon DISABLED_ICON = DebuggerIcons.DISABLED_BREAKPOINT_ICON;
private static Icon ourVerifiedWarningsIcon = IconLoader.getIcon("/debugger/db_verified_warning_breakpoint.png");
private String myMethodName;
public static final @NonNls Key<LineBreakpoint> CATEGORY = BreakpointCategory.lookup("line_breakpoints");
protected LineBreakpoint(Project project) {
super(project);
}
protected LineBreakpoint(Project project, RangeHighlighter highlighter) {
super(project, highlighter);
}
protected Icon getDisabledIcon() {
final Breakpoint master = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().findMasterBreakpoint(this);
return master == null? DISABLED_ICON : DebuggerIcons.DISABLED_DEPENDENT_BREAKPOINT_ICON;
}
protected Icon getSetIcon() {
return ICON;
}
protected Icon getInvalidIcon() {
return DebuggerIcons.INVALID_BREAKPOINT_ICON;
}
protected Icon getVerifiedIcon() {
return DebuggerIcons.VERIFIED_BREAKPOINT_ICON;
}
protected Icon getVerifiedWarningsIcon() {
return ourVerifiedWarningsIcon;
}
public Key<LineBreakpoint> getCategory() {
return CATEGORY;
}
protected void reload(PsiFile file) {
super.reload(file);
myMethodName = LineBreakpoint.findMethodName(file, getHighlighter().getStartOffset());
}
protected void createRequestForPreparedClass(final DebugProcessImpl debugProcess, final ReferenceType classType) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
List<Location> locs = debugProcess.getPositionManager().locationsOfLine(classType, getSourcePosition());
if (locs.size() > 0) {
for (final Location location : locs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found location for reference type " + classType.name() + " at line " + getLineIndex() + "; isObsolete: " + (debugProcess.getVirtualMachineProxy().versionHigher("1.4") && location.method().isObsolete()));
}
BreakpointRequest request = debugProcess.getRequestsManager().createBreakpointRequest(LineBreakpoint.this, location);
debugProcess.getRequestsManager().enableRequest(request);
if (LOG.isDebugEnabled()) {
LOG.debug("Created breakpoint request for reference type " + classType.name() + " at line " + getLineIndex());
}
}
}
else {
// there's no executable code in this class
debugProcess.getRequestsManager().setInvalid(LineBreakpoint.this, DebuggerBundle.message(
"error.invalid.breakpoint.no.executable.code", (getLineIndex() + 1), classType.name())
);
if (LOG.isDebugEnabled()) {
LOG.debug("No locations of type " + classType.name() + " found at line " + getLineIndex());
}
}
}
catch (ClassNotPreparedException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("ClassNotPreparedException: " + ex.getMessage());
}
// there's a chance to add a breakpoint when the class is prepared
}
catch (ObjectCollectedException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("ObjectCollectedException: " + ex.getMessage());
}
// there's a chance to add a breakpoint when the class is prepared
}
catch (InvalidLineNumberException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("InvalidLineNumberException: " + ex.getMessage());
}
debugProcess.getRequestsManager().setInvalid(LineBreakpoint.this, DebuggerBundle.message("error.invalid.breakpoint.bad.line.number"));
}
catch (InternalException ex) {
LOG.info(ex);
}
catch(Exception ex) {
LOG.info(ex);
}
updateUI();
}
});
}
public boolean evaluateCondition(EvaluationContextImpl context, LocatableEvent event) throws EvaluateException {
if(CLASS_FILTERS_ENABLED){
Value value = context.getThisObject();
ObjectReference thisObject = (ObjectReference)value;
if(thisObject == null) {
return false;
}
String name = DebuggerUtilsEx.getQualifiedClassName(thisObject.referenceType().name(), getProject());
if(name == null) {
return false;
}
ClassFilter [] filters = getClassFilters();
boolean matches = false;
for (int i = 0; i < filters.length; i++) {
ClassFilter classFilter = filters[i];
if(classFilter.isEnabled() && classFilter.matches(name)) {
matches = true;
break;
}
}
if(!matches) {
return false;
}
ClassFilter [] ifilters = getClassExclusionFilters();
for (int i = 0; i < ifilters.length; i++) {
ClassFilter classFilter = ifilters[i];
if(classFilter.isEnabled() && classFilter.matches(name)) {
return false;
}
}
}
return super.evaluateCondition(context, event);
}
public String toString() {
return getDescription();
}
public String getDisplayName() {
final int lineNumber = (getHighlighter().getDocument().getLineNumber(getHighlighter().getStartOffset()) + 1);
if(isValid()) {
final String className = getClassName();
final boolean hasClassInfo = className != null && className.length() > 0;
final boolean hasMethodInfo = myMethodName != null && myMethodName.length() > 0;
if (hasClassInfo || hasMethodInfo) {
final StringBuilder info = StringBuilderSpinAllocator.alloc();
try {
if (hasClassInfo) {
info.append(className);
}
if(hasMethodInfo) {
if (hasClassInfo) {
info.append(".");
}
info.append(myMethodName);
}
return DebuggerBundle.message("line.breakpoint.display.name.with.class.or.method", lineNumber, info.toString());
}
finally {
StringBuilderSpinAllocator.dispose(info);
}
}
return DebuggerBundle.message("line.breakpoint.display.name", lineNumber);
}
return DebuggerBundle.message("status.breakpoint.invalid");
}
private static @Nullable String findMethodName(final PsiFile file, final int offset) {
if (file instanceof JspFile) {
return null;
}
if (file instanceof PsiJavaFile) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
final PsiMethod method = DebuggerUtilsEx.findPsiMethod(file, offset);
return method != null? method.getName() + "()" : null;
}
});
}
return null;
}
public String getEventMessage(LocatableEvent event) {
final Location location = event.location();
try {
return DebuggerBundle.message(
"status.line.breakpoint.reached",
location.declaringType().name() + "." + location.method().name(),
location.sourceName(),
getLineIndex() + 1
);
}
catch (AbsentInformationException e) {
final String sourceName = getSourcePosition().getFile().getName();
return DebuggerBundle.message(
"status.line.breakpoint.reached",
location.declaringType().name() + "." + location.method().name(),
sourceName,
getLineIndex() + 1
);
}
}
public PsiElement getEvaluationElement() {
return PositionUtil.getContextElement(getSourcePosition());
}
protected static LineBreakpoint create(Project project, Document document, int lineIndex) {
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) return null;
LineBreakpoint breakpoint = new LineBreakpoint(project, createHighlighter(project, document, lineIndex));
return (LineBreakpoint)breakpoint.init();
}
public boolean canMoveTo(SourcePosition position) {
if (!super.canMoveTo(position)) {
return false;
}
final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(position.getFile());
return canAddLineBreakpoint(myProject, document, position.getLine());
}
public static boolean canAddLineBreakpoint(Project project, final Document document, final int lineIndex) {
if (lineIndex < 0 || lineIndex >= document.getLineCount()) {
return false;
}
final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager();
final LineBreakpoint breakpointAtLine = breakpointManager.findBreakpoint( document, document.getLineStartOffset(lineIndex), CATEGORY);
if (breakpointAtLine != null) {
// there already exists a line breakpoint at this line
return false;
}
PsiDocumentManager.getInstance(project).commitDocument(document);
final boolean[] canAdd = new boolean[]{false};
DebuggerUtilsEx.iterateLine(project, document, lineIndex, new DebuggerUtilsEx.ElementVisitor() {
public boolean acceptElement(PsiElement element) {
if ((element instanceof PsiWhiteSpace) || (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null)) {
return false;
}
PsiElement child = element;
while(element != null) {
final int offset = element.getTextOffset();
if (offset >= 0) {
if (document.getLineNumber(offset) != lineIndex) {
break;
}
}
child = element;
element = element.getParent();
}
if(child instanceof PsiMethod && child.getTextRange().getEndOffset() >= document.getLineEndOffset(lineIndex)) {
PsiCodeBlock body = ((PsiMethod)child).getBody();
if(body == null) {
canAdd[0] = false;
}
else {
PsiStatement[] statements = body.getStatements();
canAdd[0] = statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == lineIndex;
}
}
else {
canAdd[0] = true;
}
return true;
}
});
return canAdd[0];
}
public @Nullable String getMethodName() {
return myMethodName;
}
}
|
package com.intellij.openapi.command.impl;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.command.*;
import com.intellij.openapi.command.undo.*;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorStateLevel;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileEvent;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.containers.HashSet;
import com.intellij.CommonBundle;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiDocumentManager;
import java.util.*;
public class UndoManagerImpl extends UndoManager implements ProjectComponent, ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.command.impl.UndoManagerImpl");
public static final int GLOBAL_UNDO_LIMIT = 10;
public static final int LOCAL_UNDO_LIMIT = 100;
public static final int COMMANDS_TO_KEEP_LIVE_QUEUES = 100;
public static final int COMMAND_TO_RUN_COMPACT = 20;
public static final int FREE_QUEUES_LIMIT = 30;
private ProjectEx myProject;
private int myCommandLevel = 0;
private static final int NONE = 0;
private static final int UNDO = 1;
private static final int REDO = 2;
private int myCurrentOperationState = NONE;
private CommandMerger myLastMerger;
private CommandListener myCommandListener;
private final UndoRedoStacksHolder myUndoStacksHolder = new UndoRedoStacksHolder();
private final UndoRedoStacksHolder myRedoStacksHolder = new UndoRedoStacksHolder();
DocumentEditingUndoProvider myDocumentEditingUndoProvider;
private CommandMerger myCurrentMerger;
private CurrentEditorProvider myCurrentEditorProvider;
private FileOperationsUndoProvider myFileOperationUndoProvider;
private Project myCurrentActionProject = DummyProject.getInstance();
private int myCommandCounter = 1;
private MyBeforeDeletionListener myBeforeFileDeletionListener;
private CommandProcessor myCommandProcessor;
private EditorFactory myEditorFactory;
private VirtualFileManager myVirtualFileManager;
private StartupManager myStartupManager;
public UndoManagerImpl(Project project,
Application application,
CommandProcessor commandProcessor,
EditorFactory editorFactory,
VirtualFileManager virtualFileManager,
StartupManager startupManager) {
myProject = (ProjectEx)project;
myCommandProcessor = commandProcessor;
myEditorFactory = editorFactory;
myVirtualFileManager = virtualFileManager;
myStartupManager = startupManager;
init(application);
}
public UndoManagerImpl(Application application,
CommandProcessor commandProcessor,
EditorFactory editorFactory,
VirtualFileManager virtualFileManager) {
myProject = null;
myCommandProcessor = commandProcessor;
myEditorFactory = editorFactory;
myVirtualFileManager = virtualFileManager;
init(application);
}
private void init(Application application) {
if (myProject == null || application.isUnitTestMode() && !myProject.isDefault() && !myProject.isDummy()) {
initialize();
}
}
public String getComponentName() {
return "UndoManager";
}
public Project getProject() {
return myProject;
}
public void initComponent() { }
private void initialize() {
Runnable initAction = new Runnable() {
public void run() {
runStartupActivity();
}
};
if (myProject != null) {
myStartupManager.registerStartupActivity(initAction);
}
else {
initAction.run();
}
}
public void runStartupActivity() {
myCurrentEditorProvider = new FocusBasedCurrentEditorProvider();
myCommandListener = new CommandAdapter() {
private boolean myFakeCommandStarted = false;
public void commandStarted(CommandEvent event) {
onCommandStarted(event.getProject(), event.getUndoConfirmationPolicy());
}
public void commandFinished(CommandEvent event) {
onCommandFinished(event.getProject(), event.getCommandName(), event.getCommandGroupId());
}
public void undoTransparentActionStarted() {
if (!isInsideCommand()) {
myFakeCommandStarted = true;
onCommandStarted(myProject, UndoConfirmationPolicy.DEFAULT);
}
}
public void undoTransparentActionFinished() {
if (myFakeCommandStarted) {
myFakeCommandStarted = false;
onCommandFinished(myProject, "", null);
}
}
};
myCommandProcessor.addCommandListener(myCommandListener);
myDocumentEditingUndoProvider = new DocumentEditingUndoProvider(myProject, myEditorFactory);
myLastMerger = new CommandMerger(this, myEditorFactory);
myFileOperationUndoProvider = new FileOperationsUndoProvider(this, myProject);
myBeforeFileDeletionListener = new MyBeforeDeletionListener();
myVirtualFileManager.addVirtualFileListener(myBeforeFileDeletionListener);
}
public void onCommandFinished(final Project project,
final String commandName,
final Object commandGroupId) {
commandFinished(commandName, commandGroupId);
if (myCommandLevel == 0) {
myFileOperationUndoProvider.commandFinished(project);
myCurrentActionProject = DummyProject.getInstance();
}
LOG.assertTrue(myCommandLevel == 0 || !(myCurrentActionProject instanceof DummyProject));
}
private void onCommandStarted(final Project project, UndoConfirmationPolicy undoConfirmationPolicy) {
if (myCommandLevel == 0) {
myFileOperationUndoProvider.commandStarted(project);
myCurrentActionProject = project;
}
commandStarted(undoConfirmationPolicy);
LOG.assertTrue(myCommandLevel == 0 || !(myCurrentActionProject instanceof DummyProject));
}
public void dropHistory() {
// Run dummy command in order to drop all mergers...
CommandProcessor.getInstance().executeCommand(myProject, EmptyRunnable.getInstance(),
CommonBundle.message("drop.undo.history.command.name"), null);
LOG.assertTrue(myCommandLevel == 0);
myUndoStacksHolder.dropHistory();
myRedoStacksHolder.dropHistory();
}
public void disposeComponent() {
if (myCommandListener != null) {
myCommandProcessor.removeCommandListener(myCommandListener);
myDocumentEditingUndoProvider.dispose();
myLastMerger.dispose();
myFileOperationUndoProvider.dispose();
}
myVirtualFileManager.removeVirtualFileListener(myBeforeFileDeletionListener);
myProject = null;
}
public void setCurrentEditorProvider(CurrentEditorProvider currentEditorProvider) {
myCurrentEditorProvider = currentEditorProvider;
}
public void projectOpened() {
initialize();
}
public void projectClosed() {
}
public void clearUndoRedoQueue(FileEditor editor) {
LOG.assertTrue(myCommandLevel == 0);
myLastMerger.flushCurrentCommand();
disposeCurrentMerger();
myUndoStacksHolder.clearEditorStack(editor);
myRedoStacksHolder.clearEditorStack(editor);
}
public void clearUndoRedoQueue(Document document) {
clearUndoRedoQueue(DocumentReferenceByDocument.createDocumentReference(document));
}
public void clearUndoRedoQueue(DocumentReference docRef) {
myLastMerger.flushCurrentCommand();
disposeCurrentMerger();
myUndoStacksHolder.clearFileQueue(docRef);
myRedoStacksHolder.clearFileQueue(docRef);
}
public void clearUndoRedoQueue(VirtualFile file) {
clearUndoRedoQueue(new DocumentReferenceByVirtualFile(file));
}
public void compact() {
if (myCurrentOperationState == NONE && myCommandCounter % COMMAND_TO_RUN_COMPACT == 0) {
doCompact();
}
}
private void doCompact() {
Set<DocumentReference> docsOnHold = new HashSet<DocumentReference>(myUndoStacksHolder.getAffectedDocuments());
docsOnHold.addAll(myRedoStacksHolder.getAffectedDocuments());
docsOnHold.removeAll(myUndoStacksHolder.getDocsInGlobalQueue());
docsOnHold.removeAll(myRedoStacksHolder.getDocsInGlobalQueue());
Set<DocumentReference> openedDocs = new HashSet<DocumentReference>();
for (DocumentReference docRef : docsOnHold) {
final VirtualFile file = docRef.getFile();
if (file != null) {
if (myProject != null && FileEditorManager.getInstance(myProject).isFileOpen(file)) {
openedDocs.add(docRef);
}
}
else {
Document document = docRef.getDocument();
if (document != null && EditorFactory.getInstance().getEditors(document, myProject).length > 0) {
openedDocs.add(docRef);
}
}
}
docsOnHold.removeAll(openedDocs);
if (docsOnHold.size() <= FREE_QUEUES_LIMIT) return;
final DocumentReference[] freeDocs = docsOnHold.toArray(new DocumentReference[docsOnHold.size()]);
Arrays.sort(freeDocs, new Comparator<DocumentReference>() {
public int compare(DocumentReference docRef1, DocumentReference docRef2) {
return getRefAge(docRef1) - getRefAge(docRef2);
}
});
for (int i = 0; i < freeDocs.length - FREE_QUEUES_LIMIT; i++) {
DocumentReference doc = freeDocs[i];
if (getRefAge(doc) + COMMANDS_TO_KEEP_LIVE_QUEUES > myCommandCounter) break;
clearUndoRedoQueue(doc);
}
}
private int getRefAge(DocumentReference ref) {
return Math.max(myUndoStacksHolder.getYoungestCommandAge(ref),
myRedoStacksHolder.getYoungestCommandAge(ref));
}
public void undoableActionPerformed(UndoableAction action) {
if (myCurrentOperationState != NONE) return;
if (myCommandLevel == 0) {
LOG.assertTrue(action instanceof NonUndoableAction,
"Undoable actions allowed inside commands only (see com.intellij.openapi.command.CommandProcessor.executeCommand())");
commandStarted(UndoConfirmationPolicy.DEFAULT);
myCurrentMerger.add(action, false);
commandFinished("", null);
return;
}
myCurrentMerger.add(action, CommandProcessor.getInstance().isUndoTransparentActionInProgress());
}
public boolean isUndoInProgress() {
return myCurrentOperationState == UNDO;
}
public boolean isRedoInProgress() {
return myCurrentOperationState == REDO;
}
public void undo(FileEditor editor) {
LOG.assertTrue(isUndoAvailable(editor));
myCurrentOperationState = UNDO;
undoOrRedo(editor);
}
public void redo(FileEditor editor) {
LOG.assertTrue(isRedoAvailable(editor));
myCurrentOperationState = REDO;
undoOrRedo(editor);
}
private void undoOrRedo(final FileEditor editor) {
final RuntimeException[] exception = new RuntimeException[1];
Runnable executeUndoOrRedoAction = new Runnable() {
public void run() {
try {
if (isUndoInProgress()) {
myLastMerger.undoOrRedo(editor, true);
}
else {
myLastMerger.undoOrRedo(editor, false);
}
}
catch (RuntimeException ex) {
exception[0] = ex;
}
finally {
myCurrentOperationState = NONE;
}
}
};
CommandProcessor.getInstance().executeCommand(myProject, executeUndoOrRedoAction,
isUndoInProgress() ? CommonBundle.message("undo.command.name") : CommonBundle
.message("redo.command.name"), null, myLastMerger.getUndoConfirmationPolicy());
if (exception[0] != null) throw exception[0];
}
public boolean isUndoAvailable(FileEditor editor) {
if (editor != null) {
if (editor instanceof TextEditor) {
Editor activeEditor = ((TextEditor)editor).getEditor();
if (activeEditor.isViewer()) {
return false;
}
}
Document[] documents = TextEditorProvider.getDocuments(editor);
if (documents == null || documents.length == 0) return false;
for (Document document : documents) {
if (myLastMerger != null && !myLastMerger.isEmpty(DocumentReferenceByDocument.createDocumentReference(document))) {
return true;
}
LinkedList localStack = getUndoStacksHolder().getStack(document);
if (!localStack.isEmpty()) {
return true;
}
}
return false;
}
else {
if (myLastMerger != null && myLastMerger.isComplex() && !myLastMerger.isEmpty()) return true;
return !myUndoStacksHolder.getGlobalStack().isEmpty();
}
}
public boolean isRedoAvailable(FileEditor editor) {
if (editor != null) {
if (editor instanceof TextEditor) {
Editor activeEditor = ((TextEditor)editor).getEditor();
if (activeEditor.isViewer()) {
return false;
}
}
Document[] documents = TextEditorProvider.getDocuments(editor);
if (documents == null || documents.length == 0){
return false;
}
for (Document document : documents) {
LinkedList localStack = getRedoStacksHolder().getStack(document);
if (!localStack.isEmpty()) {
return true;
}
}
return false;
}
else {
return !myRedoStacksHolder.getGlobalStack().isEmpty();
}
}
public boolean isActive() {
return Comparing.equal(myProject, myCurrentActionProject);
}
private void commandStarted(UndoConfirmationPolicy undoConfirmationPolicy) {
if (myCommandLevel == 0) {
myCurrentMerger = new CommandMerger(this, EditorFactory.getInstance());
}
LOG.assertTrue(myCurrentMerger != null, String.valueOf(myCommandLevel));
myCurrentMerger.setBeforeState(getCurrentState());
myCurrentMerger.mergeUndoConfirmationPolicy(undoConfirmationPolicy);
myCommandLevel++;
}
private EditorAndState getCurrentState() {
FileEditor editor = myCurrentEditorProvider.getCurrentEditor();
if (editor == null) {
return null;
}
return new EditorAndState(editor, editor.getState(FileEditorStateLevel.UNDO));
}
private void commandFinished(String commandName, Object groupId) {
if (myCommandLevel == 0) return; // possible if command listener is added within command
myCommandLevel
if (myCommandLevel > 0) return;
myCurrentMerger.setAfterState(getCurrentState());
myLastMerger.commandFinished(commandName, groupId, myCurrentMerger);
disposeCurrentMerger();
}
private void disposeCurrentMerger() {
LOG.assertTrue(myCommandLevel == 0);
if (myCurrentMerger != null) {
myCurrentMerger.dispose();
myCurrentMerger = null;
}
}
public UndoRedoStacksHolder getUndoStacksHolder() {
return myUndoStacksHolder;
}
public UndoRedoStacksHolder getRedoStacksHolder() {
return myRedoStacksHolder;
}
public boolean isInsideCommand() {
return myCommandLevel > 0;
}
public boolean undoableActionsForDocumentAreEmpty(DocumentReference docRef) {
if (myCurrentMerger != null && !myCurrentMerger.isEmpty(docRef)) return false;
if (myLastMerger != null && !myLastMerger.isEmpty(docRef)) return false;
if (!myUndoStacksHolder.getStack(docRef).isEmpty()) return false;
LinkedList<UndoableGroup> globalStack = myUndoStacksHolder.getGlobalStack();
for (final UndoableGroup group : globalStack) {
Collection<DocumentReference> affectedDocuments = group.getAffectedDocuments();
if (affectedDocuments.contains(docRef)) return false;
}
return true;
}
public int getCommandCounterAndInc() {
return ++myCommandCounter;
}
public DocumentReference findInvalidatedReferenceByUrl(String url) {
DocumentReference result = findInvalidatedReferenceByUrl(myUndoStacksHolder.getAffectedDocuments(), url);
if (result != null) return result;
result = findInvalidatedReferenceByUrl(myRedoStacksHolder.getAffectedDocuments(), url);
if (result != null) return result;
result = findInvalidatedReferenceByUrl(myRedoStacksHolder.getGlobalStackAffectedDocuments(), url);
if (result != null) return result;
if (myLastMerger != null) {
result = findInvalidatedReferenceByUrl(myLastMerger.getAffectedDocuments(), url);
if (result != null) return result;
}
if (myCurrentMerger != null) {
result = findInvalidatedReferenceByUrl(myCurrentMerger.getAffectedDocuments(), url);
if (result != null) return result;
}
return null;
}
private DocumentReference findInvalidatedReferenceByUrl(Collection<DocumentReference> collection, String url) {
for (final DocumentReference documentReference : collection) {
if (documentReference.equalsByUrl(url)) return documentReference;
}
return null;
}
public void markDocumentForUndo(PsiFile file) {
Project project = file.getProject();
final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
final DocumentReference ref = DocumentReferenceByDocument.createDocumentReference(document);
undoableActionPerformed(new UndoableAction() {
public void undo() {}
public void redo() {}
public DocumentReference[] getAffectedDocuments() {
return new DocumentReference[] {ref};
}
public boolean isComplex() { return false; }
});
}
private class MyBeforeDeletionListener extends VirtualFileAdapter {
public void beforeFileDeletion(VirtualFileEvent event) {
VirtualFile file = event.getFile();
beforeFileDeletion(file, myUndoStacksHolder.getAffectedDocuments());
beforeFileDeletion(file, myUndoStacksHolder.getGlobalStackAffectedDocuments());
beforeFileDeletion(file, myRedoStacksHolder.getAffectedDocuments());
beforeFileDeletion(file, myRedoStacksHolder.getGlobalStackAffectedDocuments());
if (myLastMerger != null) beforeFileDeletion(file, myLastMerger.getAffectedDocuments());
if (myCurrentMerger != null) beforeFileDeletion(file, myCurrentMerger.getAffectedDocuments());
}
private void beforeFileDeletion(VirtualFile file, Collection<DocumentReference> docs) {
for (final DocumentReference documentReference : docs) {
documentReference.beforeFileDeletion(file);
}
}
}
}
|
package org.deeplearning4j.eval;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.random.impl.BernoulliDistribution;
import org.nd4j.linalg.api.ops.random.impl.BinomialDistribution;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.NDArrayIndex;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class ROCTest {
private static Map<Double,Double> expTPR;
private static Map<Double,Double> expFPR;
static {
expTPR = new HashMap<>();
double totalPositives = 5.0;
expTPR.put(0/10.0, 5.0/totalPositives); //All 10 predicted as class 1, of which 5 of 5 are correct
expTPR.put(1/10.0, 5.0/totalPositives);
expTPR.put(2/10.0, 5.0/totalPositives);
expTPR.put(3/10.0, 5.0/totalPositives);
expTPR.put(4/10.0, 5.0/totalPositives);
expTPR.put(5/10.0, 5.0/totalPositives);
expTPR.put(6/10.0, 4.0/totalPositives); //Threshold: 0.4 -> last 4 predicted; last 5 actual
expTPR.put(7/10.0, 3.0/totalPositives);
expTPR.put(8/10.0, 2.0/totalPositives);
expTPR.put(9/10.0, 1.0/totalPositives);
expTPR.put(10/10.0, 0.0/totalPositives);
expFPR = new HashMap<>();
double totalNegatives = 5.0;
expFPR.put(0/10.0, 5.0/totalNegatives); //All 10 predicted as class 1, but all 5 true negatives are predicted positive
expFPR.put(1/10.0, 4.0/totalNegatives); //1 true negative is predicted as negative; 4 false positives
expFPR.put(2/10.0, 3.0/totalNegatives); //2 true negatives are predicted as negative; 3 false positives
expFPR.put(3/10.0, 2.0/totalNegatives);
expFPR.put(4/10.0, 1.0/totalNegatives);
expFPR.put(5/10.0, 0.0/totalNegatives);
expFPR.put(6/10.0, 0.0/totalNegatives);
expFPR.put(7/10.0, 0.0/totalNegatives);
expFPR.put(8/10.0, 0.0/totalNegatives);
expFPR.put(9/10.0, 0.0/totalNegatives);
expFPR.put(10/10.0, 0.0/totalNegatives);
}
@Test
public void testRocBasic(){
//2 outputs here - probability distribution over classes (softmax)
INDArray predictions = Nd4j.create(new double[][]{
{1.0, 0.001}, //add 0.001 to avoid numerical/rounding issues (float vs. double, etc)
{0.899, 0.101},
{0.799, 0.201},
{0.699, 0.301},
{0.599, 0.401},
{0.499, 0.501},
{0.399, 0.601},
{0.299, 0.701},
{0.199, 0.801},
{0.099, 0.901}});
INDArray actual = Nd4j.create(new double[][]{
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{0, 1},
{0, 1},
{0, 1},
{0, 1},
{0, 1}});
ROC roc = new ROC(10);
roc.eval(actual, predictions);
List<ROC.ROCValue> list = roc.getResults();
assertEquals(11,list.size()); //0 + 10 steps
for( int i=0; i<11; i++ ){
ROC.ROCValue v = list.get(i);
double expThreshold = i / 10.0;
assertEquals(expThreshold, v.getThreshold(), 1e-5);
// System.out.println("t=" + expThreshold + "\t" + v.getFalsePositiveRate() + "\t" + v.getTruePositiveRate());
double efpr = expFPR.get(expThreshold);
double afpr = v.getFalsePositiveRate();
assertEquals(efpr, afpr, 1e-5);
double etpr = expTPR.get(expThreshold);
double atpr = v.getTruePositiveRate();
assertEquals(etpr, atpr, 1e-5);
}
//Expect AUC == 1.0 here
double auc = roc.calculateAUC();
assertEquals(1.0, auc, 1e-6);
}
@Test
public void testRocBasicSingleClass(){
//1 output here - single probability value (sigmoid)
//add 0.001 to avoid numerical/rounding issues (float vs. double, etc)
INDArray predictions = Nd4j.create(new double[]{0.001, 0.101, 0.201, 0.301, 0.401, 0.501, 0.601, 0.701, 0.801, 0.901}, new int[]{10,1});
INDArray actual = Nd4j.create(new double[]{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1}, new int[]{10,1});
ROC roc = new ROC(10);
roc.eval(actual, predictions);
List<ROC.ROCValue> list = roc.getResults();
assertEquals(11,list.size()); //0 + 10 steps
for( int i=0; i<11; i++ ){
ROC.ROCValue v = list.get(i);
double expThreshold = i / 10.0;
assertEquals(expThreshold, v.getThreshold(), 1e-5);
// System.out.println("t=" + expThreshold + "\t" + v.getFalsePositiveRate() + "\t" + v.getTruePositiveRate());
double efpr = expFPR.get(expThreshold);
double afpr = v.getFalsePositiveRate();
assertEquals(efpr, afpr, 1e-5);
double etpr = expTPR.get(expThreshold);
double atpr = v.getTruePositiveRate();
assertEquals(etpr, atpr, 1e-5);
}
//Expect AUC == 1.0 here
double auc = roc.calculateAUC();
assertEquals(1.0, auc, 1e-6);
}
@Test
public void testRoc(){
//Previous tests allowed for a perfect classifier with right threshold...
INDArray labels = Nd4j.create(new double[][]{
{0,1},
{0,1},
{1,0},
{1,0},
{1,0}});
INDArray prediction = Nd4j.create(new double[][]{
{0.199, 0.801},
{0.499, 0.501},
{0.399, 0.601},
{0.799, 0.201},
{0.899, 0.101}});
Map<Double,Double> expTPR = new HashMap<>();
double totalPositives = 2.0;
expTPR.put(0.0, 2.0/totalPositives); //All predicted class 1 -> 2 true positives / 2 total positives
expTPR.put(0.1, 2.0/totalPositives);
expTPR.put(0.2, 2.0/totalPositives);
expTPR.put(0.3, 2.0/totalPositives);
expTPR.put(0.4, 2.0/totalPositives);
expTPR.put(0.5, 2.0/totalPositives);
expTPR.put(0.6, 1.0/totalPositives); //At threshold of 0.6, only 1 of 2 positives are predicted positive
expTPR.put(0.7, 1.0/totalPositives);
expTPR.put(0.8, 1.0/totalPositives);
expTPR.put(0.9, 0.0/totalPositives); //At threshold of 0.9, 0 of 2 positives are predicted positive
expTPR.put(1.0, 0.0/totalPositives);
Map<Double,Double> expFPR = new HashMap<>();
double totalNegatives = 3.0;
expFPR.put(0.0, 3.0/totalNegatives); //All predicted class 1 -> 3 false positives / 3 total negatives
expFPR.put(0.1, 3.0/totalNegatives);
expFPR.put(0.2, 2.0/totalNegatives); //At threshold of 0.2: 1 true negative, 2 false positives
expFPR.put(0.3, 1.0/totalNegatives); //At threshold of 0.3: 2 true negative, 1 false positive
expFPR.put(0.4, 1.0/totalNegatives);
expFPR.put(0.5, 1.0/totalNegatives);
expFPR.put(0.6, 1.0/totalNegatives);
expFPR.put(0.7, 0.0/totalNegatives); //At threshold of 0.7: 3 true negatives, 0 false positives
expFPR.put(0.8, 0.0/totalNegatives);
expFPR.put(0.9, 0.0/totalNegatives);
expFPR.put(1.0, 0.0/totalNegatives);
ROC roc = new ROC(10);
roc.eval(labels, prediction);
List<ROC.ROCValue> list = roc.getResults();
double[][] asArray = roc.getResultsAsArray();
assertEquals(2, asArray.length);
assertEquals(11, asArray[0].length);
assertEquals(11, asArray[1].length);
assertEquals(11,list.size()); //0 + 10 steps
for( int i=0; i<11; i++ ){
ROC.ROCValue v = list.get(i);
double expThreshold = i / 10.0;
assertEquals(expThreshold, v.getThreshold(), 1e-5);
double efpr = expFPR.get(expThreshold);
double afpr = v.getFalsePositiveRate();
assertEquals(efpr, afpr, 1e-5);
double etpr = expTPR.get(expThreshold);
double atpr = v.getTruePositiveRate();
assertEquals(etpr, atpr, 1e-5);
assertEquals(v.getFalsePositiveRate(), asArray[0][i], 1e-6);
assertEquals(v.getTruePositiveRate(), asArray[1][i], 1e-6);
// System.out.println(v.getFalsePositiveRate() + "\t" + v.getTruePositiveRate());
}
//AUC: expected values are based on plotting the ROC curve and manually calculating the area
double expAUC = 0.5 * 1.0/3.0 + (1-1/3.0)*1.0;
double actAUC = roc.calculateAUC();
assertEquals(expAUC, actAUC, 1e-6);
}
@Test
public void testRocTimeSeriesNoMasking(){
//Same as first test...
//2 outputs here - probability distribution over classes (softmax)
INDArray predictions2d = Nd4j.create(new double[][]{
{1.0, 0.001}, //add 0.001 to avoid numerical/rounding issues (float vs. double, etc)
{0.899, 0.101},
{0.799, 0.201},
{0.699, 0.301},
{0.599, 0.401},
{0.499, 0.501},
{0.399, 0.601},
{0.299, 0.701},
{0.199, 0.801},
{0.099, 0.901}});
INDArray actual2d = Nd4j.create(new double[][]{
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{0, 1},
{0, 1},
{0, 1},
{0, 1},
{0, 1}});
INDArray predictions3d = Nd4j.create(2,2,5);
predictions3d.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.all())
.assign(predictions2d.get(NDArrayIndex.interval(0,5), NDArrayIndex.all()));
predictions3d.get(NDArrayIndex.point(1), NDArrayIndex.all(), NDArrayIndex.all())
.assign(predictions2d.get(NDArrayIndex.interval(5,10), NDArrayIndex.all()));
INDArray labels3d = Nd4j.create(2,2,5);
labels3d.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.all())
.assign(actual2d.get(NDArrayIndex.interval(0,5), NDArrayIndex.all()));
labels3d.get(NDArrayIndex.point(1), NDArrayIndex.all(), NDArrayIndex.all())
.assign(actual2d.get(NDArrayIndex.interval(5,10), NDArrayIndex.all()));
ROC rocExp = new ROC(10);
rocExp.eval(actual2d, predictions2d);
ROC rocAct = new ROC(10);
rocAct.evalTimeSeries(labels3d, predictions3d);
assertEquals(rocExp.calculateAUC(), rocAct.calculateAUC(), 1e-6);
List<ROC.ROCValue> expValues = rocExp.getResults();
List<ROC.ROCValue> actValues = rocAct.getResults();
assertEquals(expValues, actValues);
}
@Test
public void testRocTimeSeriesMasking(){
//2 outputs here - probability distribution over classes (softmax)
INDArray predictions2d = Nd4j.create(new double[][]{
{1.0, 0.001}, //add 0.001 to avoid numerical/rounding issues (float vs. double, etc)
{0.899, 0.101},
{0.799, 0.201},
{0.699, 0.301},
{0.599, 0.401},
{0.499, 0.501},
{0.399, 0.601},
{0.299, 0.701},
{0.199, 0.801},
{0.099, 0.901}});
INDArray actual2d = Nd4j.create(new double[][]{
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{1, 0},
{0, 1},
{0, 1},
{0, 1},
{0, 1},
{0, 1}});
//Create time series data... first time series: length 4. Second time series: length 6
INDArray predictions3d = Nd4j.create(2,2,6);
INDArray tad = predictions3d.tensorAlongDimension(0, 1,2).transpose();
tad.get(NDArrayIndex.interval(0,4), NDArrayIndex.all())
.assign(predictions2d.get(NDArrayIndex.interval(0,4), NDArrayIndex.all()));
tad = predictions3d.tensorAlongDimension(1, 1,2).transpose();
tad.assign(predictions2d.get(NDArrayIndex.interval(4,10), NDArrayIndex.all()));
INDArray labels3d = Nd4j.create(2,2,6);
tad = labels3d.tensorAlongDimension(0, 1,2).transpose();
tad.get(NDArrayIndex.interval(0,4), NDArrayIndex.all())
.assign(actual2d.get(NDArrayIndex.interval(0,4), NDArrayIndex.all()));
tad = labels3d.tensorAlongDimension(1, 1,2).transpose();
tad.assign(actual2d.get(NDArrayIndex.interval(4,10), NDArrayIndex.all()));
INDArray mask = Nd4j.zeros(2,6);
mask.get(NDArrayIndex.point(0),NDArrayIndex.interval(0,4)).assign(1);
mask.get(NDArrayIndex.point(1),NDArrayIndex.all()).assign(1);
ROC rocExp = new ROC(10);
rocExp.eval(actual2d, predictions2d);
ROC rocAct = new ROC(10);
rocAct.evalTimeSeries(labels3d, predictions3d, mask);
assertEquals(rocExp.calculateAUC(), rocAct.calculateAUC(), 1e-6);
List<ROC.ROCValue> expValues = rocExp.getResults();
List<ROC.ROCValue> actValues = rocAct.getResults();
assertEquals(expValues, actValues);
}
@Test
public void testCompareRocAndRocMultiClass(){
Nd4j.getRandom().setSeed(12345);
//For 2 class case: ROC and Multi-class ROC should be the same...
int nExamples = 200;
INDArray predictions = Nd4j.rand(nExamples, 2);
INDArray tempSum = predictions.sum(1);
predictions.diviColumnVector(tempSum);
INDArray labels = Nd4j.create(nExamples, 2);
Random r = new Random(12345);
for( int i=0; i<nExamples; i++ ) {
labels.putScalar(i, r.nextInt(2), 1.0);
}
int numSteps = 30;
ROC roc = new ROC(numSteps);
roc.eval(labels, predictions);
ROCMultiClass rocMultiClass = new ROCMultiClass(numSteps);
rocMultiClass.eval(labels, predictions);
double auc = roc.calculateAUC();
double auc1 = rocMultiClass.calculateAUC(1);
assertEquals(auc, auc1, 1e-6);
double[][] rocPoints = roc.getResultsAsArray();
double[][] rocPoints0 = rocMultiClass.getResultsAsArray(1);
assertEquals(rocPoints.length, rocPoints0.length);
for( int i=0; i<rocPoints[0].length; i++ ){
assertEquals(rocPoints[0][i], rocPoints0[0][i], 1e-6);
assertEquals(rocPoints[1][i], rocPoints0[1][i], 1e-6);
}
}
}
|
package org.apache.velocity.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.HttpServletRequestWrap;
import org.apache.velocity.app.HttpServletResponseWrap;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
/**
* Base class which simplifies the use of Velocity with Servlets.
* Extend this class, implement the <code>handleRequest()</code> method,
* and add your data to the context. Then call
* <code>getTemplate("myTemplate.wm")</code>.
*
* This class puts some things into the context object that you should
* be aware of:
* <pre>
* "req" - The HttpServletRequest object
* "res" - The HttpServletResponse object
* </pre>
*
* There are other methods you can override to access, alter or control
* any part of the request processing chain. Please see the javadocs for
* more information on :
* <ul>
* <li> loadConfiguration() : for setting up the Velocity runtime
* <li> createContext() : for creating and loading the Context
* <li> setContentType() : for changing the content type on a request
* by request basis
* <li> handleRequest() : you <b>must</b> implement this
* <li> mergeTemplate() : the template rendering process
* <li> requestCleanup() : post rendering resource or other cleanup
* <li> error() : error handling
* </ul>
* <br>
* If you put a contentType object into the context within either your
* serlvet or within your template, then that will be used to override
* the default content type specified in the properties file.
*
* "contentType" - The value for the Content-Type: header
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="kjohnson@transparent.com">Kent Johnson</a>
* $Id: VelocityServlet.java,v 1.40 2001/08/07 22:26:46 geirm Exp $
*/
public abstract class VelocityServlet extends HttpServlet
{
/**
* The HTTP request object context key.
*/
public static final String REQUEST = "req";
/**
* The HTTP response object context key.
*/
public static final String RESPONSE = "res";
/**
* The HTTP content type context key.
*/
public static final String CONTENT_TYPE = "default.contentType";
/**
* The default content type for the response
*/
public static final String DEFAULT_CONTENT_TYPE = "text/html";
/**
* Encoding for the output stream
*/
public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
/**
* The encoding to use when generating outputing.
*/
private static String encoding = null;
/**
* The default content type.
*/
private static String defaultContentType;
/**
* This is the string that is looked for when getInitParameter is
* called.
*/
protected static final String INIT_PROPS_KEY = "properties";
/**
* Cache of writers
*/
private static SimplePool writerPool = new SimplePool(40);
/**
* Performs initialization of this servlet. Called by the servlet
* container on loading.
*
* @param config The servlet configuration to apply.
*
* @exception ServletException
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
try
{
/*
* call the overridable method to allow the
* derived classes a shot at altering the configuration
* before initializing Runtime
*/
Properties props = loadConfiguration( config );
Velocity.init( props );
defaultContentType = RuntimeSingleton.getString( CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
encoding = RuntimeSingleton.getString( RuntimeSingleton.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING);
}
catch( Exception e )
{
throw new ServletException("Error configuring the loader: " + e);
}
}
/**
* Loads the configuration information and returns that
* information as a Properties, which will be used to
* initialize the Velocity runtime.
* <br><br>
* Currently, this method gets the initialization parameter
* VelocityServlet.INIT_PROPS_KEY, which should be a file containing
* the configuration information.
* <br><br>
* To configure your Servlet Spec 2.2 compliant servlet runner to pass this
* to you, put the following in your WEB-INF/web.xml file
* <br>
* <pre>
* <servlet >
* <servlet-name> YourServlet </servlet-name>
* <servlet-class> your.package.YourServlet </servlet-class>
* <init-param>
* <param-name> properties </param-name>
* <param-value> velocity.properties </param-value>
* </init-param>
* </servlet>
* </pre>
*
* Derived classes may do the same, or take advantage of this code to do the loading for them via :
* <pre>
* Properties p = super.loadConfiguration( config );
* </pre>
* and then add or modify the configuration values from the file.
* <br>
*
* @param config ServletConfig passed to the servlets init() function
* Can be used to access the real path via ServletContext (hint)
* @return java.util.Properties loaded with configuration values to be used
* to initialize the Velocity runtime.
* @throws FileNotFoundException if a specified file is not found.
* @throws IOException I/O problem accessing the specified file, if specified.
*/
protected Properties loadConfiguration(ServletConfig config )
throws IOException, FileNotFoundException
{
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
/*
* This will attempt to find the location of the properties
* file from the relative path to the WAR archive (ie:
* docroot). Since JServ returns null for getRealPath()
* because it was never implemented correctly, then we know we
* will not have an issue with using it this way. I don't know
* if this will break other servlet engines, but it probably
* shouldn't since WAR files are the future anyways.
*/
Properties p = new Properties();
if ( propsFile != null )
{
String realPath = getServletContext().getRealPath(propsFile);
if ( realPath != null )
{
propsFile = realPath;
}
p.load( new FileInputStream(propsFile) );
}
return p;
}
/**
* Handles GET - calls doRequest()
*/
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handle a POST request - calls doRequest()
*/
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles all requests
*
* @param request HttpServletRequest object containing client request
* @param response HttpServletResponse object for the response
*/
protected void doRequest(HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
try
{
/*
* first, get a context
*/
Context context = createContext( request, response );
/*
* set the content type
*/
setContentType( request, response );
/*
* let someone handle the request
*/
Template template = handleRequest( request, response, context );
/*
* bail if we can't find the template
*/
if ( template == null )
{
return;
}
/*
* now merge it
*/
mergeTemplate( template, context, response );
/*
* call cleanup routine to let a derived class do some cleanup
*/
requestCleanup( request, response, context );
}
catch (Exception e)
{
/*
* call the error handler to let the derived class
* do something useful with this failure.
*/
error( request, response, e);
}
}
protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context )
{
return;
}
protected void mergeTemplate( Template template, Context context, HttpServletResponse response )
throws ResourceNotFoundException, ParseErrorException,
MethodInvocationException, IOException, UnsupportedEncodingException, Exception
{
ServletOutputStream output = response.getOutputStream();
VelocityWriter vw = null;
try
{
vw = (VelocityWriter) writerPool.get();
if (vw == null)
{
vw = new VelocityWriter( new OutputStreamWriter(output, encoding), 4*1024, true);
}
else
{
vw.recycle(new OutputStreamWriter(output, encoding));
}
template.merge( context, vw);
}
finally
{
try
{
if (vw != null)
{
/*
* flush and put back into the pool
* don't close to allow us to play
* nicely with others.
*/
vw.flush();
writerPool.put(vw);
}
}
catch (Exception e)
{
// do nothing
}
}
}
/**
* Sets the content type of the response. This is available to be overriden
* by a derived class.
*
* The default implementation is :
*
* response.setContentType( defaultContentType );
*
* where defaultContentType is set to the value of the default.contentType
* property, or "text/html" if that is not set.
*
* @param request servlet request from client
* @param response servlet reponse to client
*/
protected void setContentType( HttpServletRequest request, HttpServletResponse response )
{
response.setContentType( defaultContentType );
}
/**
* Returns a context suitable to pass to the handleRequest() method
* <br><br>
* Default implementation will create a VelocityContext object,
* put the HttpServletRequest and HttpServletResponse
* into the context accessable via the keys VelocityServlet.REQUEST and
* VelocityServlet.RESPONSE, respectively.
*
* @param request servlet request from client
* @param response servlet reponse to client
*
* @return context
*/
protected Context createContext(HttpServletRequest request, HttpServletResponse response )
{
/*
* create a new context
*/
VelocityContext context = new VelocityContext();
/*
* put the request/response objects into the context
* wrap the HttpServletRequest to solve the introspection
* problems
*/
context.put( REQUEST, new HttpServletRequestWrap( request ) );
context.put( RESPONSE, new HttpServletResponseWrap( response ) );
return context;
}
/**
* Retrieves the requested template.
*
* @param name The file name of the template to retrieve relative to the
* template root.
* @return The requested template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*/
public Template getTemplate( String name )
throws ResourceNotFoundException, ParseErrorException, Exception
{
return RuntimeSingleton.getTemplate(name);
}
/**
* Retrieves the requested template with the specified
* character encoding.
*
* @param name The file name of the template to retrieve relative to the
* template root.
* @param encoding the character encoding of the template
*
* @return The requested template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*
* @since Velocity v1.1
*/
public Template getTemplate( String name, String encoding )
throws ResourceNotFoundException, ParseErrorException, Exception
{
return RuntimeSingleton.getTemplate( name, encoding );
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
* <br><br>
* In the event of a problem, you may handle the request directly
* and return <code>null</code> or throw a more meaningful exception
* for the error handler to catch.
*
* @param request servlet request from client
* @param response servlet reponse
* @param ctx The context to add your data to.
* @return The template to merge with your context or null, indicating
* that you handled the processing.
*
* @since Velocity v1.1
*/
protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx )
throws Exception
{
/*
* invoke handleRequest
*/
Template t = handleRequest( ctx );
/*
* if it returns null, this is the 'old' deprecated
* way, and we want to mimic the behavior for a little
* while anyway
*/
if (t == null)
{
throw new Exception ("handleRequest(Context) returned null - no template selected!" );
}
return t;
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
* <br><br>
* In the event of a problem, you may simple return <code>null</code>
* or throw a more meaningful exception.
*
* @deprecated Use
* {@link #handleRequest( HttpServletRequest request,
* HttpServletResponse response, Context ctx )}
*
* @param ctx The context to add your data to.
* @return The template to merge with your context.
*/
protected Template handleRequest( Context ctx )
throws Exception
{
throw new Exception ("You must override VelocityServlet.handleRequest( Context) "
+ " or VelocityServlet.handleRequest( HttpServletRequest, "
+ " HttpServletResponse, Context)" );
}
/**
* Invoked when there is an error thrown in any part of doRequest() processing.
* <br><br>
* Default will send a simple HTML response indicating there was a problem.
*
* @param request original HttpServletRequest from servlet container.
* @param response HttpServletResponse object from servlet container.
* @param cause Exception that was thrown by some other part of process.
*/
protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause )
throws ServletException, IOException
{
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<body bgcolor=\"#ffffff\">");
html.append("<h2>VelocityServlet : Error processing the template</h2>");
html.append( cause );
html.append("<br>");
StringWriter sw = new StringWriter();
cause.printStackTrace( new PrintWriter( sw ) );
html.append( sw.toString() );
html.append("</body>");
html.append("</html>");
response.getOutputStream().print( html.toString() );
}
}
|
package org.apache.velocity.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.HttpServletRequestWrap;
import org.apache.velocity.app.HttpServletResponseWrap;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
/**
* Base class which simplifies the use of Velocity with Servlets.
* Extend this class, implement the <code>handleRequest()</code> method,
* and add your data to the context. Then call
* <code>getTemplate("myTemplate.wm")</code>.
*
* This class puts some things into the context object that you should
* be aware of:
* <pre>
* "req" - The HttpServletRequest object
* "res" - The HttpServletResponse object
* </pre>
*
* There are other methods you can override to access, alter or control
* any part of the request processing chain. Please see the javadocs for
* more information on :
* <ul>
* <li> loadConfiguration() : for setting up the Velocity runtime
* <li> createContext() : for creating and loading the Context
* <li> setContentType() : for changing the content type on a request
* by request basis
* <li> handleRequest() : you <b>must</b> implement this
* <li> mergeTemplate() : the template rendering process
* <li> requestCleanup() : post rendering resource or other cleanup
* <li> error() : error handling
* </ul>
* <br>
* If you put a contentType object into the context within either your
* serlvet or within your template, then that will be used to override
* the default content type specified in the properties file.
*
* "contentType" - The value for the Content-Type: header
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* $Id: VelocityServlet.java,v 1.29 2001/04/04 10:42:39 geirm Exp $
*/
public abstract class VelocityServlet extends HttpServlet
{
/**
* The HTTP request object context key.
*/
public static final String REQUEST = "req";
/**
* The HTTP response object context key.
*/
public static final String RESPONSE = "res";
/**
* The HTTP content type context key.
*/
public static final String CONTENT_TYPE = "default.contentType";
/**
* The default content type for the response
*/
public static final String DEFAULT_CONTENT_TYPE = "text/html";
/**
* The encoding to use when generating outputing.
*/
private static String encoding = null;
/**
* The default content type.
*/
private static String defaultContentType;
/**
* This is the string that is looked for when getInitParameter is
* called.
*/
private static final String INIT_PROPS_KEY = "properties";
/**
* Cache of writers
*/
private static SimplePool writerPool = new SimplePool(40);
/**
* Performs initialization of this servlet. Called by the servlet
* container on loading.
*
* @param config The servlet configuration to apply.
*
* @exception ServletException
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
try
{
/*
* call the overridable method to allow the
* derived classes a shot at altering the configuration
* before initializing Runtime
*/
Properties props = loadConfiguration( config );
Velocity.init( props );
defaultContentType = Runtime.getString( CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
encoding = Runtime.getString(Runtime.TEMPLATE_ENCODING, "8859_1");
}
catch( Exception e )
{
throw new ServletException("Error configuring the loader: " + e);
}
}
/**
* Loads the configuration information and returns that
* information as a Properties, which will be used to
* initialize the Velocity runtime.
* <br><br>
* Currently, this method gets the initialization parameter
* VelocityServlet.INIT_PROPS_KEY, which should be a file containing
* the configuration information.
* <br><br>
* To configure your Servlet Spec 2.2 compliant servlet runner to pass this
* to you, put the following in your WEB-INF/web.xml file
* <br>
* <pre>
* <servlet >
* <servlet-name> YourServlet </servlet-name>
* <servlet-class> your.package.YourServlet </servlet-class>
* <init-param>
* <param-name> properties </param-name>
* <param-value> velocity.properties </param-value>
* </init-param>
* </servlet>
* </pre>
*
* Derived classes may do the same, or take advantage of this code to do the loading for them via :
* <pre>
* Properties p = super.loadConfiguration( config );
* </pre>
* and then add or modify the configuration values from the file.
* <br>
*
* @param config ServletConfig passed to the servlets init() function
* Can be used to access the real path via ServletContext (hint)
* @return java.util.Properties loaded with configuration values to be used
* to initialize the Velocity runtime.
* @throws FileNotFoundException if a specified file is not found.
* @throws IOException I/O problem accessing the specified file, if specified.
*/
protected Properties loadConfiguration(ServletConfig config )
throws IOException, FileNotFoundException
{
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
/*
* This will attempt to find the location of the properties
* file from the relative path to the WAR archive (ie:
* docroot). Since JServ returns null for getRealPath()
* because it was never implemented correctly, then we know we
* will not have an issue with using it this way. I don't know
* if this will break other servlet engines, but it probably
* shouldn't since WAR files are the future anyways.
*/
Properties p = new Properties();
if ( propsFile != null )
{
String realPath = getServletContext().getRealPath(propsFile);
if ( realPath != null )
{
propsFile = realPath;
}
p.load( new FileInputStream(propsFile) );
}
return p;
}
/**
* Handles GET - calls doRequest()
*/
public final void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handle a POST request - calls doRequest()
*/
public final void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles all requests
*
* @param request HttpServletRequest object containing client request
* @param response HttpServletResponse object for the response
*/
private void doRequest(HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
try
{
/*
* first, get a context
*/
Context context = createContext( request, response );
/*
* set the content type
*/
setContentType( request, response );
/*
* let someone handle the request
*/
Template template = handleRequest(context);
/*
* bail if we can't find the template
*/
if ( template == null )
{
throw new Exception ("Cannot find the template!" );
}
/*
* now merge it
*/
mergeTemplate( template, context, response );
/*
* call cleanup routine to let a derived class do some cleanup
*/
requestCleanup( request, response, context );
}
catch (Exception e)
{
/*
* call the error handler to let the derived class
* do something useful with this failure.
*/
error( request, response, e);
}
}
protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context )
{
return;
}
protected void mergeTemplate( Template template, Context context, HttpServletResponse response )
throws ResourceNotFoundException, ParseErrorException,
MethodInvocationException, IOException, UnsupportedEncodingException, Exception
{
ServletOutputStream output = response.getOutputStream();
VelocityWriter vw = null;
try
{
vw = (VelocityWriter) writerPool.get();
if (vw == null)
{
vw = new VelocityWriter( new OutputStreamWriter(output, encoding), 4*1024, true);
}
else
{
vw.recycle(new OutputStreamWriter(output, encoding));
}
template.merge( context, vw);
}
finally
{
try
{
if (vw != null)
{
vw.flush();
writerPool.put(vw);
output.close();
}
}
catch (Exception e)
{
// do nothing
}
}
}
/**
* Sets the content type of the response. This is available to be overriden
* by a derived class.
*
* The default implementation is :
*
* response.setContentType( defaultContentType );
*
* where defaultContentType is set to the value of the default.contentType
* property, or "text/html" if that is not set.
*
* @param request servlet request from client
* @param response servlet reponse to client
*/
protected void setContentType( HttpServletRequest request, HttpServletResponse response )
{
response.setContentType( defaultContentType );
}
/**
* Returns a context suitable to pass to the handleRequest() method
* <br><br>
* Default implementation will create a VelocityContext object,
* put the HttpServletRequest and HttpServletResponse
* into the context accessable via the keys VelocityServlet.REQUEST and
* VelocityServlet.RESPONSE, respectively.
*
* @param request servlet request from client
* @param response servlet reponse to client
*
* @return context
*/
protected Context createContext(HttpServletRequest request, HttpServletResponse response )
{
/*
* create a new context
*/
VelocityContext context = new VelocityContext();
/*
* put the request/response objects into the context
* wrap the HttpServletRequest to solve the introspection
* problems
*/
context.put( REQUEST, new HttpServletRequestWrap( request ) );
context.put( RESPONSE, new HttpServletResponseWrap( response ) );
return context;
}
/**
* Retrieves the requested template.
*
* @param name The file name of the template to retrieve relative to the
* template root.
* @return The requested template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*/
public Template getTemplate( String name )
throws ResourceNotFoundException, ParseErrorException, Exception
{
return Runtime.getTemplate(name);
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
* <br><br>
* In the event of a problem, you may simple return <code>null</code>
* or throw a more meaningful exception.
*
* @param ctx The context to add your data to.
* @return The template to merge with your context.
*/
protected abstract Template handleRequest( Context ctx ) throws Exception;
/**
* Invoked when there is an error thrown in any part of doRequest() processing.
* <br><br>
* Default will send a simple HTML response indicating there was a problem.
*
* @param request original HttpServletRequest from servlet container.
* @param response HttpServletResponse object from servlet container.
* @param cause Exception that was thrown by some other part of process.
*/
protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause )
throws ServletException, IOException
{
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<body bgcolor=\"#ffffff\">");
html.append("<h2>VelocityServlet : Error processing the template</h2>");
html.append( cause );
html.append("<br>");
StringWriter sw = new StringWriter();
cause.printStackTrace( new PrintWriter( sw ) );
html.append( sw.toString() );
html.append("</body>");
html.append("</html>");
response.getOutputStream().print( html.toString() );
}
}
|
package org.distbc.planner;
import com.google.inject.Inject;
import org.distbc.data.structures.Catalog;
import org.distbc.data.structures.Table;
import org.distbc.data.structures.TopLevelDataStructure;
import org.distbc.parser.ParsingResult;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* While every sensible query plan can be imagined as a tree this query planner thinks of as a series of independent
* query plans (swim lanes) that merge together at some point.
* Therefore, it starts looking at every table independently and tries to figure out how it can mutate each table.
* At some point two of these swim lanes merge and become one.
*
* Limitations:
* - column names need to be unique
* - only lower case keywords
*/
class QueryPlannerImpl implements QueryPlanner {
private final Catalog catalog;
@Inject
QueryPlannerImpl(Catalog catalog) {
this.catalog = catalog;
}
@Override
public QueryPlan generateQueryPlan(ParsingResult parsingResult) {
List<Table> tables = orderTablesInExecutionOrder(parsingResult);
Map<String, QueryPlanSwimLane> tableNameToSwimLand = new HashMap<>(tables.size());
QueryPlanImpl qp = new QueryPlanImpl();
tables.forEach(table -> {
QueryPlanSwimLane sl = new QueryPlanSwimLane(table);
// figure out projections first
sl.addOperation(generateProjectionForTable(table, parsingResult));
// then do selections
if (parsingResult.getWhereClauses().size() > 0) {
sl.addOperation(generateSelectionForTable(table, parsingResult));
}
qp.addSwimLane(sl);
tableNameToSwimLand.put(table.getName(), sl);
});
// each of these swim lanes can be kicked off already
// but we don't do that...
// then determine how tables feed into joins
parsingResult.getJoinClauses().forEach(joinClause -> {
// TODO: get both tables out of the joinClause
// potentially parse the string again ... not crazy cool but gets us there :)
// create new swim lane from child swim lanes
// let's see how this goes for us :)
qp.addSwimLane(generateJoinForSwimLanes(tableNameToSwimLand.get(""), tableNameToSwimLand.get(""), parsingResult));
});
return qp;
}
private List<Table> orderTablesInExecutionOrder(ParsingResult parsingResult) {
return parsingResult.getTableNames().stream()
.map(tableName -> catalog.get(tableName, Table.class))
.sorted(Comparator.comparing(TopLevelDataStructure::getName))
.collect(Collectors.toList());
}
private Operation generateProjectionForTable(Table table, ParsingResult parsingResult) {
return new Projection(parsingResult.getProjectionColumnNames(), table.getColumnNames());
}
private Operation generateSelectionForTable(Table table, ParsingResult parsingResult) {
List<String> columnsOnTable = table.getColumnNames();
// List<String> allWhereClauses = parsingResult.getWhereClauses();
List<ParsingResult.BinaryOperation> bos = parsingResult.getBinaryOperations();
bos = bos.stream()
.filter(bo -> columnsOnTable.indexOf(bo.operand1) >= 0)
.collect(Collectors.toList());
// get all where clauses that are interesting for the table in question
// convert the tree into a series of strings
// selections with literals only
return new Selection(bos);
}
private QueryPlanSwimLane generateJoinForSwimLanes(QueryPlanSwimLane sl1, QueryPlanSwimLane sl2, ParsingResult parsingResult) {
return null;
}
}
|
package etomica.virial.simulations;
import java.awt.Color;
import etomica.api.IAtomList;
import etomica.data.AccumulatorRatioAverage;
import etomica.data.IData;
import etomica.data.types.DataGroup;
import etomica.graphics.ColorSchemeByType;
import etomica.graphics.SimulationGraphic;
import etomica.potential.P2EffectiveFeynmanHibbs;
import etomica.potential.P2HePCKLJS;
import etomica.space.Space;
import etomica.space3d.Space3D;
import etomica.species.SpeciesSpheresMono;
import etomica.units.Kelvin;
import etomica.util.Constants;
import etomica.util.ParameterBase;
import etomica.virial.ClusterAbstract;
import etomica.virial.ClusterSum;
import etomica.virial.MayerD2FDT2Spherical;
import etomica.virial.MayerDFDTSpherical;
import etomica.virial.MayerESpherical;
import etomica.virial.MayerGeneralSpherical;
import etomica.virial.MayerHardSphere;
import etomica.virial.SpeciesFactorySpheres;
import etomica.virial.cluster.Standard;
import etomica.virial.cluster.VirialDiagrams;
/**
* Computes first or second temperatures (see firstDerivative variable) of additive virial coefficients using the
* ab initio pair potential for helium from Przybytek et al. (2010) (Phys. Rev. Lett. 104, 183003).
*
* Use the boolean QFH to select whether the quadratic Feynman-Hibbs modification to the potential is used.
*
* @author kate
*
*/
public class VirialHePCKLJSTempDeriv {
public static void main(String[] args) {
VirialParam params = new VirialParam();
double temperatureK; final int nPoints; double sigmaHSRef;
long steps; boolean firstDerivative; boolean QFH;
if (args.length == 0) {
nPoints = params.nPoints;
temperatureK = params.temperature;
steps = params.numSteps;
sigmaHSRef = params.sigmaHSRef;
firstDerivative = params.firstDerivative;
QFH = params.QFH;
// number of overlap sampling steps
// for each overlap sampling step, the simulation boxes are allotted
// 1000 attempts for MC moves, total
} else if (args.length == 6) {
//ReadParameters paramReader = new ReadParameters(args[0], params);
//paramReader.readParameters();
nPoints = Integer.parseInt(args[0]);
temperatureK = Double.parseDouble(args[1]);
steps = Integer.parseInt(args[2]);
sigmaHSRef = Double.parseDouble(args[3]);
firstDerivative = Boolean.parseBoolean(args[4]);
QFH = Boolean.parseBoolean(args[5]);
params.writeRefPref = true;
} else {
throw new IllegalArgumentException("Incorrect number of arguments passed.");
}
int numSubSteps = 1000;
final double[] HSB = new double[7];
HSB[2] = Standard.B2HS(sigmaHSRef);
HSB[3] = Standard.B3HS(sigmaHSRef);
HSB[4] = Standard.B4HS(sigmaHSRef);
HSB[5] = Standard.B5HS(sigmaHSRef);
HSB[6] = Standard.B6HS(sigmaHSRef);
System.out.println("sigmaHSRef: "+sigmaHSRef);
System.out.println("B"+nPoints+"HS: "+HSB[nPoints]);
if (firstDerivative) {
System.out.println("Helium overlap sampling dB"+nPoints+"Add/dT at T="+temperatureK+ " K");
} else {
System.out.println("Helium overlap sampling d2B"+nPoints+"Add/dT2 at T="+temperatureK+ " K");
}
if (QFH) {
System.out.println("Quadratic Feymann-Hibbs version of potential employed.");
}
double temperature = Kelvin.UNIT.toSim(temperatureK);
//Next line not needed because energy in Kelvin
//temperature = Kelvin.UNIT.toSim(temperature);
System.out.println(steps+" steps ("+steps/1000+" blocks of 1000)");
steps /= 1000;
Space space = Space3D.getInstance();
MayerGeneralSpherical fTarget; MayerESpherical eTarget;
MayerDFDTSpherical dfdTTarget; MayerD2FDT2Spherical df2dT2Target;
if (QFH) {
P2HePCKLJS p20 = new P2HePCKLJS(space);
P2EffectiveFeynmanHibbs p2 = new P2EffectiveFeynmanHibbs(Space3D.getInstance(),p20);
p2.setTemperature(temperature);
p2.setMass(4.002602);
fTarget = new MayerGeneralSpherical(p2);
eTarget = new MayerESpherical(p2);
dfdTTarget = new MayerDFDTSpherical(p2);
df2dT2Target = new MayerD2FDT2Spherical(p2);
} else {
P2HePCKLJS p2 = new P2HePCKLJS(space);
fTarget = new MayerGeneralSpherical(p2);
eTarget = new MayerESpherical(p2);
dfdTTarget = new MayerDFDTSpherical(p2);
df2dT2Target = new MayerD2FDT2Spherical(p2);
}
VirialDiagrams targetCluster1 = new VirialDiagrams(nPoints, false, false);
ClusterSum targetCluster;
if (firstDerivative) {
targetCluster = targetCluster1.makeVirialClusterTempDeriv(fTarget, eTarget, dfdTTarget);
} else {
targetCluster = targetCluster1.makeVirialClusterSecondTemperatureDerivative(fTarget, eTarget, dfdTTarget, df2dT2Target);
}
MayerHardSphere fRef = new MayerHardSphere(sigmaHSRef);
ClusterAbstract refCluster = Standard.virialCluster(nPoints, fRef, nPoints>3, null, false);
targetCluster.setTemperature(temperature);
refCluster.setTemperature(temperature);
final SimulationVirialOverlap sim = new SimulationVirialOverlap(space,new SpeciesFactorySpheres(),
temperature,refCluster,targetCluster, false);
IAtomList atoms = sim.box[1].getLeafList();
if (QFH) {
} else {
for (int i=1;i<atoms.getAtomCount();i++) {
atoms.getAtom(i).getPosition().setX(0, i*10);
}
}
if (false) {
sim.box[0].getBoundary().setBoxSize(space.makeVector(new double[]{10,10,10}));
sim.box[1].getBoundary().setBoxSize(space.makeVector(new double[]{10,10,10}));
SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, space, sim.getController());
simGraphic.getDisplayBox(sim.box[0]).setShowBoundary(false);
simGraphic.getDisplayBox(sim.box[1]).setShowBoundary(false);
SpeciesSpheresMono species = (SpeciesSpheresMono)sim.getSpecies(0);
((ColorSchemeByType)simGraphic.getDisplayBox(sim.box[0]).getColorScheme()).setColor(species.getAtomType(0), Color.WHITE);
((ColorSchemeByType)simGraphic.getDisplayBox(sim.box[1]).getColorScheme()).setColor(species.getAtomType(0), Color.WHITE);
simGraphic.makeAndDisplayFrame();
sim.integratorOS.setNumSubSteps(numSubSteps);
sim.setAccumulatorBlockSize(1000);
// if running interactively, set filename to null so that it doens't read
// (or write) to a refpref file
sim.getController().removeAction(sim.ai);
// sim.getController().addAction(new IAction() {
// public void actionPerformed() {
// sim.initRefPref(null, 0);
// sim.equilibrate(null,0);
// sim.ai.setMaxSteps(Long.MAX_VALUE);
sim.getController().addAction(sim.ai);
if ((Double.isNaN(sim.refPref) || Double.isInfinite(sim.refPref) || sim.refPref == 0)) {
throw new RuntimeException("Oops");
}
return;
}
// if running interactively, don't use the file
String refFileName = args.length > 0 ? "refpref"+nPoints+"_"+params.temperature : null;
// this will either read the refpref in from a file or run a short simulation to find it
sim.initRefPref(refFileName, steps/40);
// run another short simulation to find MC move step sizes and maybe narrow in more on the best ref pref
// if it does continue looking for a pref, it will write the value to the file
sim.equilibrate(refFileName, steps/20);
if (sim.refPref == 0 || Double.isNaN(sim.refPref) || Double.isInfinite(sim.refPref)) {
throw new RuntimeException("oops");
}
sim.setAccumulatorBlockSize((int)steps);
System.out.println("equilibration finished");
System.out.println("MC Move step sizes (ref) "+sim.mcMoveTranslate[0].getStepSize());
System.out.println("MC Move step sizes (target) "+sim.mcMoveTranslate[1].getStepSize());
// IAction progressReport = new IAction() {
// public void actionPerformed() {
// System.out.print(sim.integratorOS.getStepCount()+" steps: ");
// double ratio = sim.dsvo.getDataAsScalar();
// double error = sim.dsvo.getError();
// System.out.println("abs average: "+ratio*HSB[nPoints]+", error: "+error*HSB[nPoints]);
// sim.integratorOS.addIntervalAction(progressReport);
// sim.integratorOS.setActionInterval(progressReport, (int)(steps/10));
sim.integratorOS.getMoveManager().setEquilibrating(false);
sim.ai.setMaxSteps(steps);
sim.getController().actionPerformed();
System.out.println("final reference step frequency "+sim.integratorOS.getStepFreq0());
System.out.println("actual reference step frequency "+sim.integratorOS.getActualStepFreq0());
double[] ratioAndError = sim.dsvo.getOverlapAverageAndError();
double ratio = ratioAndError[0];
double error = ratioAndError[1];
System.out.println("ratio average: "+ratio+", error: "+error);
System.out.println("abs average: "+ratio*HSB[nPoints]+", error: "+error*HSB[nPoints]);
IData ratioData = ((DataGroup)sim.accumulators[0].getData()).getData(AccumulatorRatioAverage.StatType.RATIO.index);
IData ratioErrorData = ((DataGroup)sim.accumulators[0].getData()).getData(AccumulatorRatioAverage.StatType.RATIO_ERROR.index);
IData averageData = ((DataGroup)sim.accumulators[0].getData()).getData(AccumulatorRatioAverage.StatType.AVERAGE.index);
IData stdevData = ((DataGroup)sim.accumulators[0].getData()).getData(AccumulatorRatioAverage.StatType.STANDARD_DEVIATION.index);
IData errorData = ((DataGroup)sim.accumulators[0].getData()).getData(AccumulatorRatioAverage.StatType.ERROR.index);
System.out.println("reference ratio average: "+ratioData.getValue(1)+" error: "+ratioErrorData.getValue(1));
System.out.println("reference average: "+averageData.getValue(0)
+" stdev: "+stdevData.getValue(0)
+" error: "+errorData.getValue(0));
System.out.println("reference overlap average: "+averageData.getValue(1)
+" stdev: "+stdevData.getValue(1)
+" error: "+errorData.getValue(1));
ratioData = ((DataGroup)sim.accumulators[1].getData()).getData(AccumulatorRatioAverage.StatType.RATIO.index);
ratioErrorData = ((DataGroup)sim.accumulators[1].getData()).getData(AccumulatorRatioAverage.StatType.RATIO_ERROR.index);
averageData = ((DataGroup)sim.accumulators[1].getData()).getData(AccumulatorRatioAverage.StatType.AVERAGE.index);
stdevData = ((DataGroup)sim.accumulators[1].getData()).getData(AccumulatorRatioAverage.StatType.STANDARD_DEVIATION.index);
errorData = ((DataGroup)sim.accumulators[1].getData()).getData(AccumulatorRatioAverage.StatType.ERROR.index);
System.out.println("target ratio average: "+ratioData.getValue(1)+" error: "+ratioErrorData.getValue(1));
System.out.println("target average: "+averageData.getValue(0)
+" stdev: "+stdevData.getValue(0)
+" error: "+errorData.getValue(0));
System.out.println("target overlap average: "+averageData.getValue(1)
+" stdev: "+stdevData.getValue(1)
+" error: "+errorData.getValue(1));
System.out.println();
System.out.println("cm"+((nPoints-1)*3)+"/mol"+(nPoints-1)+"/K: ");
double convertBeta = temperature/temperatureK;
if (!firstDerivative) {
convertBeta*=convertBeta;
}
System.out.println("abs average: "+ratio*HSB[nPoints]*Math.pow(Constants.AVOGADRO*1e-24,nPoints-1)*convertBeta+", error: "+error*HSB[nPoints]*Math.pow(Constants.AVOGADRO*1e-24,nPoints-1)*convertBeta);
}
/**
* Inner class for parameters
*/
public static class VirialParam extends ParameterBase {
public int nPoints = 4;
public double temperature = 50.0; // Kelvin
public long numSteps = 100000;
public double sigmaHSRef = 3;
public boolean firstDerivative = true;
public boolean QFH = false;
public boolean writeRefPref;
}
}
|
package org.apache.velocity.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
/**
* Base class which simplifies the use of Velocity with Servlets.
* Extend this class, implement the <code>handleRequest()</code> method,
* and add your data to the context. Then call
* <code>getTemplate("myTemplate.wm")</code>.
*
* This class puts some things into the context object that you should
* be aware of:
* <pre>
* "req" - The HttpServletRequest object
* "res" - The HttpServletResponse object
* </pre>
*
* There are other methods you can override to access, alter or control
* any part of the request processing chain. Please see the javadocs for
* more information on :
* <ul>
* <li> loadConfiguration() : for setting up the Velocity runtime
* <li> createContext() : for creating and loading the Context
* <li> setContentType() : for changing the content type on a request
* by request basis
* <li> handleRequest() : you <b>must</b> implement this
* <li> mergeTemplate() : the template rendering process
* <li> requestCleanup() : post rendering resource or other cleanup
* <li> error() : error handling
* </ul>
* <br>
* If you put a contentType object into the context within either your
* serlvet or within your template, then that will be used to override
* the default content type specified in the properties file.
*
* "contentType" - The value for the Content-Type: header
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="kjohnson@transparent.com">Kent Johnson</a>
* @author <a href="dlr@finemaltcoding.com">Daniel Rall</a>
* $Id: VelocityServlet.java,v 1.45 2002/04/03 16:07:33 dlr Exp $
*/
public abstract class VelocityServlet extends HttpServlet
{
/**
* The HTTP request object context key.
*/
public static final String REQUEST = "req";
/**
* The HTTP response object context key.
*/
public static final String RESPONSE = "res";
/**
* The HTTP content type context key.
*/
public static final String CONTENT_TYPE = "default.contentType";
/**
* The default content type for the response
*/
public static final String DEFAULT_CONTENT_TYPE = "text/html";
/**
* Encoding for the output stream
*/
public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
/**
* The encoding to use when generating outputing.
*/
private static String encoding = null;
/**
* The default content type.
*/
private static String defaultContentType;
/**
* This is the string that is looked for when getInitParameter is
* called (<code>org.apache.velocity.properties</code>).
*/
protected static final String INIT_PROPS_KEY =
"org.apache.velocity.properties";
/**
* Use of this properties key has been deprecated, and will be
* removed in Velocity version 1.5.
*/
private static final String OLD_INIT_PROPS_KEY = "properties";
/**
* Cache of writers
*/
private static SimplePool writerPool = new SimplePool(40);
/**
* Performs initialization of this servlet. Called by the servlet
* container on loading.
*
* @param config The servlet configuration to apply.
*
* @exception ServletException
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
/*
* do whatever we have to do to init Velocity
*/
initVelocity( config );
/*
* we can get these now that velocity is initialized
*/
defaultContentType = RuntimeSingleton.getString( CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
encoding = RuntimeSingleton.getString( RuntimeSingleton.OUTPUT_ENCODING,
DEFAULT_OUTPUT_ENCODING);
return;
}
/**
* Initializes the Velocity runtime, first calling
* loadConfiguration(ServletConvig) to get a
* java.util.Properties of configuration information
* and then calling Velocity.init(). Override this
* to do anything to the environment before the
* initialization of the singelton takes place, or to
* initialize the singleton in other ways.
*/
protected void initVelocity( ServletConfig config )
throws ServletException
{
try
{
/*
* call the overridable method to allow the
* derived classes a shot at altering the configuration
* before initializing Runtime
*/
Properties props = loadConfiguration( config );
Velocity.init( props );
}
catch( Exception e )
{
throw new ServletException("Error initializing Velocity: " + e);
}
return;
}
/**
* Loads the configuration information and returns that
* information as a Properties, which will be used to
* initialize the Velocity runtime.
* <br><br>
* Currently, this method gets the initialization parameter
* VelocityServlet.INIT_PROPS_KEY, which should be a file containing
* the configuration information.
* <br><br>
* To configure your Servlet Spec 2.2 compliant servlet runner to pass
* this to you, put the following in your WEB-INF/web.xml file
* <br>
* <pre>
* <servlet>
* <servlet-name> YourServlet </servlet-name>
* <servlet-class> your.package.YourServlet </servlet-class>
* <init-param>
* <param-name> org.apache.velocity.properties </param-name>
* <param-value> velocity.properties </param-value>
* </init-param>
* </servlet>
* </pre>
*
* Alternately, if you wish to configure an entire context in this
* fashion, you may use the following:
* <br>
* <pre>
* <context-param>
* <param-name> org.apache.velocity.properties </param-name>
* <param-value> velocity.properties </param-value>
* <description> Path to Velocity configuration </description>
* </context-param>
* </pre>
*
* Derived classes may do the same, or take advantage of this code to do the loading for them via :
* <pre>
* Properties p = super.loadConfiguration( config );
* </pre>
* and then add or modify the configuration values from the file.
* <br>
*
* @param config ServletConfig passed to the servlets init() function
* Can be used to access the real path via ServletContext (hint)
* @return java.util.Properties loaded with configuration values to be used
* to initialize the Velocity runtime.
* @throws FileNotFoundException if a specified file is not found.
* @throws IOException I/O problem accessing the specified file, if specified.
*/
protected Properties loadConfiguration(ServletConfig config )
throws IOException, FileNotFoundException
{
// This is a little overly complex because of legacy support
// for the initialization properties key "properties".
// References to OLD_INIT_PROPS_KEY should be removed at
// Velocity version 1.5.
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
propsFile = config.getInitParameter(OLD_INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
propsFile = config.getServletContext()
.getInitParameter(INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
propsFile = config.getServletContext()
.getInitParameter(OLD_INIT_PROPS_KEY);
}
else
{
// TODO: Log deprecation warning.
}
}
else
{
// TODO: Log deprecation warning.
}
}
/*
* This will attempt to find the location of the properties
* file from the relative path to the WAR archive (ie:
* docroot). Since JServ returns null for getRealPath()
* because it was never implemented correctly, then we know we
* will not have an issue with using it this way. I don't know
* if this will break other servlet engines, but it probably
* shouldn't since WAR files are the future anyways.
*/
Properties p = new Properties();
if ( propsFile != null )
{
String realPath = getServletContext().getRealPath(propsFile);
if ( realPath != null )
{
propsFile = realPath;
}
p.load( new FileInputStream(propsFile) );
}
return p;
}
/**
* Handles GET - calls doRequest()
*/
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handle a POST request - calls doRequest()
*/
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles all requests
*
* @param request HttpServletRequest object containing client request
* @param response HttpServletResponse object for the response
*/
protected void doRequest(HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
try
{
/*
* first, get a context
*/
Context context = createContext( request, response );
/*
* set the content type
*/
setContentType( request, response );
/*
* let someone handle the request
*/
Template template = handleRequest( request, response, context );
/*
* bail if we can't find the template
*/
if ( template == null )
{
return;
}
/*
* now merge it
*/
mergeTemplate( template, context, response );
/*
* call cleanup routine to let a derived class do some cleanup
*/
requestCleanup( request, response, context );
}
catch (Exception e)
{
/*
* call the error handler to let the derived class
* do something useful with this failure.
*/
error( request, response, e);
}
}
protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context )
{
return;
}
protected void mergeTemplate( Template template, Context context, HttpServletResponse response )
throws ResourceNotFoundException, ParseErrorException,
MethodInvocationException, IOException, UnsupportedEncodingException, Exception
{
ServletOutputStream output = response.getOutputStream();
VelocityWriter vw = null;
try
{
vw = (VelocityWriter) writerPool.get();
if (vw == null)
{
vw = new VelocityWriter( new OutputStreamWriter(output, encoding), 4*1024, true);
}
else
{
vw.recycle(new OutputStreamWriter(output, encoding));
}
template.merge( context, vw);
}
finally
{
try
{
if (vw != null)
{
/*
* flush and put back into the pool
* don't close to allow us to play
* nicely with others.
*/
vw.flush();
writerPool.put(vw);
}
}
catch (Exception e)
{
// do nothing
}
}
}
/**
* Sets the content type of the response. This is available to be overriden
* by a derived class.
*
* The default implementation is :
*
* response.setContentType( defaultContentType );
*
* where defaultContentType is set to the value of the default.contentType
* property, or "text/html" if that is not set.
*
* @param request servlet request from client
* @param response servlet reponse to client
*/
protected void setContentType( HttpServletRequest request, HttpServletResponse response )
{
response.setContentType( defaultContentType );
}
/**
* Returns a context suitable to pass to the handleRequest() method
* <br><br>
* Default implementation will create a VelocityContext object,
* put the HttpServletRequest and HttpServletResponse
* into the context accessable via the keys VelocityServlet.REQUEST and
* VelocityServlet.RESPONSE, respectively.
*
* @param request servlet request from client
* @param response servlet reponse to client
*
* @return context
*/
protected Context createContext(HttpServletRequest request, HttpServletResponse response )
{
/*
* create a new context
*/
VelocityContext context = new VelocityContext();
/*
* put the request/response objects into the context
* wrap the HttpServletRequest to solve the introspection
* problems
*/
context.put( REQUEST, request );
context.put( RESPONSE, response );
return context;
}
/**
* Retrieves the requested template.
*
* @param name The file name of the template to retrieve relative to the
* template root.
* @return The requested template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*/
public Template getTemplate( String name )
throws ResourceNotFoundException, ParseErrorException, Exception
{
return RuntimeSingleton.getTemplate(name);
}
/**
* Retrieves the requested template with the specified
* character encoding.
*
* @param name The file name of the template to retrieve relative to the
* template root.
* @param encoding the character encoding of the template
*
* @return The requested template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*
* @since Velocity v1.1
*/
public Template getTemplate( String name, String encoding )
throws ResourceNotFoundException, ParseErrorException, Exception
{
return RuntimeSingleton.getTemplate( name, encoding );
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
* <br><br>
* In the event of a problem, you may handle the request directly
* and return <code>null</code> or throw a more meaningful exception
* for the error handler to catch.
*
* @param request servlet request from client
* @param response servlet reponse
* @param ctx The context to add your data to.
* @return The template to merge with your context or null, indicating
* that you handled the processing.
*
* @since Velocity v1.1
*/
protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx )
throws Exception
{
/*
* invoke handleRequest
*/
Template t = handleRequest( ctx );
/*
* if it returns null, this is the 'old' deprecated
* way, and we want to mimic the behavior for a little
* while anyway
*/
if (t == null)
{
throw new Exception ("handleRequest(Context) returned null - no template selected!" );
}
return t;
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
* <br><br>
* In the event of a problem, you may simple return <code>null</code>
* or throw a more meaningful exception.
*
* @deprecated Use
* {@link #handleRequest( HttpServletRequest request,
* HttpServletResponse response, Context ctx )}
*
* @param ctx The context to add your data to.
* @return The template to merge with your context.
*/
protected Template handleRequest( Context ctx )
throws Exception
{
throw new Exception ("You must override VelocityServlet.handleRequest( Context) "
+ " or VelocityServlet.handleRequest( HttpServletRequest, "
+ " HttpServletResponse, Context)" );
}
/**
* Invoked when there is an error thrown in any part of doRequest() processing.
* <br><br>
* Default will send a simple HTML response indicating there was a problem.
*
* @param request original HttpServletRequest from servlet container.
* @param response HttpServletResponse object from servlet container.
* @param cause Exception that was thrown by some other part of process.
*/
protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause )
throws ServletException, IOException
{
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<body bgcolor=\"#ffffff\">");
html.append("<h2>VelocityServlet : Error processing the template</h2>");
html.append("<pre>");
html.append( cause );
html.append("<br>");
StringWriter sw = new StringWriter();
cause.printStackTrace( new PrintWriter( sw ) );
html.append( sw.toString() );
html.append("</pre>");
html.append("</body>");
html.append("</html>");
response.getOutputStream().print( html.toString() );
}
}
|
package org.apache.velocity.test;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.LogSystem;
import junit.framework.TestCase;
/**
* Tests if we can hand Velocity an arbitrary class for logging.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ExternalLoggerTest.java,v 1.4 2001/08/20 11:08:14 geirm Exp $
*/
public class ExternalLoggerTest extends TestCase implements LogSystem
{
private String logString = null;
private VelocityEngine ve = null;
/**
* Default constructor.
*/
public ExternalLoggerTest()
{
super("LoggerTest");
try
{
/*
* use an alternative logger. Set it up here and pass it in.
*/
ve = new VelocityEngine();
ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this );
ve.init();
}
catch (Exception e)
{
System.err.println("Cannot setup LoggerTest : " + e);
System.exit(1);
}
}
public void init( RuntimeServices rs )
{
// do nothing with it
}
public static junit.framework.Test suite ()
{
return new ExternalLoggerTest();
}
/**
* Runs the test.
*/
public void runTest ()
{
/*
* simply log something and see if we get it.
*/
logString = null;
String testString = "This is a test.";
ve.warn( testString );
if (logString == null || !logString.equals( VelocityEngine.WARN_PREFIX + testString ) )
{
fail("Didn't recieve log message.");
}
}
public void logVelocityMessage(int level, String message)
{
String out = "";
/*
* Start with the appropriate prefix
*/
switch( level )
{
case LogSystem.DEBUG_ID :
out = VelocityEngine.DEBUG_PREFIX;
break;
case LogSystem.INFO_ID :
out = VelocityEngine.INFO_PREFIX;
break;
case LogSystem.WARN_ID :
out = VelocityEngine.WARN_PREFIX;
break;
case LogSystem.ERROR_ID :
out = VelocityEngine.ERROR_PREFIX;
break;
default :
out = VelocityEngine.UNKNOWN_PREFIX;
break;
}
logString = out + message;
}
}
|
package org.jdesktop.swingx.border;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.util.HashMap;
import java.util.Map;
import javax.swing.UIManager;
import javax.swing.border.Border;
/**
* Implements a DropShadow for components. In general, the DropShadowBorder will
* work with any rectangular components that do not have a default border installed
* as part of the look and feel, or otherwise. For example, DropShadowBorder works
* wonderfully with JPanel, but horribly with JComboBox.
*
* @author rbair
*/
public class DropShadowBorder implements Border {
private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT,
BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT};
private static final Map<Integer,Map<Position,BufferedImage>> CACHE
= new HashMap<Integer,Map<Position,BufferedImage>>();
private final Color lineColor;
private final int lineWidth;
private final int shadowSize;
private final float shadowOpacity;
private final int cornerSize;
private final boolean showTopShadow;
private final boolean showLeftShadow;
private final boolean showBottomShadow;
private final boolean showRightShadow;
public DropShadowBorder() {
this(UIManager.getColor("Control"), 1, 5);
}
public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) {
this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true);
}
public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) {
this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true);
}
public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize,
float shadowOpacity, int cornerSize, boolean showTopShadow,
boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) {
this.lineColor = lineColor;
this.lineWidth = lineWidth;
this.shadowSize = shadowSize;
this.shadowOpacity = shadowOpacity;
this.cornerSize = cornerSize;
this.showTopShadow = showTopShadow;
this.showLeftShadow = showLeftShadow;
this.showBottomShadow = showBottomShadow;
this.showRightShadow = showRightShadow;
}
/**
* @inheritDoc
*/
public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) {
/*
* 1) Get images for this border
* 2) Paint the images for each side of the border that should be painted
*/
Map<Position,BufferedImage> images = getImages(null);
//compute the edges of the component -- not including the border
// int leftEdge = x + borderInsets.left;
// int rightEdge = x + width - borderInsets.right;
// int topEdge = y + borderInsets.top;
// int bottomEdge = y + height - borderInsets.bottom;
Graphics2D g2 = (Graphics2D)graphics.create();
g2.setColor(lineColor);
//The location and size of the shadows depends on which shadows are being
//drawn. For instance, if the left & bottom shadows are being drawn, then
//the left shadow extends all the way down to the corner, a corner is drawn,
//and then the bottom shadow begins at the corner. If, however, only the
//bottom shadow is drawn, then the bottom-left corner is drawn to the
//right of the corner, and the bottom shadow is somewhat shorter than before.
Point topLeftShadowPoint = null;
if (showLeftShadow || showTopShadow) {
topLeftShadowPoint = new Point();
if (showLeftShadow && !showTopShadow) {
topLeftShadowPoint.setLocation(x, y + shadowSize);
} else if (showLeftShadow && showTopShadow) {
topLeftShadowPoint.setLocation(x, y);
} else if (!showLeftShadow && showTopShadow) {
topLeftShadowPoint.setLocation(x + shadowSize, y);
}
}
Point bottomLeftShadowPoint = null;
if (showLeftShadow || showBottomShadow) {
bottomLeftShadowPoint = new Point();
if (showLeftShadow && !showBottomShadow) {
bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize);
} else if (showLeftShadow && showBottomShadow) {
bottomLeftShadowPoint.setLocation(x, y + height - shadowSize);
} else if (!showLeftShadow && showBottomShadow) {
bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize);
}
}
Point bottomRightShadowPoint = null;
if (showRightShadow || showBottomShadow) {
bottomRightShadowPoint = new Point();
if (showRightShadow && !showBottomShadow) {
bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize);
} else if (showRightShadow && showBottomShadow) {
bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize);
} else if (!showRightShadow && showBottomShadow) {
bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize);
}
}
Point topRightShadowPoint = null;
if (showRightShadow || showTopShadow) {
topRightShadowPoint = new Point();
if (showRightShadow && !showTopShadow) {
topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize);
} else if (showRightShadow && showTopShadow) {
topRightShadowPoint.setLocation(x + width - shadowSize, y);
} else if (!showRightShadow && showTopShadow) {
topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y);
}
}
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
if (showLeftShadow) {
Rectangle leftShadowRect =
new Rectangle(x,
topLeftShadowPoint.y + shadowSize,
shadowSize,
bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize);
g2.drawImage(images.get(Position.LEFT),
leftShadowRect.x, leftShadowRect.y,
leftShadowRect.width, leftShadowRect.height, null);
}
if (showBottomShadow) {
Rectangle bottomShadowRect =
new Rectangle(bottomLeftShadowPoint.x + shadowSize,
y + height - shadowSize,
bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize,
shadowSize);
g2.drawImage(images.get(Position.BOTTOM),
bottomShadowRect.x, bottomShadowRect.y,
bottomShadowRect.width, bottomShadowRect.height, null);
}
if (showRightShadow) {
Rectangle rightShadowRect =
new Rectangle(x + width - shadowSize,
topRightShadowPoint.y + shadowSize,
shadowSize,
bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize);
g2.drawImage(images.get(Position.RIGHT),
rightShadowRect.x, rightShadowRect.y,
rightShadowRect.width, rightShadowRect.height, null);
}
if (showTopShadow) {
Rectangle topShadowRect =
new Rectangle(topLeftShadowPoint.x + shadowSize,
y,
topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize,
shadowSize);
g2.drawImage(images.get(Position.TOP),
topShadowRect.x, topShadowRect.y,
topShadowRect.width, topShadowRect.height, null);
}
if (showLeftShadow || showTopShadow) {
g2.drawImage(images.get(Position.TOP_LEFT),
topLeftShadowPoint.x, topLeftShadowPoint.y, null);
}
if (showLeftShadow || showBottomShadow) {
g2.drawImage(images.get(Position.BOTTOM_LEFT),
bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null);
}
if (showRightShadow || showBottomShadow) {
g2.drawImage(images.get(Position.BOTTOM_RIGHT),
bottomRightShadowPoint.x, bottomRightShadowPoint.y, null);
}
if (showRightShadow || showTopShadow) {
g2.drawImage(images.get(Position.TOP_RIGHT),
topRightShadowPoint.x, topRightShadowPoint.y, null);
}
g2.dispose();
}
private Map<Position,BufferedImage> getImages(Graphics2D g2) {
//first, check to see if an image for this size has already been rendered
//if so, use the cache. Else, draw and save
Map<Position,BufferedImage> images = CACHE.get(shadowSize);
if (images == null) {
images = new HashMap<Position,BufferedImage>();
/*
* Do draw a drop shadow, I have to:
* 1) Create a rounded rectangle
* 2) Create a BufferedImage to draw the rounded rect in
* 3) Translate the graphics for the image, so that the rectangle
* is centered in the drawn space. The border around the rectangle
* needs to be shadowWidth wide, so that there is space for the
* shadow to be drawn.
* 4) Draw the rounded rect as black, with an opacity of 50%
* 5) Create the BLUR_KERNEL
* 6) Blur the image
* 7) copy off the corners, sides, etc into images to be used for
* drawing the Border
*/
int rectWidth = cornerSize + 1;
RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize);
int imageWidth = rectWidth + shadowSize * 2;
BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB);
Graphics2D buffer = (Graphics2D)image.getGraphics();
buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity));
buffer.translate(shadowSize, shadowSize);
buffer.fill(rect);
buffer.dispose();
float blurry = 1.0f / (float)(shadowSize * shadowSize);
float[] blurKernel = new float[shadowSize * shadowSize];
for (int i=0; i<blurKernel.length; i++) {
blurKernel[i] = blurry;
}
ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel));
BufferedImage targetImage = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB);
((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2));
int x = 1;
int y = 1;
int w = shadowSize;
int h = shadowSize;
images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h));
x = 1;
y = h;
w = shadowSize;
h = 1;
images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h));
x = 1;
y = rectWidth;
w = shadowSize;
h = shadowSize;
images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h));
x = cornerSize + 1;
y = rectWidth;
w = 1;
h = shadowSize;
images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h));
x = rectWidth;
y = x;
w = shadowSize;
h = shadowSize;
images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h));
x = rectWidth;
y = cornerSize + 1;
w = shadowSize;
h = 1;
images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h));
x = rectWidth;
y = 1;
w = shadowSize;
h = shadowSize;
images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h));
x = shadowSize;
y = 1;
w = 1;
h = shadowSize;
images.put(Position.TOP, getSubImage(targetImage, x, y, w, h));
image.flush();
CACHE.put(shadowSize, images);
}
return images;
}
/**
* Returns a new BufferedImage that represents a subregion of the given
* BufferedImage. (Note that this method does not use
* BufferedImage.getSubimage(), which will defeat image acceleration
* strategies on later JDKs.)
*/
private BufferedImage getSubImage(BufferedImage img,
int x, int y, int w, int h) {
BufferedImage ret = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = ret.createGraphics();
g2.drawImage(img,
0, 0, w, h,
x, y, x+w, y+h,
null);
g2.dispose();
return ret;
}
/**
* @inheritDoc
*/
public Insets getBorderInsets(Component c) {
int top = showTopShadow ? lineWidth + shadowSize : lineWidth;
int left = showLeftShadow ? lineWidth + shadowSize : lineWidth;
int bottom = showBottomShadow ? lineWidth + shadowSize : lineWidth;
int right = showRightShadow ? lineWidth + shadowSize : lineWidth;
return new Insets(top, left, bottom, right);
}
/**
* @inheritDoc
*/
public boolean isBorderOpaque() {
return false;
}
public boolean isShowTopShadow() {
return showTopShadow;
}
public boolean isShowLeftShadow() {
return showLeftShadow;
}
public boolean isShowRightShadow() {
return showRightShadow;
}
public boolean isShowBottomShadow() {
return showBottomShadow;
}
public int getLineWidth() {
return lineWidth;
}
public Color getLineColor() {
return lineColor;
}
public int getShadowSize() {
return shadowSize;
}
public float getShadowOpacity() {
return shadowOpacity;
}
public int getCornerSize() {
return cornerSize;
}
}
|
package sr_eels;
import eftemj.EFTEMj;
import gui.GenericDialogPlus;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.gui.GenericDialog;
import ij.plugin.filter.ExtendedPlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import libs.lma.LMA;
import tools.StringManipulator;
/**
* <p>
* This plugin is used to correct SR-EELS images.
* </p>
* <p>
* As it implements {@link ExtendedPlugInFilter} you have to apply it to an
* image. Additionally there has to be a SR-EELS characterisation data set. Each
* data set contains the files <code>Borders.txt</code> and
* <code>Width.txt</code> that are necessary to run the correction. The plugin
* assumes that the data set is can be found in a sub folder of where the
* SR-EELS image is stored. If there is more than one characterisation data set,
* the plugin presents a dialog to choose the preferred data set.
* </p>
*
* @author Michael Entrup b. Epping <michael.entrup@wwu.de>
*/
public class SR_EELS_CorrectionPlugin implements ExtendedPlugInFilter {
/**
* The plugin will be aborted.
*/
private final int CANCEL = 0;
/**
* The plugin will continue with the next step.
*/
private final int OK = 1;
/**
* <code>DOES_32 | NO_CHANGES | FINAL_PROCESSING</code>
*/
private final int FLAGS = DOES_32 | NO_CHANGES | FINAL_PROCESSING;
/**
* A {@link String} for the file field of the {@link GenericDialogPlus}.
*/
private final String NO_FILE_SELECTED = "No file selected.";
/**
* The path where <code>Borders.txt</code> can be found.
*/
private String pathBorders = NO_FILE_SELECTED;
/**
* The path where <code>Width.txt</code> can be found.
*/
private String pathWidth = NO_FILE_SELECTED;
/**
* <p>
* An {@link SR_EELS_FloatProcessor} that contains the image that will be
* corrected.
* </p>
* <p>
* The input image will not be changed!
* </p>
*/
private SR_EELS_FloatProcessor inputProcessor;
private SR_EELS_FloatProcessor outputProcessor;
private String title;
/**
* <p>
* An {@link ImagePlus} that contains the image that is the result of the
* correction.
* </p>
*/
private ImagePlus outputImage;
/**
* This field indicates the progress. A static method is used to increase the
* value by 1. It is necessary to use volatile because different
* {@link Thread}s call the related method.
*/
private static volatile int progress;
/**
* Number of steps until the correction is finished.
*/
private static int progressSteps;
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.PlugInFilter#setup(java.lang.String, ij.ImagePlus)
*/
@Override
public int setup(final String arg, final ImagePlus imp) {
/*
* This will be called when the run method has finished.
*/
if (arg == "final") {
outputImage.show();
return NO_CHANGES | DONE;
}
return FLAGS;
}
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
*/
@Override
public void run(final ImageProcessor ip) {
IJ.showStatus("Preparing correction...");
final SR_EELS_Polynomial_2D widthFunction = getFunctionWidth();
inputProcessor.setWidthFunction(widthFunction);
final SR_EELS_Polynomial_2D borderFunction = getFunctionBorders();
inputProcessor.setBorderFunction(borderFunction);
/*
* TODO: Add the used correction methods to the image title.
*/
outputProcessor = widthFunction.createOutputImage();
outputImage = new ImagePlus(title + "_corrected", outputProcessor);
final CoordinateCorrector coordinateCorrection =
new FullCoordinateCorrection(inputProcessor, outputProcessor);
final IntensityCorrector intensityCorrection =
new SimpleIntensityCorrection(inputProcessor, coordinateCorrection);
/*
* Each line of the image is a step that is visualise by the progress bar of
* ImageJ.
*/
setupProgress(outputProcessor.getHeight());
if (EFTEMj.debugLevel == EFTEMj.DEBUG_FULL) {
for (int x2 = 0; x2 < outputProcessor.getHeight(); x2++) {
for (int x1 = 0; x1 < outputProcessor.getWidth(); x1++) {
final float intensity = intensityCorrection.getIntensity(x1, x2);
outputProcessor.setf(x1, x2, intensity);
}
updateProgress();
}
}
else {
final ExecutorService executorService =
Executors
.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int x2 = 0; x2 < outputProcessor.getHeight(); x2++) {
final int x2Temp = x2;
executorService.execute(new Runnable() {
@Override
public void run() {
for (int x1 = 0; x1 < outputProcessor.getWidth(); x1++) {
final float intensity =
intensityCorrection.getIntensity(x1, x2Temp);
outputProcessor.setf(x1, x2Temp, intensity);
}
updateProgress();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(30, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Use this method for batch processing. Values that are set up by the GUI
* have to be paased as parameters.
*
* @param input_image is the image to correct.
* @param path_borders is the text file that contains the characterisation
* results for the borders.
* @param path_width is the text file that contains the characterisation
* results for the width.
* @return the corrected image.
*/
public ImagePlus correctImage(final ImagePlus input_image,
final String path_borders, final String path_width)
{
this.inputProcessor =
new SR_EELS_FloatProcessor((FloatProcessor) input_image.getProcessor(),
CameraSetup.getFullWidth() / input_image.getWidth(), CameraSetup
.getFullHeight() /
input_image.getHeight(), input_image.getWidth() / 2, input_image
.getHeight() / 2);
title = StringManipulator.removeExtensionFromTitle(input_image.getTitle());
this.pathBorders = path_borders;
this.pathWidth = path_width;
run(null);
return outputImage;
}
/**
* <p>
* The results of the {@link SR_EELS_CharacterisationPlugin} plugin are
* parsed.
* </p>
* <p>
* This function extracts the values that describe the pathway of the borders
* of a spectrum.
* </p>
*
* @return a polynomial that fits the given data points
*/
private SR_EELS_Polynomial_2D getFunctionBorders() {
final DataImporter importer = new DataImporter(pathBorders, true);
final double[][] vals =
new double[importer.vals.length][importer.vals[0].length];
for (int i = 0; i < vals.length; i++) {
// y value (this is a position on the x2 axis)
vals[i][0] = importer.vals[i][0] - CameraSetup.getFullHeight() / 2;
// x1 value
vals[i][1] = importer.vals[i][1] - CameraSetup.getFullWidth() / 2;
// x2 value
vals[i][2] = importer.vals[i][2] - CameraSetup.getFullHeight() / 2;
}
/*
* Define the orders of the 2D polynomial.
*/
final int m = 3;
final int n = 2;
final SR_EELS_Polynomial_2D func = new SR_EELS_Polynomial_2D(m, n);
final double[] a_fit = new double[(m + 1) * (n + 1)];
Arrays.fill(a_fit, 1.);
final LMA lma = new LMA(func, a_fit, vals);
lma.fit();
if (true) {
IJ.log(func.compareWithGnuplot(SR_EELS_Polynomial_2D.BORDERS));
}
return new SR_EELS_Polynomial_2D(m, n, a_fit);
}
/**
* <p>
* The results of the {@link SR_EELS_CharacterisationPlugin} plugin are
* parsed.
* </p>
* <p>
* This function extracts the values that describe the width of a spectrum
* depending on its position on the camera.
* </p>
*
* @return a polynomial that fits the given data points
*/
private SR_EELS_Polynomial_2D getFunctionWidth() {
final DataImporter importer = new DataImporter(pathWidth, false);
final double[][] vals =
new double[importer.vals.length][importer.vals[0].length];
for (int i = 0; i < vals.length; i++) {
// y value (the width is a difference of two x2 values)
vals[i][0] = importer.vals[i][0];
// x1 value
vals[i][1] = importer.vals[i][1] - CameraSetup.getFullWidth() / 2;
// x2 value
vals[i][2] = importer.vals[i][2] - CameraSetup.getFullHeight() / 2;
}
/*
* Define the orders of the 2D polynomial.
*/
final int m = 2;
final int n = 2;
final SR_EELS_Polynomial_2D func = new SR_EELS_Polynomial_2D(m, n);
final double[] b_fit = new double[(m + 1) * (n + 1)];
Arrays.fill(b_fit, 1.);
final LMA lma = new LMA(func, b_fit, vals);
lma.fit();
if (true) {
IJ.log(func.compareWithGnuplot(SR_EELS_Polynomial_2D.WIDTH_VS_POS));
}
return new SR_EELS_Polynomial_2D(m, n, b_fit);
}
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.ExtendedPlugInFilter#showDialog(ij.ImagePlus, java.lang.String,
* ij.plugin.filter.PlugInFilterRunner)
*/
@Override
public int showDialog(final ImagePlus imp, final String command,
final PlugInFilterRunner pfr)
{
final String searchPath = IJ.getDirectory("image");
final LinkedList<String> found_poly = new LinkedList<String>();
final LinkedList<String> found_borders = new LinkedList<String>();
findDatasets(searchPath, found_poly, SR_EELS.FILENAME_WIDTH);
findDatasets(searchPath, found_borders, SR_EELS.FILENAME_BORDERS);
if (found_poly.size() > 1 | found_borders.size() > 1) {
/*
* A dialog is presented to select one of the found files.
*/
final GenericDialog gd =
new GenericDialog(command + " - Select data set", IJ.getInstance());
if (found_poly.size() > 1) {
String[] files_poly = new String[found_poly.size()];
files_poly = found_poly.toArray(files_poly);
gd.addRadioButtonGroup(SR_EELS.FILENAME_WIDTH, files_poly, found_poly
.size(), 1, found_poly.get(0));
}
if (found_borders.size() > 1) {
String[] files_borders = new String[found_borders.size()];
files_borders = found_borders.toArray(files_borders);
gd.addRadioButtonGroup(SR_EELS.FILENAME_BORDERS, files_borders,
found_borders.size(), 1, found_borders.get(0));
}
gd.setResizable(false);
gd.showDialog();
if (gd.wasCanceled()) {
canceled();
return NO_CHANGES | DONE;
}
if (found_poly.size() > 1) {
pathWidth = gd.getNextRadioButton();
}
if (found_borders.size() > 1) {
pathBorders = gd.getNextRadioButton();
}
}
/*
* If only one file has been found, this one automatically is passed to the
* parameters dialog.
*/
if (found_poly.size() == 1) {
pathWidth = found_poly.getFirst();
}
if (found_borders.size() == 1) {
pathBorders = found_borders.getFirst();
}
do {
if (showParameterDialog(command) == CANCEL) {
canceled();
return NO_CHANGES | DONE;
}
}
while (!pathWidth.contains(".txt") | !pathBorders.contains(".txt"));
inputProcessor =
new SR_EELS_FloatProcessor((FloatProcessor) imp.getProcessor(),
CameraSetup.getFullWidth() / imp.getWidth(), CameraSetup
.getFullHeight() /
imp.getHeight(), imp.getWidth() / 2, imp.getHeight() / 2);
title = StringManipulator.removeExtensionFromTitle(imp.getTitle());
return FLAGS;
}
/**
* Searches the given folder for a data set file. Recursion is used to search
* in subfolders.
*
* @param searchPath the folder to search in.
* @param found a {@link Vector} that stores all found file paths.
* @param filename is the full name of the file we search for.
*/
private void findDatasets(final String searchPath,
final LinkedList<String> found, final String filename)
{
final String[] entries = new File(searchPath).list();
for (final String entrie : entries) {
if (entrie.equals(filename)) {
found.add(searchPath + entrie);
}
if (new File(searchPath + entrie).isDirectory()) {
findDatasets(searchPath + entrie + File.separatorChar, found, filename);
}
}
}
/**
* Creates and shows the {@link GenericDialog} that is used to set the
* parameters for elemental mapping.
*
* @param dialogTitle
* @return The constant <code>OK</code> or <code>CANCEL</code>.
*/
private int showParameterDialog(final String dialogTitle) {
final GenericDialogPlus gd =
new GenericDialogPlus(dialogTitle + " - set parameters", IJ.getInstance());
gd.addFileField(SR_EELS.FILENAME_WIDTH, pathWidth);
gd.addFileField(SR_EELS.FILENAME_BORDERS, pathBorders);
// TODO Add drop down menu for correction method.
gd.setResizable(false);
gd.showDialog();
if (gd.wasCanceled()) {
return CANCEL;
}
pathWidth = gd.getNextString();
pathBorders = gd.getNextString();
return OK;
}
/**
* Cancel the plugin and show a status message.
*/
private void canceled() {
IJ.showStatus("SR-EELS correction has been canceled.");
}
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.ExtendedPlugInFilter#setNPasses(int)
*/
@Override
public void setNPasses(final int nPasses) {
// This method is not used.
}
private static void setupProgress(final int fullProgress) {
progressSteps = fullProgress;
progress = 0;
}
private static void updateProgress() {
progress++;
IJ.showProgress(progress, progressSteps);
}
public static void main(final String[] args) {
EFTEMj.debugLevel = EFTEMj.DEBUG_FULL;
/*
* start ImageJ
*/
new ImageJ();
String baseFolder = "C:/Temp/";
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 ||
os.indexOf("aix") > 0)
{
baseFolder = "~/Downloads/";
}
/*
* Check if the test image is available. Otherwise prompt a message with the
* download link.
*/
final File testImage =
new File(baseFolder + "20140106 SM125 -20%/SR-EELS_TestImage_small.tif");
if (!testImage.exists()) {
final String url = "http://eftemj.entrup.com.de/SR-EELS_TestImage.zip";
/*
* IJ.showMessage("Test image not found", "<html>" + "Please download the file" + "<br />" + "<a href='" +
* url + "'>SR-EELS_TestImage.zip</a> from" + "<br/>" + url + "<br />" + "and extract it to 'C:\\temp\\'." +
* "</html>");
*/
final GenericDialog gd = new GenericDialog("Test image not found");
gd.addMessage("Please download the file 'SR-EELS_TestImage.zip' and extract it to '" +
baseFolder + "'.");
gd.addMessage("Copy the following link, or click Ok to open it with your default browser.");
gd.addStringField("", url, url.length());
gd.showDialog();
if (gd.wasOKed()) {
try {
final URI link = new URI(url);
final Desktop desktop = Desktop.getDesktop();
desktop.browse(link);
}
catch (final Exception exc) {
IJ.showMessage("An Exception occured", exc.getMessage());
return;
}
}
return;
}
/*
* open the test image
*/
final ImagePlus image =
IJ.openImage("C:/Temp/20140106 SM125 -20%/SR-EELS_TestImage_small.tif");
// final ImagePlus image =
// IJ.openImage("Q:/Aktuell/SR-EELS Calibration measurements/20131104 SM125 80%/projection.tif");
image.show();
/*
* run the plugin
*/
final Class<?> clazz = SR_EELS_CorrectionPlugin.class;
IJ.runPlugIn(clazz.getName(), "");
}
/**
* <p>
* This class is used to load a data file that contains a data set for the fit
* of a 2D polynomial. For each y-value there is are pairs of x-values that is
* stored at a 2D array.
* </p>
* <p>
* The data file must contain one data point at each line. Each data point
* contains of x1, x2 and y separated by whitespace. Lines that contain a '#'
* are regarded as comments.
* </p>
* <p>
* The Plugin {@link SR_EELS_CharacterisationPlugin} creates files that can be
* processed by this class.
* </p>
*
* @author Michael Entrup b. Epping <michael.entrup@wwu.de>
*/
private static class DataImporter {
/**
* <p>
* The first index will iterate through all the data points.
* </p>
* <p>
* The second index defines y-value (index 0), the x1-value (index 1) and
* the x2-value (index 2).
* </p>
*/
protected double[][] vals;
/**
* When loading the file <code>Borders.txt</code> there is a fourth column,
* that contains the weight. This value is stored in a separate array-
*/
protected double[] weights;
public DataImporter(final String dataFilePath, final boolean readWeights) {
/*
* 'Borders.txt' contains a fourth column and has to be handled different
* than 'Width.txt'.
*/
boolean isBordersTxt = false;
/*
* First we read the file and store the values a a vector.
*/
final File file = new File(dataFilePath);
final Vector<Double[]> values = new Vector<Double[]>();
try {
final BufferedReader reader = new BufferedReader(new FileReader(file));
boolean containsData = true;
do {
final String line = reader.readLine();
if (line == null) {
containsData = false;
}
else {
/*
* Only read the line if if does not contain any comment.
*/
if (line.indexOf('
/*
* This RegExpr splits the line at whitespace characters.
*/
final String[] splitLine = line.split("\\s+");
if (readWeights == true) {
if (splitLine.length >= 4) {
isBordersTxt = true;
final Double[] point =
{ Double.valueOf(splitLine[0]),
Double.valueOf(splitLine[1]),
Double.valueOf(splitLine[2]),
Double.valueOf(splitLine[3]) };
values.add(point);
}
}
else {
if (splitLine.length >= 3) {
final Double[] point =
{ Double.valueOf(splitLine[0]),
Double.valueOf(splitLine[1]),
Double.valueOf(splitLine[2]) };
values.add(point);
}
}
}
}
}
while (containsData);
reader.close();
}
catch (final FileNotFoundException exc) {
exc.printStackTrace();
}
catch (final IOException exc) {
exc.printStackTrace();
}
/*
* Reading the file is done now.
*/
vals = new double[values.size()][3];
weights = new double[values.size()];
for (int i = 0; i < values.size(); i++) {
if (isBordersTxt) {
vals[i][0] = values.get(i)[2];
}
else {
vals[i][0] = values.get(i)[2];
}
vals[i][1] = values.get(i)[0];
vals[i][2] = values.get(i)[1];
if (readWeights == true) {
weights[i] = values.get(i)[3];
}
}
}
}
}
|
package org.jaxen.saxpath.base;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.jaxen.saxpath.Axis;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.XPathSyntaxException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathReaderTest extends TestCase
{
private ConformanceXPathHandler expected;
private ConformanceXPathHandler actual;
private Document doc;
private XPathReader reader;
private String text;
private String[] paths = {
"/foo/bar[@a='1' and @b='2']",
"/foo/bar[@a='1' and @b!='2']",
"$varname[@a='1']",
"//attribute::*[.!='crunchy']",
|
package com.expidev.gcmapp.http;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.expidev.gcmapp.json.MinistryJsonParser;
import com.expidev.gcmapp.model.Ministry;
import com.expidev.gcmapp.utils.JsonStringReader;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import me.thekey.android.TheKey;
import me.thekey.android.lib.TheKeyImpl;
import static com.expidev.gcmapp.BuildConfig.THEKEY_CLIENTID;
public class GmaApiClient
{
private final String TAG = getClass().getSimpleName();
private static final String BASE_URL_STAGE = "https://stage.sbr.global-registry.org/api";
private static final String BASE_URL_PROD = "https://sbr.global-registry.org/api";
private static final String MEASUREMENTS = "/measurements";
private static final String MINISTRIES = "/ministries";
private static final String TOKEN = "/token";
private static final String TRAINING = "/training";
private final String PREF_NAME = "gcm_prefs";
private final TheKey theKey;
private String ticket;
private Context context;
private LocalBroadcastManager broadcastManager;
private SharedPreferences preferences;
private SharedPreferences.Editor prefEditor;
public GmaApiClient(final Context context)
{
theKey = TheKeyImpl.getInstance(context, THEKEY_CLIENTID);
this.context = context;
broadcastManager = LocalBroadcastManager.getInstance(context);
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
prefEditor = preferences.edit();
}
private HttpsURLConnection prepareRequest(HttpsURLConnection connection)
{
String cookie = preferences.getString("Cookie", "");
if (!cookie.isEmpty())
{
connection.addRequestProperty("Cookie", cookie);
}
return connection;
}
private HttpsURLConnection processResponse(HttpsURLConnection connection) throws IOException
{
if (connection.getHeaderFields() != null)
{
String headerName;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
{
if (headerName.equals("Set-Cookie"))
{
String cookie = connection.getHeaderField(i);
cookie = cookie.split("\\;")[0] + "; ";
stringBuilder.append(cookie);
}
}
// cookie store is not retrieving cookie so it will be saved to preferences
prefEditor.putString("Cookie", stringBuilder.toString());
prefEditor.commit();
}
return connection;
}
public JSONObject authorizeUser()
{
try
{
ticket = theKey.getTicket(BASE_URL_STAGE + MEASUREMENTS + TOKEN);
Log.i(TAG, "Ticket: " + ticket);
if (ticket == null) return null;
String urlString = BASE_URL_STAGE + MEASUREMENTS + TOKEN + "?st=" + ticket + "&refresh=true";
Log.i(TAG, "URL: " + urlString);
URL url = new URL(urlString);
return new JSONObject(httpGet(url));
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
public List<Ministry> getAllMinistries(String sessionToken)
{
String reason;
String urlString = BASE_URL_STAGE + MEASUREMENTS + MINISTRIES + "?token=" + sessionToken;
try
{
JSONObject jsonObject = new JSONObject(httpGet(new URL(urlString)));
if(jsonObject == null)
{
reason = "Failed to retrieve ministries, most likely cause is a bad session ticket";
}
else
{
reason = jsonObject.optString("reason");
}
if(reason != null)
{
Log.e(TAG, reason);
return dummyMinistryList();
}
else
{
JSONArray names = new JSONArray();
names.put("ministry_id");
names.put("name");
JSONArray jsonArray = jsonObject.toJSONArray(names);
return MinistryJsonParser.parseMinistriesJson(jsonArray);
}
}
catch(Exception e)
{
reason = e.getMessage();
Log.e(TAG, "Problem occurred while retrieving ministries: " + reason);
return dummyMinistryList();
}
}
private ArrayList<Ministry> dummyMinistryList()
{
ArrayList<Ministry> dummyList = new ArrayList<Ministry>();
Ministry dummy1 = new Ministry();
dummy1.setMinistryId("37e3bb68-da0b-11e3-9786-12725f8f377c");
dummy1.setName("Addis Ababa Campus Team (ETH)");
dummyList.add(dummy1);
return dummyList;
}
public JSONArray searchTraining(String ministryId, String sessionTicket)
{
try
{
String urlString = BASE_URL_STAGE + MEASUREMENTS +TRAINING +
"?token=" + sessionTicket + "&ministry_id=" + ministryId +
"&mcc=slm";
Log.i(TAG, "Url: " + urlString);
URL url = new URL(urlString);
return new JSONArray(httpGet(url));
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
private String httpGet(URL url) throws IOException, JSONException, URISyntaxException
{
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
prepareRequest(connection);
connection.setReadTimeout(10000);
connection.setConnectTimeout(10000);
connection.connect();
processResponse(connection);
if (connection.getResponseCode() == HttpStatus.SC_OK)
{
InputStream inputStream = connection.getInputStream();
if (inputStream != null)
{
String jsonAsString = JsonStringReader.readFully(inputStream, "UTF-8");
Log.i(TAG, jsonAsString);
// instead of returning a JSONObject, a string will be returned. This is
// because some endpoints return an object and some return an array.
return jsonAsString;
}
}
else
{
Log.d(TAG, "Status: " + connection.getResponseCode());
}
return null;
}
}
|
package com.karambit.bookie.helper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.karambit.bookie.model.User;
import java.util.HashMap;
public class DBHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Bookie.db";
public static final String USER_TABLE_NAME = "user";
public static final String USER_COLUMN_ID = "id";
public static final String USER_COLUMN_NAME = "name";
public static final String USER_COLUMN_IMAGE_URL = "image_url";
public static final String USER_COLUMN_THUMBNAIL_URL = "thumbnail_url";
public static final String USER_COLUMN_LATITUDE = "latitude";
public static final String USER_COLUMN_LONGITUDE = "longitude";
public static final String USER_COLUMN_PASSWORD = "password";
public static final String USER_COLUMN_EMAIL = "email";
public static final String USER_COLUMN_VERIFIED = "verified";
public static final String USER_COLUMN_BIO = "bio";
public static final String USER_COLUMN_BOOK_COUNTER = "book_counter";
public static final String USER_COLUMN_POINT = "point";
private HashMap hp;
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE " + USER_TABLE_NAME +
" (" + USER_COLUMN_ID + " INTEGER PRIMERY KEY, " +
USER_COLUMN_NAME + " TEXT, " +
USER_COLUMN_IMAGE_URL + " TEXT, " +
USER_COLUMN_THUMBNAIL_URL + " TEXT, " +
USER_COLUMN_LATITUDE + " DOUBLE, " +
USER_COLUMN_LONGITUDE + " DOUBLE, " +
USER_COLUMN_PASSWORD + " TEXT, " +
USER_COLUMN_EMAIL + " TEXT, " +
USER_COLUMN_VERIFIED + " BIT, " +
USER_COLUMN_BIO + " TEXT, " +
USER_COLUMN_BOOK_COUNTER + " INTEGER, " +
USER_COLUMN_POINT + " INTEGER)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);
onCreate(db);
}
public boolean insertCurrentUser(int id, String name, String imageURL, String thumbnailURL, double latitude, double longitude,
String password, String email, boolean verified, String bio, int bookCounter, int point) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_COLUMN_ID, id);
contentValues.put(USER_COLUMN_NAME, name);
contentValues.put(USER_COLUMN_IMAGE_URL, imageURL);
contentValues.put(USER_COLUMN_THUMBNAIL_URL, thumbnailURL);
contentValues.put(USER_COLUMN_LATITUDE, latitude);
contentValues.put(USER_COLUMN_LONGITUDE, longitude);
contentValues.put(USER_COLUMN_PASSWORD, password);
contentValues.put(USER_COLUMN_EMAIL, email);
contentValues.put(USER_COLUMN_VERIFIED, verified);
contentValues.put(USER_COLUMN_BIO, bio);
contentValues.put(USER_COLUMN_BOOK_COUNTER, bookCounter);
contentValues.put(USER_COLUMN_POINT, point);
boolean result = db.insert(USER_TABLE_NAME, null, contentValues) > 0;
if (db.isOpen()){
db.close();
}
if (result) {
return true;
} else {
return false;
}
}
public boolean insertCurrentUser(User.Details user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_COLUMN_ID, user.getUser().getID());
contentValues.put(USER_COLUMN_NAME, user.getUser().getName());
contentValues.put(USER_COLUMN_IMAGE_URL, user.getUser().getImageUrl());
contentValues.put(USER_COLUMN_THUMBNAIL_URL, user.getUser().getThumbnailUrl());
contentValues.put(USER_COLUMN_LATITUDE, user.getUser().getLatitude());
contentValues.put(USER_COLUMN_LONGITUDE, user.getUser().getLongitude());
contentValues.put(USER_COLUMN_PASSWORD, user.getPassword());
contentValues.put(USER_COLUMN_EMAIL, user.getEmail());
contentValues.put(USER_COLUMN_VERIFIED, user.isVerified());
contentValues.put(USER_COLUMN_BIO, user.getBio());
contentValues.put(USER_COLUMN_BOOK_COUNTER, user.getBookCounter());
contentValues.put(USER_COLUMN_POINT, user.getPoint());
boolean result = db.insert(USER_TABLE_NAME, null, contentValues) > 0;
if (db.isOpen()){
db.close();
}
if (result) {
return true;
} else {
return false;
}
}
public User getCurrentUser() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECt * FROM " + USER_TABLE_NAME, null);
res.moveToFirst();
User user = new User(res.getInt(res.getColumnIndex(USER_COLUMN_ID)),
res.getString(res.getColumnIndex(USER_COLUMN_NAME)),
res.getString(res.getColumnIndex(USER_COLUMN_IMAGE_URL)),
res.getString(res.getColumnIndex(USER_COLUMN_THUMBNAIL_URL)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LATITUDE)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LONGITUDE)));
res.close();
if (db.isOpen()){
db.close();
}
return user;
}
public User.Details getCurrentUserDetails() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECt * FROM " + USER_TABLE_NAME, null);
res.moveToFirst();
User user = new User(res.getInt(res.getColumnIndex(USER_COLUMN_ID)),
res.getString(res.getColumnIndex(USER_COLUMN_NAME)),
res.getString(res.getColumnIndex(USER_COLUMN_IMAGE_URL)),
res.getString(res.getColumnIndex(USER_COLUMN_THUMBNAIL_URL)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LATITUDE)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LONGITUDE)));
User.Details details = user.new Details(res.getString(res.getColumnIndex(USER_COLUMN_PASSWORD)),
res.getString(res.getColumnIndex(USER_COLUMN_EMAIL)),
res.getInt(res.getColumnIndex(USER_COLUMN_VERIFIED)) > 0,
res.getString(res.getColumnIndex(USER_COLUMN_BIO)),
res.getInt(res.getColumnIndex(USER_COLUMN_BOOK_COUNTER)),
res.getInt(res.getColumnIndex(USER_COLUMN_POINT)));
res.close();
if (db.isOpen()){
db.close();
}
return details;
}
public int deleteCurrentUser() {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(USER_TABLE_NAME, null, null);
if (db.isOpen()){
db.close();
}
return result;
}
}
|
package eu.redray.trevie.utility;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Provides methods for retrieving and deleting movie poster images
*/
public class PosterHeper {
private final static String FILE_EXTENSION = ".png";
private final static String DIRECTORY = "Posters";
/**
* Saves poster image to internal storage
*
* @param context the context of the app giving access to file storage
* @param bitmap the poster of a movie provided as bitmap
* @param title the title of a movie
* @return the path to saved image
*/
public static String savePoster(Context context, Bitmap bitmap, String title) {
OutputStream fOut = null;
Uri outputFileUri = null;
try {
File root = new File(context.getFilesDir()
+ File.separator + DIRECTORY + File.separator);
// Create root directory if it doesn't exist
if (!root.exists()) {
//noinspection ResultOfMethodCallIgnored
root.mkdirs();
}
File sdImageMainDirectory = new File(root, title + FILE_EXTENSION);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (FileNotFoundException e) {
Log.e(PosterHeper.class.getSimpleName(), e.getMessage(), e);
e.printStackTrace();
} finally {
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
if (fOut != null) {
fOut.close();
}
} catch (IOException e) {
Log.e(PosterHeper.class.getSimpleName(), e.getMessage(), e);
e.printStackTrace();
}
}
return outputFileUri.toString();
}
/**
* Deletes poster image from internal storage
*
* @param context the context of the app giving access to file storage
* @param title the title of a movie
* @return true if successful
*/
public static boolean deletePoster(Context context, String title) {
File file = new File(context.getFilesDir() + File.separator + DIRECTORY + File.separator,
title + FILE_EXTENSION);
return file.delete();
}
}
|
package scorched.android;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Controller for the Scorched Android game.
*
* GameControlView gets input from the user, as well as events from other
* parts of the system, and presents them to Graphics and mModel.
*/
class GameControlView extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "GameControlView";
class ScorchedThread extends Thread {
/** The semaphore representing user input during a player's turn */
private Object mUserInputSem = new Object();
/** Represents the current controller state */
private GameState mGameState;
/** True if the game is running */
private boolean mRun = true;
/** Indicate whether or not the game is paused */
private boolean mPaused = false;
/** Handle to the surface manager object we interact with */
private SurfaceHolder mSurfaceHolder;
/** Handle to the application context;
* used to (for example) fetch Drawables. */
private Context mContext;
/** Message handler used by thread to interact with TextView */
private Handler mHandler;
/** The slider representing power */
private SalvoSlider mPowerSlider;
/** The slider representing angle */
private SalvoSlider mAngleSlider;
/** Last X coordinate the user touched (in game coordinates) */
private float mTouchX;
/** Last Y coordinate the user touched (in game coordinates) */
private float mTouchY;
/** The object to control sound */
private Sound mSound;
public ScorchedThread(SurfaceHolder surfaceHolder,
Context context,
Handler handler,
SalvoSlider powerSlider,
SalvoSlider angleSlider) {
mGameState = null;
mSurfaceHolder = surfaceHolder;
mContext = context;
mHandler = handler;
mPowerSlider = powerSlider;
mAngleSlider = angleSlider;
}
/** Shut down the thread */
public void suicide() {
synchronized (mUserInputSem) {
mRun = false;
}
// interrupt anybody in wait()
this.interrupt();
}
/* Callback invoked when the surface dimensions change. */
public void setSurfaceSize(int width, int height) {
synchronized (mUserInputSem) {
Graphics.instance.setSurfaceSize(width, height);
mUserInputSem.notify();
}
}
@Override
public void run() {
Log.w(TAG, "run(): waiting for surface to be created.");
mRun = true;
synchronized (mSurfaceHasBeenCreatedSem) {
while (!mSurfaceHasBeenCreated) {
try {
mSurfaceHasBeenCreatedSem.wait();
}
catch (InterruptedException e) {
Log.w(TAG, "interrupted waiting for " +
"mSurfaceHasBeenCreatedSem");
mRun = false;
}
}
}
Log.w(TAG, "run(): surface has been created.");
// main loop
Log.w(TAG, "run(): entering main loop.");
synchronized (mUserInputSem) {
mGameState = GameState.sTurnStartState;
while (true) {
mGameState.onEnter(mModel,
mPowerSlider, mAngleSlider,
mPowerAdaptor, mAngleAdaptor);
GameState next = null;
while (true) {
next = mGameState.main(mModel);
if (next != null)
break;
// redraw whatever needs to be redrawn
if (mGameState.needRedraw()) {
Canvas canvas = null;
try {
canvas = mSurfaceHolder.lockCanvas(null);
mGameState.redraw(canvas, mModel);
}
finally {
if (canvas != null) {
// Don't leave the Surface in an
// inconsistent state
mSurfaceHolder.
unlockCanvasAndPost(canvas);
}
}
}
try {
if (!mRun) {
Log.w(TAG, "mRun == false. quitting.");
return;
}
mUserInputSem.wait(mGameState.
getBlockingDelay());
}
catch (InterruptedException e) {
if (!mRun) {
Log.w(TAG, "interrupted: quitting.");
return;
}
}
}
mGameState.onExit(mPowerSlider, mAngleSlider);
Log.w(TAG, "transitioning from " +
mGameState.toString() + " to " +
next.toString());
mGameState = next;
}
}
}
/**
* Dump game state to the provided Bundle. Typically called when the
* Activity is being suspended.
*
* @return Bundle with this view's state
*/
public Bundle saveState(Bundle map) {
synchronized (mSurfaceHolder) {
mModel.saveState(map);
}
return map;
}
/**
* Restores game state from the indicated Bundle. Typically called
* when the Activity is being restored after having been previously
* destroyed.
*
* @param savedState Bundle containing the game state
*/
public synchronized void restoreState(Bundle map) {
synchronized (mSurfaceHolder) {
mModel.restoreState(map);
mPaused = false;
}
}
/** Called from GUI thread when the user presses a button.
*/
public void onButton(GameState.GameButton b) {
synchronized (mUserInputSem) {
if (mGameState.onButton(b))
mUserInputSem.notify();
}
}
/** Called (from the GUI thread) when the user moves a slider
*/
public void onSliderChange(boolean isPowerSlider, int val) {
synchronized (mUserInputSem) {
if (mGameState.onSlider(mModel, isPowerSlider, val))
mUserInputSem.notify();
}
}
/** Handles a touchscreen event */
public boolean onTouchEvent(MotionEvent me) {
synchronized (mUserInputSem) {
if (mGameState.onTouchEvent(me))
mUserInputSem.notify();
}
return true;
}
}
/** The thread that draws the animation */
private ScorchedThread mThread;
private Object mSurfaceHasBeenCreatedSem = new Object();
/** True only once the Surface has been created and is ready to
* be used */
private boolean mSurfaceHasBeenCreated = false;
/** Pointer to the model */
public Model mModel = null;
SalvoSlider.Listener mPowerAdaptor;
SalvoSlider.Listener mAngleAdaptor;
/** Fetches the animation thread for this GameControlView. */
public ScorchedThread getThread() {
return mThread;
}
/** Pan the game board */
@Override
public boolean onTouchEvent(MotionEvent me) {
return mThread.onTouchEvent(me);
}
/**
* Standard window-focus override. Notice focus lost so we can pause on
* focus lost. e.g. user switches to take a call.
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
//if (!hasWindowFocus)
//mThread.pause();
}
/** Callback invoked when the surface dimensions change. */
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
mThread.setSurfaceSize(width, height);
}
/** Callback invoked when the Surface has been created and is
* ready to be used. */
public void surfaceCreated(SurfaceHolder holder) {
synchronized (mSurfaceHasBeenCreatedSem) {
// Wake up mThread.run() if it's waiting for the surface to have
// ben created
mSurfaceHasBeenCreated = true;
mSurfaceHasBeenCreatedSem.notify();
}
Log.w(TAG, "surfaceCreated(): set mSurfaceHasBeenCreated");
}
/** Callback invoked when the Surface has been destroyed and must
* no longer be touched.
* WARNING: after this method returns, the Surface/Canvas must
* never be touched again! */
public void surfaceDestroyed(SurfaceHolder holder) {
// we have to tell thread to shut down & wait for it to finish,
// or else it might touch the Surface after we return and explode
mThread.suicide();
while (true) {
try {
mThread.join();
break;
}
catch (InterruptedException e) {
}
}
}
public GameControlView(Context context, AttributeSet attrs) {
super(context, attrs);
// Try to get hardware acceleration
try {
getHolder().setType(
android.view.SurfaceHolder.SURFACE_TYPE_HARDWARE);
Log.w(TAG, "GameControlView: activated hardware acceleration");
}
catch(Exception e2) {
getHolder().setType(
android.view.SurfaceHolder.SURFACE_TYPE_NORMAL);
Log.w(TAG, "GameControlView: no acceleration");
}
}
public void initialize(Model model,
SalvoSlider powerSlider, SalvoSlider angleSlider)
{
mModel = model;
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// Create game controller thread
mThread = new ScorchedThread(holder, getContext(),
new Handler() {
@Override
public void handleMessage(Message m) {
//mStatusText.setVisibility(m.getData().getInt("viz"));
//mStatusText.setText(m.getData().getString("text"));
}
},
powerSlider,
angleSlider);
mPowerAdaptor = new SalvoSlider.Listener() {
public void onPositionChange(int val) {
mThread.onSliderChange(true, val);
}
};
mAngleAdaptor = new SalvoSlider.Listener() {
public void onPositionChange(int val) {
mThread.onSliderChange(false, val);
}
};
setFocusable(false); // make sure we get key events
// Start the animation thread
mThread.start();
}
}
|
package io.gresse.hugo.anecdote;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemSelected;
import io.gresse.hugo.anecdote.about.AboutFragment;
import io.gresse.hugo.anecdote.anecdote.ToolbarSpinnerAdapter;
import io.gresse.hugo.anecdote.anecdote.UpdateAnecdoteFragmentEvent;
import io.gresse.hugo.anecdote.anecdote.WebsiteDialogFragment;
import io.gresse.hugo.anecdote.anecdote.fullscreen.ChangeFullscreenEvent;
import io.gresse.hugo.anecdote.anecdote.like.FavoritesRepository;
import io.gresse.hugo.anecdote.anecdote.list.AnecdoteFragment;
import io.gresse.hugo.anecdote.anecdote.service.AnecdoteService;
import io.gresse.hugo.anecdote.api.WebsiteApiService;
import io.gresse.hugo.anecdote.api.chooser.WebsiteChooserFragment;
import io.gresse.hugo.anecdote.api.event.LoadRemoteWebsiteEvent;
import io.gresse.hugo.anecdote.api.event.OnRemoteWebsiteResponseEvent;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.api.model.WebsitePage;
import io.gresse.hugo.anecdote.event.ChangeTitleEvent;
import io.gresse.hugo.anecdote.event.DisplaySnackbarEvent;
import io.gresse.hugo.anecdote.event.NetworkConnectivityChangeEvent;
import io.gresse.hugo.anecdote.event.RequestFailedEvent;
import io.gresse.hugo.anecdote.event.ResetAppEvent;
import io.gresse.hugo.anecdote.event.WebsitesChangeEvent;
import io.gresse.hugo.anecdote.setting.SettingsFragment;
import io.gresse.hugo.anecdote.storage.SpStorage;
import io.gresse.hugo.anecdote.tracking.EventTracker;
import io.gresse.hugo.anecdote.util.FragmentStackManager;
import io.gresse.hugo.anecdote.util.NetworkConnectivityListener;
import toothpick.Scope;
import toothpick.Toothpick;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, NetworkConnectivityListener.ConnectivityListener {
private static final String TAG = MainActivity.class.getSimpleName();
@BindView(R.id.coordinatorLayout)
public CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.app_bar_layout)
public AppBarLayout mAppBarLayout;
@BindView(R.id.toolbar)
public Toolbar mToolbar;
@BindView(R.id.drawer_layout)
public DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view)
public NavigationView mNavigationView;
@BindView(R.id.toolbarSpinner)
public Spinner mToolbarSpinner;
@BindView(R.id.fragment_container)
public View mFragmentContainer;
@Inject
protected ServiceProvider mServiceProvider;
protected NetworkConnectivityListener mNetworkConnectivityListener;
protected List<Website> mWebsites;
protected Snackbar mSnackbar;
protected ToolbarSpinnerAdapter mToolbarSpinnerAdapter;
protected int mToolbarScrollFlags;
protected CoordinatorLayout.Behavior mFragmentLayoutBehavior;
protected FragmentStackManager mFragmentStackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
Scope scope = Toothpick.openScopes(getApplication(), this);
super.onCreate(savedInstanceState);
Toothpick.inject(this, scope);
if (EventTracker.isEventEnable()) {
new EventTracker(this);
}
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
// Process migration before getting anything else from shared preferences
boolean openWebsiteChooserAddMode = SpStorage.migrate(this);
mWebsites = SpStorage.getWebsites(this);
mServiceProvider.createAnecdoteService(this, mWebsites);
mServiceProvider.register(EventBus.getDefault());
populateNavigationView(false);
mNetworkConnectivityListener = new NetworkConnectivityListener();
mNetworkConnectivityListener.startListening(this, this);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
mToolbarScrollFlags = params.getScrollFlags();
mFragmentStackManager = new FragmentStackManager(mSnackbar);
if (openWebsiteChooserAddMode) {
changeFragment(WebsiteChooserFragment.newInstance(WebsiteChooserFragment.BUNDLE_MODE_ADD), false, false);
} else if (SpStorage.isFirstLaunch(this) || mWebsites.isEmpty()) {
changeFragment(Fragment.instantiate(this, WebsiteChooserFragment.class.getName()), false, false);
} else {
changeAnecdoteFragment(mWebsites.get(0), mWebsites.get(0).pages.get(0));
}
mToolbarSpinnerAdapter = new ToolbarSpinnerAdapter(getApplicationContext(), "test", new ArrayList<String>());
mToolbarSpinner.setAdapter(mToolbarSpinnerAdapter);
}
@Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
EventBus.getDefault().post(new LoadRemoteWebsiteEvent());
}
@Override
public void onPause() {
super.onPause();
EventBus.getDefault().unregister(this);
}
@Override
protected void onStart() {
super.onStart();
EventTracker.onStart(this);
}
@Override
protected void onStop() {
super.onStop();
EventTracker.onStop();
}
@Override
protected void onDestroy() {
Toothpick.closeScope(this);
mServiceProvider.unregister(EventBus.getDefault());
mNetworkConnectivityListener.stopListening();
super.onDestroy();
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
int fragmentCount = getSupportFragmentManager().getBackStackEntryCount();
if (fragmentCount == 1) {
finish();
return;
}
super.onBackPressed();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
changeFragment(
Fragment.instantiate(this, AboutFragment.class.getName()),
true,
true);
return true;
case R.id.action_settings:
changeFragment(
Fragment.instantiate(this, SettingsFragment.class.getName()),
true,
true);
return true;
case R.id.action_feedback:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "hugo.gresse@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " feedback");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getGroupId()) {
case R.id.drawer_group_content:
for (Website website : mWebsites) {
if (website.name.equals(item.getTitle())) {
goToWebsite(website);
break;
}
}
break;
case R.id.drawer_group_favorites:
goToWebsite(FavoritesRepository.getFavoritesWebsite(this));
break;
case R.id.drawer_group_action:
changeFragment(
WebsiteChooserFragment.newInstance(WebsiteChooserFragment.BUNDLE_MODE_ADD),
true,
true);
break;
default:
Toast.makeText(this, "NavigationGroup not managed", Toast.LENGTH_SHORT).show();
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@OnItemSelected(R.id.toolbarSpinner)
public void onSpinnerSelected(AppCompatSpinner adapter, View v, int i, long lng) {
if (mToolbarSpinnerAdapter.getWebsite() != null) {
changeAnecdoteFragment(mToolbarSpinnerAdapter.getWebsite(), mToolbarSpinnerAdapter.getWebsite().pages.get(i));
}
}
private void goToWebsite(Website website){
changeAnecdoteFragment(website, website.pages.get(0));
// We redisplay the toolbar if it was scrollUp by removing the scrollFlags,
// wait a litle and reset the last scrollFlags on it (doing it right after was not working
final AppBarLayout.LayoutParams layoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
final int scrollFlags = layoutParams.getScrollFlags();
layoutParams.setScrollFlags(0);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
layoutParams.setScrollFlags(scrollFlags);
mToolbar.setLayoutParams(layoutParams);
}
}, 100);
}
/**
* Change tu current displayed fragment by a new one.
*
* @param frag the new fragment to display
* @param saveInBackstack if we want the fragment to be in backstack
* @param animate if we want a nice animation or not
*/
private void changeFragment(Fragment frag, boolean saveInBackstack, boolean animate) {
changeFragment(frag, saveInBackstack, animate, null, null);
}
/**
* Change tu current displayed fragment by a new one.
*
* @param frag the new fragment to display
* @param saveInBackstack if we want the fragment to be in backstack
* @param animate if we want a nice animation or not
* @param sharedView the shared view for the transition
* @param sharedName the shared name of the transition
*/
private void changeFragment(Fragment frag,
boolean saveInBackstack,
boolean animate,
@Nullable View sharedView,
@Nullable String sharedName) {
mFragmentStackManager.changeFragment(
this,
frag,
saveInBackstack,
animate,
sharedView,
sharedName);
}
/**
* Change the current fragment to a new one displaying given website spec
*
* @param website the website specification to be displayed in the fragment
*/
private void changeAnecdoteFragment(Website website, WebsitePage websitePage) {
changeFragment(AnecdoteFragment.newInstance(website, websitePage), true, false);
}
private void resetAnecdoteServices() {
mWebsites = SpStorage.getWebsites(this);
mServiceProvider.unregister(EventBus.getDefault());
mServiceProvider.createAnecdoteService(this, mWebsites);
mServiceProvider.register(EventBus.getDefault());
if (!mWebsites.isEmpty()) {
changeAnecdoteFragment(mWebsites.get(0), mWebsites.get(0).pages.get(0));
} else {
changeFragment(Fragment.instantiate(this, WebsiteChooserFragment.class.getName()), false, false);
}
}
private void populateNavigationView(boolean addNewNotification) {
// Setup NavigationView
final Menu navigationViewMenu = mNavigationView.getMenu();
navigationViewMenu.clear();
for (final Website website : mWebsites) {
final ImageButton imageButton = (ImageButton) navigationViewMenu
.add(R.id.drawer_group_content, Menu.NONE, Menu.NONE, website.name)
.setActionView(R.layout.navigationview_actionlayout)
.getActionView();
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, imageButton);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.website_popup, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
// Remove edit button for remote website
if (!website.isEditable()) {
Toast.makeText(
MainActivity.this,
R.string.action_website_noteditable_toast,
Toast.LENGTH_SHORT)
.show();
return false;
}
openWebsiteDialog(website);
break;
case R.id.action_delete:
SpStorage.deleteWebsite(MainActivity.this, website);
EventBus.getDefault().post(new WebsitesChangeEvent());
EventTracker.trackWebsiteDelete(website.name);
break;
case R.id.action_default:
SpStorage.setDefaultWebsite(MainActivity.this, website);
EventBus.getDefault().post(new WebsitesChangeEvent());
EventTracker.trackWebsiteDefault(website.name);
break;
default:
Toast.makeText(
MainActivity.this,
R.string.not_implemented,
Toast.LENGTH_SHORT)
.show();
break;
}
return true;
}
});
popup.show();
}
});
}
navigationViewMenu.add(R.id.drawer_group_favorites, Menu.NONE, Menu.NONE, R.string.action_favoris)
.setIcon(R.drawable.ic_favorite_white_24dp);
navigationViewMenu.setGroupCheckable(R.id.drawer_group_favorites, true, true);
navigationViewMenu.add(R.id.drawer_group_action, Menu.NONE, Menu.NONE, R.string.action_website_add)
.setIcon(R.drawable.ic_add_white_24dp);
if (addNewNotification) {
navigationViewMenu
.add(R.id.drawer_group_action, Menu.NONE, Menu.NONE, R.string.action_website_newwebsite)
.setIcon(R.drawable.ic_info_outline_white_24dp);
}
navigationViewMenu.setGroupCheckable(R.id.drawer_group_content, true, true);
navigationViewMenu.getItem(0).setChecked(true);
}
/**
* Open a dialog to edit given website or create a new one. One save/add, will fire {@link WebsitesChangeEvent}
*
* @param website website to edit
*/
private void openWebsiteDialog(@Nullable Website website) {
if (website == null) {
EventTracker.trackWebsiteEdit("", false);
} else {
EventTracker.trackWebsiteEdit(website.name, false);
}
FragmentManager fm = getSupportFragmentManager();
DialogFragment dialogFragment = WebsiteDialogFragment.newInstance(website);
dialogFragment.show(fm, dialogFragment.getClass().getSimpleName());
}
/**
* Get the anecdote Service corresponding to the given name
*
* @param websitePageSlug the website page slug to get the service from
* @return an anecdote Service, if one is find
*/
@Nullable
public AnecdoteService getAnecdoteService(String websitePageSlug) {
return mServiceProvider.getAnecdoteService(websitePageSlug);
}
public WebsiteApiService getWebsiteApiService() {
return mServiceProvider.getWebsiteApiService();
}
@Subscribe
public void onRequestFailed(final RequestFailedEvent event) {
if (Configuration.DEBUG) {
Log.d(TAG, "RequestFailed: " + event.toString());
}
//noinspection WrongConstant
mSnackbar = Snackbar
.make(mCoordinatorLayout, event.formatErrorMessage(this), Snackbar.LENGTH_INDEFINITE);
mSnackbar
.setAction(getString(R.string.action_retry), new View.OnClickListener() {
@Override
public void onClick(View v) {
mSnackbar = null;
EventBus.getDefault().post(event.originalEvent);
}
})
.show();
}
@Subscribe
public void changeTitle(ChangeTitleEvent event) {
if(event.spinnerEnable) {
AnecdoteService anecdoteService = getAnecdoteService(event.additionalTitle);
if (anecdoteService != null) {
int selectedItem = mToolbarSpinnerAdapter.populate(anecdoteService.getWebsite(), event.additionalTitle);
mToolbarSpinnerAdapter.notifyDataSetChanged();
mToolbarSpinner.setSelection(selectedItem);
}
/*
* When the current toolbar is not displaying an AnecdoteFragment and that we want to display an
* AnecdoteFragment now, we need to set back the scrollflags.
*/
if (mToolbarSpinner.getVisibility() != View.VISIBLE) {
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
params.setScrollFlags(mToolbarScrollFlags);
}
if(anecdoteService != null && anecdoteService.getWebsite().pages.size() > 1){
mToolbar.setTitle("");
mToolbarSpinner.setVisibility(View.VISIBLE);
} else {
mToolbar.setTitle(event.title);
mToolbarSpinner.setVisibility(View.GONE);
}
} else {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
mToolbarSpinner.setVisibility(View.GONE);
mToolbar.setTitle(event.title);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
params.setScrollFlags(0);
}
Menu menu = mNavigationView.getMenu();
for (int i = 0; i < mNavigationView.getMenu().size(); i++) {
if (menu.getItem(i).getTitle().equals(event.title)) {
mNavigationView.getMenu().getItem(i).setChecked(true);
} else {
mNavigationView.getMenu().getItem(i).setChecked(false);
}
}
}
@Subscribe
public void onWebsitesChangeEvent(WebsitesChangeEvent event) {
if (event.fromWebsiteChooserOverride) {
Log.d(TAG, "onWebsitesChangeEvent: removing all fragments");
// if we come after a restoration or at the first start
// 1. remove all already added fragment
FragmentManager fm = getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
// 2. remove the WebsiteChooserFragment
Fragment fragment = fm.findFragmentByTag(WebsiteChooserFragment.class.getName());
if (fragment != null) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.remove(fragment).commit();
}
}
resetAnecdoteServices();
populateNavigationView(false);
EventBus.getDefault().post(new UpdateAnecdoteFragmentEvent());
}
@Subscribe
public void changeFullscreenVisibilityEvent(ChangeFullscreenEvent event) {
if (event.toFullscreen && getSupportActionBar() != null) {
getSupportActionBar().hide();
// mAppBarLayout.animate().translationY(-mAppBarLayout.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
} else if (getSupportActionBar() != null) {
getSupportActionBar().show();
// mAppBarLayout.animate().translationY(0).setInterpolator(new AccelerateInterpolator()).start();
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mAppBarLayout.getParent().requestLayout();
}
}, 600);
if (event.toFullscreen) {
// Hide status bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Remove the layout behavior on fragment container to prevent issue with the fullscreen
CoordinatorLayout.LayoutParams fragmentContainerLayoutParams =
(CoordinatorLayout.LayoutParams) mFragmentContainer.getLayoutParams();
mFragmentLayoutBehavior = fragmentContainerLayoutParams.getBehavior();
fragmentContainerLayoutParams.setBehavior(null);
} else {
// Show status bar
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Set back the layout behavior on fragment container
((CoordinatorLayout.LayoutParams) mFragmentContainer.getLayoutParams())
.setBehavior(new AppBarLayout.ScrollingViewBehavior());
}
}
@Subscribe
public void onRemoteWebsiteLoaded(OnRemoteWebsiteResponseEvent event) {
if (!event.isSuccessful) return;
if (mWebsites == null || mWebsites.isEmpty()) return;
/*
* Check remote website and local to update local configuration if needed
*/
Website tempWebsite;
List<Website> newWebsiteList = new ArrayList<>();
boolean dataModified = false;
for (Website website : mWebsites) {
int index = event.websiteList.lastIndexOf(website);
// This remote website has not been found locally, skip it
if (index == -1) {
continue;
}
tempWebsite = event.websiteList.get(index);
if (!website.isUpToDate(tempWebsite)) {
dataModified = true;
newWebsiteList.add(tempWebsite);
} else {
newWebsiteList.add(website);
}
}
boolean newNotification = false;
int savedWebsiteNumber = SpStorage.getSavedRemoteWebsiteNumber(this);
if (savedWebsiteNumber < event.websiteList.size()) {
// Display new website notification
newNotification = true;
SpStorage.setSavedRemoteWebsiteNumber(this, event.websiteList.size());
} else if (event.websiteList.size() < savedWebsiteNumber) {
SpStorage.setSavedRemoteWebsiteNumber(this, event.websiteList.size());
}
if (dataModified) {
Log.i(TAG, "Updating websites configuration");
mWebsites = newWebsiteList;
SpStorage.saveWebsites(this, mWebsites);
resetAnecdoteServices();
populateNavigationView(newNotification);
EventBus.getDefault().post(new UpdateAnecdoteFragmentEvent());
} else if (newNotification) {
populateNavigationView(true);
}
}
@Subscribe
public void onWebsiteReset(ResetAppEvent event) {
changeFragment(
WebsiteChooserFragment.newInstance(WebsiteChooserFragment.BUNDLE_MODE_RESTORE),
true,
true);
}
@Subscribe
public void onDisplaySnackbarEvent(final DisplaySnackbarEvent event) {
if (mSnackbar != null && mSnackbar.isShownOrQueued()) {
mSnackbar.dismiss();
}
mSnackbar = Snackbar.make(mCoordinatorLayout, event.toastMessage, Snackbar.LENGTH_INDEFINITE);
mSnackbar
.setAction(event.actionString, new View.OnClickListener() {
@Override
public void onClick(View v) {
mSnackbar = null;
MainActivity.this.startActivity(event.intentToRun);
}
})
.setDuration(event.duration)
.show();
}
@Override
public void onConnectivityChange(NetworkConnectivityListener.State state) {
Log.d(TAG, "onConnectivityChange: " + state);
EventBus.getDefault().post(new NetworkConnectivityChangeEvent(state));
if (state == NetworkConnectivityListener.State.CONNECTED && mSnackbar != null && mSnackbar.isShownOrQueued()) {
mSnackbar.dismiss();
}
}
}
|
package se.cygni.snake.start;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
@RestController
public class StartController {
@RequestMapping("/")
public void index(HttpServletResponse response) throws Exception {
response.sendRedirect("http://game.snake.cygni.se");
}
@RequestMapping("/mtd2017")
public void mtd2017(HttpServletResponse response) throws Exception {
response.sendRedirect("https://docs.google.com/a/cygni.se/forms/d/e/1FAIpQLSe0tZDPLPGvj05wiC57LzieVOv3Y_s26fHtJ6S0KVViLbpUBw/viewform");
}
}
|
package victory.sandbox.mytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MyActivity extends Activity {
Button clickToList;
ListView myListView;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
private int swipeNumber;
private class SwipeItemTouchListener extends SwipeDetector {
private long minTime = 0;
private int debounceLength = 500;
private SwipeDetector.Action lastAction = Action.None;
private boolean isBounce () {
long toc = System.currentTimeMillis();
boolean result;
if (toc < minTime) { // too soon
result = true;
} else {
minTime = toc + debounceLength;
result = false;
}
return result;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
super.onTouch(view, event);
if (isLeftToRight() && !isBounce()) {
if (lastAction.equals(Action.None)) {
swipeNumber += 1;
}
}
lastAction = swipeHorizontal;
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
clickToList = (Button) findViewById(R.id.clickToList);
myListView = (ListView) findViewById(R.id.listView);
myListView.setOnTouchListener(new SwipeItemTouchListener());
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(
getApplicationContext(),
R.layout.list_layout,
R.id.listTextView,
arrayList);
myListView.setAdapter(adapter);
clickToList.setOnClickListener(new View.OnClickListener() {
private Integer counter = 0;
private int maxClicks = 50;
@Override
public void onClick(View v) {
if (counter >= maxClicks) {
return;
}
arrayList.add("Row: " + counter.toString() + " Swipe Number: " + swipeNumber);
counter += 1;
adapter.notifyDataSetChanged();
myListView.setBackgroundColor(
getResources().getColor(android.R.color.background_dark));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
return (id == R.id.action_settings) || (super.onOptionsItemSelected(item));
}
}
|
package org.togglz.console;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.togglz.core.manager.FeatureManager;
public class RequestEvent {
private final ServletContext context;
private final HttpServletRequest request;
private final HttpServletResponse response;
private final String path;
private final FeatureManager featureManager;
public RequestEvent(FeatureManager featureManager, ServletContext context, HttpServletRequest request,
HttpServletResponse response) {
this.featureManager = featureManager;
this.context = context;
this.request = request;
this.response = response;
// /contextPath/togglz/index -> /index
String prefix = request.getContextPath() + request.getServletPath();
path = request.getRequestURI()
.substring(prefix.length())
.replaceAll("(?i);jsessionid=[\\w\\.\\-]+", "");
}
public ServletContext getContext() {
return context;
}
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public String getPath() {
return path;
}
public FeatureManager getFeatureManager() {
return featureManager;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.