answer
stringlengths 17
10.2M
|
|---|
package com.github.davidcarboni.thetrain;
import com.github.davidcarboni.cryptolite.Random;
import com.github.davidcarboni.httpino.Endpoint;
import com.github.davidcarboni.httpino.Host;
import com.github.davidcarboni.httpino.Http;
import com.github.davidcarboni.httpino.Response;
import com.github.davidcarboni.restolino.json.Serialiser;
import com.github.davidcarboni.thetrain.helpers.PathUtils;
import com.github.davidcarboni.thetrain.json.Result;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
/**
* Example publishing client implementation.
*/
public class Client {
public static void main(String[] args) throws IOException {
Host host = new Host("http://localhost:8080");
Path generated = Generator.generate();
System.out.println("Generated content in: " + generated);
try (Http http = new Http()) {
String encryptionPassword = Random.password(8);
// Set up a transaction
Endpoint begin = new Endpoint(host, "begin").setParameter("encryptionPassword", encryptionPassword);
Response<Result> beginResponse = http.post(begin, Result.class);
check(beginResponse);
String transactionId = beginResponse.body.transaction.id();
// Publish some content
Endpoint publish = new Endpoint(host, "publish").setParameter("transactionId", transactionId).setParameter("encryptionPassword", encryptionPassword);
List<String> uris = PathUtils.listUris(generated);
for (String uri : uris) {
Path path = PathUtils.toPath(uri, generated);
Endpoint endpoint = publish.setParameter("uri", uri);
Response<Result> resultResponse = http.postFile(endpoint, path, Result.class);
check(resultResponse);
}
// Commit the transaction
Endpoint commit = new Endpoint(host, "commit").setParameter("transactionId", transactionId).setParameter("encryptionPassword", encryptionPassword);
Response<Result> commitResponse = http.post(commit, null, Result.class);
check(commitResponse);
Endpoint transaction = new Endpoint(host, "transaction").setParameter("transactionId", transactionId).setParameter("encryptionPassword", encryptionPassword);
Response<Result> transactionResponse = http.getJson(transaction, Result.class);
check(transactionResponse);
Serialiser.getBuilder().setPrettyPrinting();
System.out.println(Serialiser.serialise(transactionResponse.body));
// int i = 0;
// for (UriInfo uriInfo : transactionResponse.body.transaction.uris()) {
// System.out.println(uriInfo.uri());
// System.out.println(uriInfo.sha());
// System.out.println(uriInfo.action());
// System.out.println(uriInfo.status());
// System.out.println();
// System.out.println("Total: " + i);
}
}
static void check(Response<Result> response) {
if (response.statusLine.getStatusCode() != 200) {
throw new RuntimeException(response.statusLine + " : " + Serialiser.serialise(response.body));
} else if (response.body.transaction.hasErrors()) {
throw new RuntimeException(Serialiser.serialise(response.body.transaction));
}
System.out.println(response.body.message);
}
}
|
package com.google.sps.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.api.mockito.PowerMockito;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.github.mustachejava.DefaultMustacheFactory;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ResultsServlet.class, DefaultMustacheFactory.class})
public final class ResultsServletTest {
private final static ResultsServlet RESULTS_SERVLET = new ResultsServlet();
@Before
public void setUpMustacheFactoryMock() throws Exception {
DefaultMustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("results.test");
DefaultMustacheFactory mfMocked = PowerMockito.mock(DefaultMustacheFactory.class);
PowerMockito.when(mfMocked.compile("results.html")).thenReturn(mustache);
PowerMockito.whenNew(DefaultMustacheFactory.class).withAnyArguments().thenReturn(mfMocked);
}
private String mockServlet(String keyValue) throws IOException {
HttpServletRequest mockedRequest = PowerMockito.mock(HttpServletRequest.class);
HttpServletResponse mockedResponse = PowerMockito.mock(HttpServletResponse.class);
PowerMockito.when(mockedRequest.getParameter("k")).thenReturn(keyValue);
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
PowerMockito.when(mockedResponse.getWriter()).thenReturn(writer);
RESULTS_SERVLET.doGet(mockedRequest, mockedResponse);
Mockito.verify(mockedRequest, Mockito.atLeast(1)).getParameter("k");
writer.flush();
return stringWriter.toString();
}
@Test
public void testServlet() throws IOException {
String expected = "value";
String actual = mockServlet(expected);
Assert.assertTrue(actual.contains(expected));
}
@Test
public void testNonAsciiCharacters() throws IOException {
String expected = "मान";
String actual = mockServlet(expected);
Assert.assertTrue(actual.contains(expected));
}
}
|
package com.mapswithme.maps.downloader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.mapswithme.maps.MWMActivity;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
class DownloadChunkTask extends AsyncTask<Void, byte [], Void>
{
private static final String TAG = "DownloadChunkTask";
private long m_httpCallbackID;
private String m_url;
private long m_beg;
private long m_end;
private long m_expectedFileSize;
private String m_postBody;
private final int NOT_SET = -1;
private final int IO_ERROR = -2;
private final int INVALID_URL = -3;
private int m_httpErrorCode = NOT_SET;
private long m_downloadedBytes = 0;
private WakeLock m_wakeLock = null;
native void onWrite(long httpCallbackID, long beg, byte [] data, long size);
native void onFinish(long httpCallbackID, long httpCode, long beg, long end);
public DownloadChunkTask(long httpCallbackID, String url, long beg, long end, long expectedFileSize, String postBody)
{
m_httpCallbackID = httpCallbackID;
m_url = url;
m_beg = beg;
m_end = end;
m_expectedFileSize = expectedFileSize;
m_postBody = postBody;
}
@Override
protected void onPreExecute()
{
PowerManager pm = (PowerManager)MWMActivity.getCurrentContext().getSystemService(
android.content.Context.POWER_SERVICE);
m_wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
m_wakeLock.acquire();
}
@Override
protected void onPostExecute(Void resCode)
{
onFinish(m_httpCallbackID, 200, m_beg, m_end);
m_wakeLock.release();
}
@Override
protected void onCancelled()
{
// Report error in callback only if we're not forcibly canceled
if (m_httpErrorCode != NOT_SET)
onFinish(m_httpCallbackID, m_httpErrorCode, m_beg, m_end);
m_wakeLock.release();
}
@Override
protected void onProgressUpdate(byte []... data)
{
if (!isCancelled())
{
// Use progress event to save downloaded bytes
onWrite(m_httpCallbackID, m_beg + m_downloadedBytes, data[0], (long)data[0].length);
m_downloadedBytes += data[0].length;
}
}
void start()
{
execute();
}
@Override
protected Void doInBackground(Void... p)
{
URL url;
try
{
url = new URL(m_url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (isCancelled())
{
urlConnection.disconnect();
return null;
}
urlConnection.setChunkedStreamingMode(0);
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(15 * 1000);
urlConnection.setReadTimeout(15 * 1000);
// use Range header only if we don't download whole file from start
if (!(m_beg == 0 && m_end < 0))
{
if (m_end > 0)
urlConnection.setRequestProperty("Range", String.format("bytes=%d-%d", m_beg, m_end));
else
urlConnection.setRequestProperty("Range", String.format("bytes=%d-", m_beg));
}
if (m_postBody.length() != 0)
{
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
final DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream());
os.writeChars(m_postBody);
}
if (isCancelled())
{
urlConnection.disconnect();
return null;
}
final int err = urlConnection.getResponseCode();
if (err != HttpURLConnection.HTTP_OK && err != HttpURLConnection.HTTP_PARTIAL)
{
// we've set error code so client should be notified about the error
m_httpErrorCode = err;
cancel(false);
urlConnection.disconnect();
return null;
}
final InputStream is = urlConnection.getInputStream();
byte [] tempBuf = new byte[1024 * 64];
long readBytes;
while ((readBytes = is.read(tempBuf)) != -1)
{
if (isCancelled())
{
urlConnection.disconnect();
return null;
}
byte [] chunk = new byte[(int)readBytes];
System.arraycopy(tempBuf, 0, chunk, 0, (int)readBytes);
publishProgress(chunk);
}
}
catch (MalformedURLException ex)
{
Log.d(TAG, "invalid url: " + m_url);
// Notify the client about error
m_httpErrorCode = INVALID_URL;
cancel(false);
}
catch (IOException ex)
{
Log.d(TAG, "ioexception: " + ex.toString());
// Notify the client about error
m_httpErrorCode = IO_ERROR;
cancel(false);
}
return null;
}
}
|
package com.ioworks.noqueue.impl;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ioworks.noqueue.FatPipe;
import com.ioworks.noqueue.FatPipe.Producer;
import com.ioworks.noqueue.ProducerSet;
import com.ioworks.noqueue.ProducerSets;
import com.ioworks.noqueue.Receptor;
public class MapReduceTests {
static Logger logger = LoggerFactory.getLogger(MapReduceTests.class);
int threads = 4;
int poolSize = 3;
int iterations = 20_000;
WordCount[] tasks;
ReducedConsumer consumer;
@Before
public void initialize() {
ProducerSets.factory = ProducerSetFactoryImpl.class;
// prepare work to do
WordCount task1 = new WordCount();
task1.put("Hello", 1);
task1.put("World", 1);
task1.put("Apache", 1);
WordCount task2 = new WordCount();
task2.put("The", 1);
task2.put("Whole", 1);
task2.put("World", 1);
tasks = new WordCount[] { task1, task2 };
// consumer will receive the work output
consumer = new ReducedConsumer();
}
@Test
public void multiThreadPerformanceTestWith1Thread() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 1;
multiThreadPerformanceTestImpl();
}
@Test
public void pooledFatPipePerformanceTestWith1Thread() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 1;
pooledFatPipePerformanceTestImpl();
}
@Test
public void multiThreadPerformanceTestWith2Threads() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 2;
multiThreadPerformanceTestImpl();
}
@Test
public void pooledFatPipePerformanceTestWith2Threads() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 2;
pooledFatPipePerformanceTestImpl();
}
@Test
public void multiThreadPerformanceTestWith4Threads() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 4;
multiThreadPerformanceTestImpl();
}
@Test
public void pooledFatPipePerformanceTestWith4Threads() throws InterruptedException, InstantiationException, IllegalAccessException {
poolSize = 4;
pooledFatPipePerformanceTestImpl();
}
protected void pooledFatPipePerformanceTestImpl() throws InterruptedException, InstantiationException, IllegalAccessException {
// initialize producer set
ProducerSet<String, WordCount, WordCount> set = ProducerSets.newProducerSet(new FatMapReducerGenerator(), 1, 0, null);
set.addConsumer(consumer, null, 0);
ExecutorService producers = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
producers.submit(() -> {
Receptor<WordCount> receptor = set.get("reducer A");
for (int r = 0; r < iterations; r++) {
// send a task to work on to the receptor
WordCount task = new WordCount(tasks[r % tasks.length], System.nanoTime());
receptor.lazySet(task);
Thread.sleep(1);
}
return null;
});
}
producers.shutdown();
producers.awaitTermination(10, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(5);
set.shutdown();
logger.info(String.format("fp(%d) throughput: %.0f, EMA Latency (uS): %.2f", poolSize, consumer.throughput(), consumer.latencyEMA / 1e3));
}
protected void multiThreadPerformanceTestImpl() throws InterruptedException, InstantiationException, IllegalAccessException {
// setup single-threaded work queue
ArrayBlockingQueue<WordCount> workQueue = new ArrayBlockingQueue<>(1024);
ArrayBlockingQueue<WordCount> outputQueue = new ArrayBlockingQueue<>(1024);
// setup a 'poolSize' daemon threads to do the work
ThreadGroup workerGroup = new ThreadGroup("workers");
for (int p = 0; p < poolSize; p++) {
Thread worker = new Thread(workerGroup, () -> {
FatMapReducer reducer = new FatMapReducer();
try {
while (true) {
WordCount task = workQueue.poll(1, TimeUnit.SECONDS);
if (task == null)
continue;
WordCount output = reducer.execute(task, null, null);
outputQueue.add(output);
}
} catch (InterruptedException e) {
logger.trace("Interrupted", e);
}
});
worker.setDaemon(true);
worker.start();
}
// setup a daemon consumer thread
Thread consumerThread = new Thread(workerGroup, () -> {
try {
while (true) {
WordCount output = outputQueue.poll(1, TimeUnit.SECONDS);
if (output == null)
continue;
consumer.consume(output, System.nanoTime());
}
} catch (InterruptedException e) {
logger.trace("Interrupted", e);
}
});
consumerThread.setDaemon(true);
consumerThread.start();
ExecutorService producers = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
producers.submit(() -> {
for (int r = 0; r < iterations; r++) {
// send a task to work on to the work queue
WordCount task = new WordCount(tasks[r % tasks.length], System.nanoTime());
workQueue.offer(task, 1, TimeUnit.SECONDS);
Thread.sleep(1);
}
return null;
});
}
producers.shutdown();
producers.awaitTermination(10, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(5);
workerGroup.interrupt();
logger.info(String.format("multi-t(%d) throughput: %.0f, EMA Latency (uS): %.2f", poolSize, consumer.throughput(), consumer.latencyEMA / 1e3));
}
static class FatMapReducerGenerator implements ProducerSet.Generator<String, WordCount, WordCount> {
@Override
public Producer<WordCount, WordCount> generate(String key) {
return new FatMapReducer();
}
@Override
public void exceptionThrown(Exception e) {
logger.warn("FatMapReducerGenerator error", e);
}
}
static class FatMapReducer implements FatPipe.Producer<WordCount, WordCount> {
private final Integer ZERO = Integer.valueOf(0);
private WordCount runningWordCounts = new WordCount();
@Override
public WordCount execute(WordCount data, Receptor<WordCount> r, FatPipe.Signal n) {
data.forEach((word, count) -> {
int newCount = runningWordCounts.getOrDefault(word, ZERO) + count;
runningWordCounts.put(word, newCount);
});
return new WordCount(runningWordCounts, data.time);
}
@Override
public void complete(WordCount product) {
}
}
static class ReducedConsumer implements FatPipe.Consumer<WordCount> {
// start counting throughput after 10,000 invocations
static final int WARMUP_COUNT_THRESHOLD = 10_000;
int invocations = 0;
long startTime = 0;
long lastInvocationTime = 0;
long lastLogTime = 0;
double latencyEMA = Double.NaN;
@Override
public void consume(WordCount data, long time) {
++invocations;
lastInvocationTime = time;
long latency = System.nanoTime() - data.time;
if (Double.isNaN(latencyEMA)) latencyEMA = latency;
else latencyEMA = 0.99 * latencyEMA + 0.01 * latency;
if (startTime == 0 && invocations > WARMUP_COUNT_THRESHOLD) {
startTime = time;
}
if (TimeUnit.NANOSECONDS.toSeconds(time - lastLogTime) > 1) {
lastLogTime = time;
logger.info("Word count: {}", data);
}
}
/**
* Calculates the consumed throughput
*
* @return The consumed throughput in invocations per second, or
* Double.NaN if the throughput cannot be calculated.
*/
public double throughput() {
if (startTime > 0 && lastInvocationTime > startTime) {
long elapsedNanos = lastInvocationTime - startTime;
return (invocations - WARMUP_COUNT_THRESHOLD) / (elapsedNanos / 1.0e9);
} else {
return Double.NaN;
}
}
public double latencyEMA() {
return latencyEMA;
}
@Override
public boolean isConsuming() {
return true;
}
}
@SuppressWarnings("serial")
static class WordCount extends HashMap<String, Integer> {
long time;
public WordCount() {
}
public WordCount(WordCount runningWordCounts) {
super(runningWordCounts);
}
public WordCount(WordCount runningWordCounts, long time) {
super(runningWordCounts);
this.time = time;
}
}
}
|
package com.ninty.system.setting;
import android.app.Activity;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class SystemSetting extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
private String TAG = SystemSetting.class.getSimpleName();
private static final String VOL_VOICE_CALL = "call";
private static final String VOL_SYSTEM = "system";
private static final String VOL_RING = "ring";
private static final String VOL_MUSIC = "music";
private static final String VOL_ALARM = "alarm";
private static final String VOL_NOTIFICATION = "notification";
private ReactApplicationContext mContext;
private AudioManager am;
private WifiManager wm;
private LocationManager lm;
private VolumeBroadcastReceiver volumeBR;
private volatile BroadcastReceiver wifiBR;
private volatile BroadcastReceiver bluetoothBR;
private volatile BroadcastReceiver locationBR;
private volatile BroadcastReceiver airplaneBR;
private IntentFilter filter;
public SystemSetting(ReactApplicationContext reactContext) {
super(reactContext);
mContext = reactContext;
reactContext.addLifecycleEventListener(this);
am = (AudioManager) mContext.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
wm = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
lm = (LocationManager) mContext.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
volumeBR = new VolumeBroadcastReceiver();
}
private void registerVolumeReceiver() {
if (!volumeBR.isRegistered()) {
filter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
mContext.registerReceiver(volumeBR, filter);
volumeBR.setRegistered(true);
}
}
private void unregisterVolumeReceiver() {
if (volumeBR.isRegistered()) {
mContext.unregisterReceiver(volumeBR);
volumeBR.setRegistered(false);
}
}
private void listenWifiState() {
if (wifiBR == null) {
synchronized (this) {
if (wifiBR == null) {
wifiBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
if (wifiState == WifiManager.WIFI_STATE_ENABLED || wifiState == WifiManager.WIFI_STATE_DISABLED) {
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventWifiChange", wifiState == WifiManager.WIFI_STATE_ENABLED);
}
}
}
};
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mContext.registerReceiver(wifiBR, wifiFilter);
}
}
}
}
private void listenBluetoothState() {
if (bluetoothBR == null) {
synchronized (this) {
if (bluetoothBR == null) {
bluetoothBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF) {
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventBluetoothChange", state == BluetoothAdapter.STATE_ON);
}
}
}
};
IntentFilter bluetoothFilter = new IntentFilter();
bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
mContext.registerReceiver(bluetoothBR, bluetoothFilter);
}
}
}
}
private void listenLocationState() {
if (locationBR == null) {
synchronized (this) {
if (locationBR == null) {
locationBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(LocationManager.PROVIDERS_CHANGED_ACTION)) {
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventLocationChange", isLocationEnable());
}
}
};
IntentFilter locationFilter = new IntentFilter();
locationFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
mContext.registerReceiver(locationBR, locationFilter);
}
}
}
}
private void listenAirplaneState() {
if (airplaneBR == null) {
synchronized (this) {
if (airplaneBR == null) {
airplaneBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
int val = Settings.System.getInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventAirplaneChange", val == 1);
} catch (Settings.SettingNotFoundException e) {
Log.e(TAG, "err", e);
}
}
};
IntentFilter locationFilter = new IntentFilter();
locationFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
mContext.registerReceiver(airplaneBR, locationFilter);
}
}
}
}
@Override
public String getName() {
return SystemSetting.class.getSimpleName();
}
@ReactMethod
public void setScreenMode(int mode, Promise promise) {
mode = mode == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL ? mode : Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
checkAndSet(Settings.System.SCREEN_BRIGHTNESS_MODE, mode, promise);
}
@ReactMethod
public void getScreenMode(Promise promise) {
try {
int mode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
promise.resolve(mode);
} catch (Settings.SettingNotFoundException e) {
Log.e(TAG, "err", e);
promise.reject("-1", "get screen mode fail", e);
}
}
@ReactMethod
public void setBrightness(float val, Promise promise) {
final int brightness = (int) (val * 255);
checkAndSet(Settings.System.SCREEN_BRIGHTNESS, brightness, promise);
}
@ReactMethod
public void setAppBrightness(float val) {
final Activity curActivity = getCurrentActivity();
if (curActivity == null) {
return;
}
final WindowManager.LayoutParams lp = curActivity.getWindow().getAttributes();
lp.screenBrightness = val;
curActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
curActivity.getWindow().setAttributes(lp);
}
});
}
@ReactMethod
public void getAppBrightness(Promise promise) {
final Activity curActivity = getCurrentActivity();
if (curActivity == null) {
return;
}
try {
float result = curActivity.getWindow().getAttributes().screenBrightness;
if (result < 0) {
int val = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
promise.resolve(val * 1.0f / 255);
} else {
promise.resolve(result);
}
} catch (Exception e) {
Log.e(TAG, "err", e);
promise.reject("-1", "get app's brightness fail", e);
}
}
@ReactMethod
public void openWriteSetting() {
Intent intent = new Intent(SysSettings.WRITESETTINGS.action, Uri.parse("package:" + mContext.getPackageName()));
mContext.getCurrentActivity().startActivity(intent);
}
@ReactMethod
public void getBrightness(Promise promise) {
try {
int val = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
promise.resolve(val * 1.0f / 255);
} catch (Settings.SettingNotFoundException e) {
Log.e(TAG, "err", e);
promise.reject("-1", "get brightness fail", e);
}
}
@ReactMethod
public void setVolume(float val, ReadableMap config) {
unregisterVolumeReceiver();
String type = config.getString("type");
boolean playSound = config.getBoolean("playSound");
boolean showUI = config.getBoolean("showUI");
int volType = getVolType(type);
int flags = 0;
if (playSound) {
flags |= AudioManager.FLAG_PLAY_SOUND;
}
if (showUI) {
flags |= AudioManager.FLAG_SHOW_UI;
}
try {
am.setStreamVolume(volType, (int) (val * am.getStreamMaxVolume(volType)), flags);
} catch (SecurityException e) {
if (val == 0) {
Log.w(TAG, "setVolume(0) failed. See https://github.com/c19354837/react-native-system-setting/issues/48");
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
mContext.startActivity(intent);
}
}
Log.e(TAG, "err", e);
}
registerVolumeReceiver();
}
@ReactMethod
public void getVolume(String type, Promise promise) {
promise.resolve(getNormalizationVolume(type));
}
private void checkAndSet(String name, int value, Promise promise) {
boolean reject = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(mContext)) {
reject = true;
} else {
try {
Settings.System.putInt(mContext.getContentResolver(), name, value);
int newVal = Settings.System.getInt(mContext.getContentResolver(), name);
if (newVal != value) {
reject = true;
}
} catch (Settings.SettingNotFoundException e) {
Log.e(TAG, "err", e);
//ignore
} catch (SecurityException e) {
Log.e(TAG, "err", e);
reject = true;
}
}
if (reject) {
promise.reject("-1", "write_settings premission is blocked by system");
} else {
promise.resolve(true);
}
}
private float getNormalizationVolume(String type) {
int volType = getVolType(type);
return am.getStreamVolume(volType) * 1.0f / am.getStreamMaxVolume(volType);
}
private int getVolType(String type) {
switch (type) {
case VOL_VOICE_CALL:
return AudioManager.STREAM_VOICE_CALL;
case VOL_SYSTEM:
return AudioManager.STREAM_SYSTEM;
case VOL_RING:
return AudioManager.STREAM_RING;
case VOL_ALARM:
return AudioManager.STREAM_ALARM;
case VOL_NOTIFICATION:
return AudioManager.STREAM_NOTIFICATION;
default:
return AudioManager.STREAM_MUSIC;
}
}
@ReactMethod
public void isWifiEnabled(Promise promise) {
if (wm != null) {
promise.resolve(wm.isWifiEnabled());
} else {
promise.reject("-1", "get wifi manager fail");
}
}
@ReactMethod
public void switchWifiSilence() {
if (wm != null) {
listenWifiState();
wm.setWifiEnabled(!wm.isWifiEnabled());
} else {
Log.w(TAG, "Cannot get wifi manager, switchWifi will be ignored");
}
}
@ReactMethod
public void switchWifi() {
switchSetting(SysSettings.WIFI);
}
@ReactMethod
public void isLocationEnabled(Promise promise) {
if (lm != null) {
promise.resolve(isLocationEnable());
} else {
promise.reject("-1", "get location manager fail");
}
}
@ReactMethod
public void getLocationMode(Promise promise) {
if (lm != null) {
int result = 0;
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
result |= 1;
}
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
result |= 1 << 1;
}
promise.resolve(result);
} else {
promise.reject("-1", "get location manager fail");
}
}
private boolean isLocationEnable() {
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
@ReactMethod
public void switchLocation() {
switchSetting(SysSettings.LOCATION);
}
@ReactMethod
public void isBluetoothEnabled(Promise promise) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
promise.resolve(bluetoothAdapter != null && bluetoothAdapter.isEnabled());
}
@ReactMethod
public void switchBluetooth() {
switchSetting(SysSettings.BLUETOOTH);
}
@ReactMethod
public void switchBluetoothSilence() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
listenBluetoothState();
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
} else {
bluetoothAdapter.enable();
}
}
}
@ReactMethod
public void activeListener(String type, Promise promise) {
switch (type) {
case "wifi":
listenWifiState();
promise.resolve(null);
return;
case "bluetooth":
listenBluetoothState();
promise.resolve(null);
return;
case "location":
listenLocationState();
promise.resolve(null);
return;
case "airplane":
listenAirplaneState();
promise.resolve(null);
return;
}
promise.reject("-1", "unsupported listener type: " + type);
}
@ReactMethod
public void isAirplaneEnabled(Promise promise) {
try {
int val = Settings.System.getInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
promise.resolve(val == 1);
} catch (Settings.SettingNotFoundException e) {
Log.e(TAG, "err", e);
promise.reject("-1", "get airplane mode fail", e);
}
}
@ReactMethod
public void switchAirplane() {
switchSetting(SysSettings.AIRPLANE);
}
private void switchSetting(SysSettings setting) {
if (mContext.getCurrentActivity() != null) {
mContext.addActivityEventListener(this);
Intent intent = new Intent(setting.action);
mContext.getCurrentActivity().startActivityForResult(intent, setting.requestCode);
} else {
Log.w(TAG, "getCurrentActivity() return null, switch will be ignore");
}
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
SysSettings setting = SysSettings.get(requestCode);
if (setting != SysSettings.UNKNOW) {
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventEnterForeground", null);
mContext.removeActivityEventListener(this);
}
}
@Override
public void onNewIntent(Intent intent) {
}
@Override
public void onHostResume() {
registerVolumeReceiver();
}
@Override
public void onHostPause() {
unregisterVolumeReceiver();
}
@Override
public void onHostDestroy() {
if (wifiBR != null) {
mContext.unregisterReceiver(wifiBR);
wifiBR = null;
}
if (bluetoothBR != null) {
mContext.unregisterReceiver(bluetoothBR);
bluetoothBR = null;
}
if (locationBR != null) {
mContext.unregisterReceiver(locationBR);
locationBR = null;
}
if (airplaneBR != null) {
mContext.unregisterReceiver(airplaneBR);
airplaneBR = null;
}
}
private class VolumeBroadcastReceiver extends BroadcastReceiver {
private boolean isRegistered = false;
public void setRegistered(boolean registered) {
isRegistered = registered;
}
public boolean isRegistered() {
return isRegistered;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
WritableMap para = Arguments.createMap();
para.putDouble("value", getNormalizationVolume(VOL_MUSIC));
para.putDouble(VOL_VOICE_CALL, getNormalizationVolume(VOL_VOICE_CALL));
para.putDouble(VOL_SYSTEM, getNormalizationVolume(VOL_SYSTEM));
para.putDouble(VOL_RING, getNormalizationVolume(VOL_RING));
para.putDouble(VOL_MUSIC, getNormalizationVolume(VOL_MUSIC));
para.putDouble(VOL_ALARM, getNormalizationVolume(VOL_ALARM));
para.putDouble(VOL_NOTIFICATION, getNormalizationVolume(VOL_NOTIFICATION));
try {
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EventVolume", para);
} catch (RuntimeException e) {
// Possible to interact with volume before JS bundle execution is finished.
// This is here to avoid app crashing.
}
}
}
}
}
|
package com.treasure_data.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.json.simple.JSONValue;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.treasure_data.auth.TreasureDataCredentials;
import com.treasure_data.client.HttpClientAdaptor.HttpConnectionImpl;
import com.treasure_data.model.Database;
import com.treasure_data.model.ExportRequest;
import com.treasure_data.model.ExportResult;
import com.treasure_data.model.Job;
import com.treasure_data.model.Request;
import com.treasure_data.model.Table;
public class TestExportData {
@Before
public void setUp() throws Exception {
Properties props = System.getProperties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
}
@Test @Ignore
public void testExportData00() throws Exception {
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials());
HttpClientAdaptor clientAdaptor = new HttpClientAdaptor(conf);
Properties props = System.getProperties();
String bucketName = props.getProperty("td.client.export.bucket");
String accessKeyID = props.getProperty("td.client.accesskey.id");
String secretAccessKey = props.getProperty("td.client.secret.accesskey");
Database database = new Database("mugadb");
Table table = new Table(database, "mugatbl");
ExportRequest request = new ExportRequest(
table, "s3", bucketName, "json.gz", accessKeyID, secretAccessKey);
ExportResult result = clientAdaptor.exportData(request);
Job job = result.getJob();
System.out.println(job.getJobID());
}
static class HttpConnectionImplforExportData01 extends HttpConnectionImpl {
@Override
void doPostRequest(Request<?> request, String path, Map<String, String> header,
Map<String, String> params) throws IOException {
// do nothing
}
@Override
int getResponseCode() throws IOException {
return HttpURLConnection.HTTP_OK;
}
@Override
String getResponseMessage() throws IOException {
return "";
}
@Override
String getResponseBody() throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("job_id", "12345");
map.put("database", "mugadb");
String jsonData = JSONValue.toJSONString(map);
return jsonData;
}
@Override
void disconnect() {
// do nothing
}
}
/**
* check normal behavior of client
*/
@Test
public void testExportData01() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials(props));
HttpClientAdaptor clientAdaptor = new HttpClientAdaptor(conf);
clientAdaptor.setConnection(new HttpConnectionImplforExportData01());
Database database = new Database("mugadb");
Table table = new Table(database, "mugatbl");
ExportRequest request = new ExportRequest(
table, "s3", "bucket1", "json.gz", "xxx", "yyy");
ExportResult result = clientAdaptor.exportData(request);
Job job = result.getJob();
assertEquals(database.getName(), job.getDatabase().getName());
}
static class HttpConnectionImplforExportData02 extends HttpConnectionImpl {
@Override
void doPostRequest(Request<?> request, String path, Map<String, String> header,
Map<String, String> params) throws IOException {
// do nothing
}
@Override
int getResponseCode() throws IOException {
return HttpURLConnection.HTTP_OK;
}
@Override
String getResponseMessage() throws IOException {
return "";
}
@Override
String getResponseBody() throws IOException {
return "foobar"; // invalid JSON data
}
@Override
void disconnect() {
// do nothing
}
}
/**
* check behavior when receiving *invalid JSON data* as response body
*/
@Test
public void testExportData02() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials(props));
HttpClientAdaptor clientAdaptor = new HttpClientAdaptor(conf);
clientAdaptor.setConnection(new HttpConnectionImplforExportData02());
try {
Database database = new Database("mugadb");
Table table = new Table(database, "mugatbl");
ExportRequest request = new ExportRequest(
table, "s3", "bucket1", "json.gz", "xxx", "yyy");
clientAdaptor.exportData(request);
fail();
} catch (Throwable t) {
assertTrue(t instanceof ClientException);
}
}
static class HttpConnectionImplforExportData03 extends HttpConnectionImpl {
@Override
void doPostRequest(Request<?> request, String path, Map<String, String> header,
Map<String, String> params) throws IOException {
// do nothing
}
@Override
int getResponseCode() throws IOException {
return HttpURLConnection.HTTP_BAD_REQUEST;
}
@Override
String getResponseMessage() throws IOException {
return "";
}
@Override
String getResponseBody() throws IOException {
return "";
}
@Override
void disconnect() {
// do nothing
}
}
/**
* check behavior when receiving non-OK response code
*/
@Test
public void testExportData03() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials(props));
HttpClientAdaptor clientAdaptor = new HttpClientAdaptor(conf);
clientAdaptor.setConnection(new HttpConnectionImplforExportData03());
try {
Database database = new Database("mugadb");
Table table = new Table(database, "mugatbl");
ExportRequest request = new ExportRequest(
table, "ex", "bucket1", "json.gz", "xxx", "yyy");
clientAdaptor.exportData(request);
fail();
} catch (Throwable t) {
assertTrue(t instanceof ClientException);
}
}
}
|
package org.mozilla.mozstumbler.client;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import org.mozilla.mozstumbler.R;
import org.mozilla.mozstumbler.service.AppGlobals;
import org.mozilla.mozstumbler.service.core.http.IHttpUtil;
import org.mozilla.mozstumbler.service.core.http.IResponse;
import org.mozilla.mozstumbler.service.utils.NetworkInfo;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class Updater {
private static final String LOG_TAG = AppGlobals.LOG_PREFIX + Updater.class.getSimpleName();
private static final String LATEST_URL = "https://github.com/mozilla/MozStumbler/releases/latest";
private static final String APK_URL_FORMAT = "https://github.com/mozilla/MozStumbler/releases/download/v%s/MozStumbler-v%s.apk";
private final IHttpUtil httpClient;
public Updater(IHttpUtil httpUtil) {
httpClient = httpUtil;
}
public boolean wifiExclusiveAndUnavailable() {
return !NetworkInfo.getInstance().isWifiAvailable() && ClientPrefs.getInstance().getUseWifiOnly();
}
public boolean checkForUpdates(final Activity activity, String api_key) {
// No API Key means skip the update
if (api_key == null || api_key.equals("")) {
return false;
}
// No wifi available and require the use of wifi only means skip
if (wifiExclusiveAndUnavailable()) {
return false;
}
new AsyncTask<Void, Void, IResponse>() {
@Override
public IResponse doInBackground(Void... params) {
return httpClient.head(LATEST_URL, null);
}
@Override
public void onPostExecute(IResponse response) {
if (response == null) {
return;
}
Map<String, List<String>> headers = response.getHeaders();
Log.i(LOG_TAG, "Got headers: "+ headers.toString());
String locationUrl = headers.get("Location").get(0);
String[] parts = locationUrl.split("/");
String tag = parts[parts.length-1];
String latestVersion = tag.substring(1); // strip the 'v' from the beginning
String installedVersion = PackageUtils.getAppVersion(activity);
Log.d(LOG_TAG, "Installed version: " + installedVersion);
Log.d(LOG_TAG, "Latest version: " + latestVersion);
if (isVersionGreaterThan(latestVersion, installedVersion) && !activity.isFinishing()) {
showUpdateDialog(activity, installedVersion, latestVersion);
}
}
}.execute();
return true;
}
private boolean isVersionGreaterThan(String a, String b) {
if (a == null) {
return false;
}
if (b == null) {
return true;
}
if (a.equals(b)) {
return false; // fast path
}
String[] as = a.split("\\.");
String[] bs = b.split("\\.");
int len = Math.min(as.length, bs.length);
try {
for (int i = 0; i < len; i++) {
int an = Integer.parseInt(as[i]);
int bn = Integer.parseInt(bs[i]);
if (an == bn) {
continue;
}
return (an > bn);
}
} catch (NumberFormatException e) {
Log.w(LOG_TAG, "a='" + a + "', b='" + b + "'", e);
return false;
}
// Strings have identical prefixes, so longest version string wins.
return as.length > bs.length;
}
private void showUpdateDialog(final Context context,
String installedVersion,
final String latestVersion) {
String msg = context.getString(R.string.update_message);
msg = String.format(msg, installedVersion, latestVersion);
if (installedVersion.startsWith("0.") &&
latestVersion.startsWith("1.")) {
// From 0.x to 1.0 and higher, the keystore changed
msg += " " + context.getString(R.string.must_uninstall_to_update);
}
final Dialog.OnCancelListener onCancel = new Dialog.OnCancelListener() {
@Override
public void onCancel(DialogInterface di) {
di.dismiss();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setTitle(context.getString(R.string.update_title))
.setMessage(msg)
.setPositiveButton(context.getString(R.string.update_now),
new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface di, int which) {
Log.d(LOG_TAG, "Update Now");
di.dismiss();
downloadAndInstallUpdate(context, latestVersion);
}
})
.setNegativeButton(context.getString(R.string.update_later),
new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface di, int which) {
onCancel.onCancel(di);
}
})
.setOnCancelListener(onCancel);
builder.create().show();
}
private void downloadAndInstallUpdate(final Context context, final String version) {
new AsyncTask<Void, Void, File>() {
@Override
public File doInBackground(Void... params) {
URL apkURL = getUpdateURL(version);
File apk = downloadFile(context, apkURL);
if (apk == null || !apk.exists()) {
Log.e(LOG_TAG, "Update file not found!");
return null;
}
return apk;
}
@Override
public void onPostExecute(File result){
if (result != null) {
installPackage(context, result);
}
}
}.execute();
}
private URL getUpdateURL(String version) {
String url = String.format(APK_URL_FORMAT, version, version);
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
private File downloadFile(Context context, URL url) {
Log.d(LOG_TAG, "Downloading: " + url);
File file;
File dir = context.getExternalFilesDir(null);
try {
file = File.createTempFile("update", ".apk", dir);
} catch (IOException e1) {
Log.e(LOG_TAG, "", e1);
return null;
}
try {
return httpClient.getUrlAsFile(url, file);
} catch (IOException e) {
Log.e(LOG_TAG, "", e);
file.delete();
return null;
}
}
private void installPackage(Context context, File apkFile) {
Uri apkURI = Uri.fromFile(apkFile);
Log.d(LOG_TAG, "Installing: " + apkURI);
//First stop the service so it is not running more
Intent service = new Intent();
service.setClass(context, ClientStumblerService.class);
context.stopService(service);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//And then kill the app to avoid any error
android.os.Process.killProcess(android.os.Process.myPid());
}
}
|
package fi.aluesarjat.prototype;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class DataServiceTest {
@Test
public void SplitDatasetDef() {
List<String> elements = DataService.splitDatasetDef("file:/opt/aluesarjat/data/Vaesto_sal/Perheet_sal/B01S_ESP_Perhetyypit.px \".\"");
assertEquals(Arrays.asList("file:/opt/aluesarjat/data/Vaesto_sal/Perheet_sal/B01S_ESP_Perhetyypit.px", "\".\""), elements);
}
@Test
public void SplitDatasetDef_With_Spaces() {
List<String> elements = DataService.splitDatasetDef("file:/opt/aluesarjat/data/Vaesto sal/Perheet_sal/B01S_ESP_Perhetyypit.px \".\"");
assertEquals(Arrays.asList("file:/opt/aluesarjat/data/Vaesto sal/Perheet_sal/B01S_ESP_Perhetyypit.px", "\".\""), elements);
}
}
|
package io.c12.bala.service;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import io.c12.bala.db.dao.UserDao;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceImplTest {
private static final String userId = "[email protected]";
private static final String password = "Password1";
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserDao userDao;
@Test
public void authenticateUser() {
// Positive Test Case
when(userDao.getPasswordHashByUserId(userId)).thenReturn("$s0$41010$dAiki5TNWpASH54dazRjHg==$ogG51PevlOjcRHNkFIlprqMxUuzwJcvX7s8h5h2oMUI=");
assertTrue(userService.authenticateUser(userId, password));
// Negative Test Case
when(userDao.getPasswordHashByUserId(userId)).thenReturn("$s0$41010$YHtdaf1NcTXeP6Uv+SVptA==$ZuDOHKVFsPNodTKec5C6JdSdojfh6NdKzEp/hm0uSHE=");
assertFalse(userService.authenticateUser(userId, password));
}
}
|
package io.github.binaryoverload;
import com.google.gson.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class JSONConfigTest {
private static JSONConfig config = new JSONConfig(JSONConfig.class.getClassLoader().getResourceAsStream("test.json"));
@Test
public void testSet() {
config.set("title", "Hi there");
assertTrue((config.getElement("title").getAsString()).equalsIgnoreCase("Hi there"));
}
@Test
public void testGet() {
assertTrue(config.getString("type").isPresent());
assertTrue(config.getString("type").get().equalsIgnoreCase("array"));
}
@Test
public void testGetEmpty() {
assertTrue(config.getElement("").equals(config.getObject()));
}
@Test(expected = IllegalArgumentException.class)
public void testGetMalformedPath() {
config.getElement("title...");
}
@Test
public void testGetString() {
assertTrue(config.getString("items.title").isPresent());
assertFalse(config.getString("items.properties").isPresent());
assertFalse(config.getString("items.required").isPresent());
}
@Test
public void testGetInteger() {
assertTrue(config.getInteger("date").isPresent());
assertFalse(config.getInteger("title").isPresent());
assertFalse(config.getInteger("items").isPresent());
}
@Test
public void testGetDouble() {
assertTrue(config.getDouble("items.properties.price.minimum").isPresent());
assertTrue(config.getDouble("date").isPresent());
assertFalse(config.getDouble("items.title").isPresent());
}
@Test
public void testGetLong() {
assertTrue(config.getLong("items.properties.price.minimum").isPresent());
assertTrue(config.getLong("date").isPresent());
assertFalse(config.getLong("items.title").isPresent());
}
@Test
public void testGetBoolean() {
assertTrue(config.getBoolean("items.properties.price.exclusiveMinimum").isPresent());
assertFalse(config.getBoolean("date").isPresent());
assertFalse(config.getBoolean("items.title").isPresent());
}
}
|
package io.github.bonigarcia.wdm.test;
import static java.lang.Boolean.parseBoolean;
import static java.lang.System.getProperty;
import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.opera.OperaOptions.CAPABILITY;
import static org.openqa.selenium.remote.DesiredCapabilities.operaBlink;
import java.io.File;
import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.opera.OperaOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.github.bonigarcia.wdm.OperaDriverManager;
import io.github.bonigarcia.wdm.base.BaseBrowserTst;
/**
* Test with Opera browser.
*
* @author Boni Garcia ([email protected])
* @since 1.0.0
*/
public class OperaTest extends BaseBrowserTst {
@BeforeClass
public static void setupClass() {
assumeFalse(parseBoolean(getProperty("headlessEnvironment")));
OperaDriverManager.getInstance().setup();
}
@Before
public void setupTest() {
File operaBinary;
if (IS_OS_WINDOWS) {
operaBinary = new File("C:\\Program Files\\Opera\\launcher.exe");
} else {
operaBinary = new File("/usr/bin/opera");
}
assumeTrue(operaBinary.exists());
OperaOptions options = new OperaOptions();
options.setBinary(operaBinary);
DesiredCapabilities capabilities = operaBlink();
capabilities.setCapability(CAPABILITY, options);
driver = new OperaDriver(capabilities);
}
}
|
package mho.wheels.iterables;
import org.jetbrains.annotations.NotNull;
import org.junit.Ignore;
import org.junit.Test;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.testing.Testing.*;
import static org.junit.Assert.fail;
public class RandomProviderTest {
private static final RandomProvider P = new RandomProvider(0x6af477d9a7e54fcaL);
private static final int DEFAULT_SAMPLE_SIZE = 1000000;
private static final int DEFAULT_TOP_COUNT = 10;
@Test
public void testConstructor() {
RandomProvider provider = new RandomProvider();
aeq(provider.getScale(), 32);
aeq(provider.getSecondaryScale(), 8);
}
@Test
public void testConstructor_int() {
aeq(new RandomProvider(5), "RandomProvider[5, 32, 8]");
aeq(new RandomProvider(100), "RandomProvider[100, 32, 8]");
aeq(new RandomProvider(-3), "RandomProvider[-3, 32, 8]");
}
@Test
public void testGetScale() {
aeq(new RandomProvider().getScale(), 32);
aeq(new RandomProvider().withScale(100).getScale(), 100);
aeq(new RandomProvider().withScale(3).getScale(), 3);
}
@Test
public void testGetSecondaryScale() {
aeq(new RandomProvider().getSecondaryScale(), 8);
aeq(new RandomProvider().withSecondaryScale(100).getSecondaryScale(), 100);
aeq(new RandomProvider().withSecondaryScale(3).getSecondaryScale(), 3);
}
private static <T> void simpleProviderHelper(
@NotNull Iterable<T> xs,
@NotNull String output,
@NotNull String sampleCountOutput
) {
aeqit(take(20, xs), output);
aeqit(sampleCount(DEFAULT_SAMPLE_SIZE, xs).entrySet(), sampleCountOutput);
}
@Test
public void testBooleans() {
simpleProviderHelper(
P.booleans(),
"[false, false, false, true, false, true, true, false, true, true, false, false, false, true, true," +
" false, false, true, true, false]",
"[false=500122, true=499878]"
);
}
@Test
public void testOrderings() {
simpleProviderHelper(
P.orderings(),
"[EQ, GT, EQ, EQ, EQ, GT, LT, GT, LT, EQ, EQ, LT, LT, GT, EQ, LT, LT, LT, GT, EQ]",
"[EQ=333219, GT=333296, LT=333485]"
);
}
@Test
public void testRoundingModes() {
simpleProviderHelper(
P.roundingModes(),
"[HALF_UP, HALF_UP, HALF_UP, DOWN, HALF_DOWN, UP, DOWN, CEILING, UNNECESSARY, HALF_DOWN, HALF_DOWN," +
" CEILING, FLOOR, HALF_DOWN, UNNECESSARY, FLOOR, FLOOR, HALF_EVEN, UP, HALF_DOWN]",
"[HALF_UP=125006, DOWN=125075, HALF_DOWN=124925, UP=124892, CEILING=125057, UNNECESSARY=125002," +
" FLOOR=125061, HALF_EVEN=124982]"
);
}
private static void geometricHelper(
@NotNull Iterable<Integer> xs,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean
) {
aeqit(take(20, xs), output);
aeq(topSampleCount(DEFAULT_SAMPLE_SIZE, DEFAULT_TOP_COUNT, xs), topSampleCount);
aeq(meanOfIntegers(xs), sampleMean);
}
private static void naturalIntegersGeometric_helper(
int mean,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean
) {
geometricHelper(P.naturalIntegersGeometric(mean), output, topSampleCount, sampleMean);
}
@Test
@Ignore
public void testNaturalIntegersGeometric() {
naturalIntegersGeometric_helper(0,
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]",
"{0=1000000}",
0.0
);
naturalIntegersGeometric_helper(
1,
"[0, 0, 0, 2, 0, 1, 2, 0, 2, 0, 0, 3, 0, 0, 0, 0, 4, 0, 1, 0]",
"{0=498731, 1=250297, 2=125336, 3=62592, 4=31500, 5=15746, 6=8002, 7=3890, 8=1922, 9=981}",
1.003892999997649
);
naturalIntegersGeometric_helper(
2,
"[2, 2, 0, 1, 3, 2, 0, 5, 1, 0, 7, 0, 0, 5, 0, 0, 0, 2, 0, 4]",
"{0=333030, 1=222156, 2=148589, 3=98029, 4=66010, 5=44029, 6=29428, 7=19470, 8=13078, 9=8797}",
2.003356999989073
);
naturalIntegersGeometric_helper(
3,
"[5, 0, 1, 3, 2, 0, 7, 0, 8, 7, 1, 2, 0, 7, 5, 5, 1, 1, 3, 0]",
"{0=249593, 1=187157, 2=140530, 3=105260, 4=79490, 5=59545, 6=44447, 7=33455, 8=24992, 9=18829}",
3.007273999991544
);
naturalIntegersGeometric_helper(
4,
"[5, 0, 1, 3, 3, 7, 17, 1, 2, 0, 7, 5, 5, 1, 5, 0, 1, 5, 0, 1]",
"{0=199675, 1=160080, 2=127838, 3=102046, 4=82544, 5=65842, 6=52302, 7=42109, 8=33370, 9=26704}",
4.002147999991753
);
naturalIntegersGeometric_helper(
5,
"[5, 0, 1, 3, 3, 7, 17, 4, 0, 7, 5, 5, 7, 2, 5, 0, 1, 0, 0, 3]",
"{0=166772, 1=138747, 2=115323, 3=96516, 4=80590, 5=67087, 6=55738, 7=46574, 8=38599, 9=32319}",
5.004303000005186
);
naturalIntegersGeometric_helper(
10,
"[5, 0, 1, 7, 7, 23, 7, 5, 5, 7, 8, 0, 1, 1, 3, 7, 19, 14, 6, 2]",
"{0=91337, 1=82350, 2=75328, 3=68014, 4=62162, 5=56226, 6=51001, 7=46587, 8=42624, 9=38253}",
10.004593000004135
);
naturalIntegersGeometric_helper(
100,
"[5, 56, 5, 25, 52, 151, 183, 38, 88, 111, 16, 41, 95, 65, 21, 85, 32, 27, 23, 15]",
"{0=10074, 2=9937, 1=9815, 3=9545, 4=9543, 5=9429, 9=9164, 6=9119, 7=9099, 10=9058}",
99.98710199999887
);
naturalIntegersGeometric_helper(
-4,
"[5, 56, 5, 25, 52, 151, 183, 38, 88, 111, 16, 41, 95, 65, 21, 85, 32, 27, 23, 15]",
"{0=10074, 2=9937, 1=9815, 3=9545, 4=9543, 5=9429, 9=9164, 6=9119, 7=9099, 10=9058}",
99.98710199999887
);
try {
P.naturalIntegersGeometric(-4);
fail();
} catch (IllegalArgumentException ignored) {}
}
private static void positiveIntegersGeometric_helper(
int mean,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean
) {
geometricHelper(P.positiveIntegersGeometric(mean), output, topSampleCount, sampleMean);
}
private void positiveIntegersGeometric_fail(int meanSize) {
try {
P.positiveIntegersGeometric(meanSize);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testPositiveIntegersGeometric() {
positiveIntegersGeometric_helper(
1,
"[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]",
"{1=1000000}",
1.000000000007918 //rounding error
);
positiveIntegersGeometric_helper(
2,
"[1, 1, 1, 3, 1, 2, 3, 1, 3, 1, 1, 4, 1, 1, 1, 1, 5, 1, 2, 1]",
"{1=498731, 2=250297, 3=125336, 4=62592, 5=31500, 6=15746, 7=8002, 8=3890, 9=1922, 10=981}",
2.00389299998003
);
positiveIntegersGeometric_helper(
3,
"[3, 3, 1, 2, 4, 3, 1, 6, 2, 1, 8, 1, 1, 6, 1, 1, 1, 3, 1, 5]",
"{1=333030, 2=222156, 3=148589, 4=98029, 5=66010, 6=44029, 7=29428, 8=19470, 9=13078, 10=8797}",
3.003356999989909
);
positiveIntegersGeometric_helper(
4,
"[6, 1, 2, 4, 3, 1, 8, 1, 9, 8, 2, 3, 1, 8, 6, 6, 2, 2, 4, 1]",
"{1=249593, 2=187157, 3=140530, 4=105260, 5=79490, 6=59545, 7=44447, 8=33455, 9=24992, 10=18829}",
4.007273999990233);
positiveIntegersGeometric_helper(
5,
"[6, 1, 2, 4, 4, 8, 18, 2, 3, 1, 8, 6, 6, 2, 6, 1, 2, 6, 1, 2]",
"{1=199675, 2=160080, 3=127838, 4=102046, 5=82544, 6=65842, 7=52302, 8=42109, 9=33370, 10=26704}",
5.002148000008636
);
positiveIntegersGeometric_helper(
10,
"[6, 1, 2, 8, 8, 24, 8, 6, 6, 8, 9, 1, 2, 2, 4, 8, 20, 15, 7, 3]",
"{1=100343, 2=89755, 3=81299, 4=72632, 5=65775, 6=58756, 7=52964, 8=47987, 9=42962, 10=38405}",
10.002680000005894
);
positiveIntegersGeometric_helper(
100,
"[6, 57, 6, 26, 53, 152, 184, 39, 89, 112, 17, 42, 96, 66, 22, 86, 33, 28, 24, 16]",
"{1=10197, 3=9995, 2=9909, 4=9645, 5=9638, 6=9529, 10=9264, 7=9236, 8=9183, 11=9132}",
100.00996300000024
);
positiveIntegersGeometric_fail(0);
positiveIntegersGeometric_fail(-5);
}
private static void negativeIntegersGeometric_helper(
int mean,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean
) {
geometricHelper(P.negativeIntegersGeometric(mean), output, topSampleCount, sampleMean);
}
private void negativeIntegersGeometric_fail(int meanSize) {
try {
P.negativeIntegersGeometric(meanSize);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testNegativeIntegersGeometric() {
negativeIntegersGeometric_helper(
-1,
"[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]",
"{-1=1000000}",
-1.000000000007918 //rounding error
);
negativeIntegersGeometric_helper(
-2,
"[-1, -1, -1, -3, -1, -2, -3, -1, -3, -1, -1, -4, -1, -1, -1, -1, -5, -1, -2, -1]",
"{-1=498731, -2=250297, -3=125336, -4=62592, -5=31500, -6=15746, -7=8002, -8=3890, -9=1922, -10=981}",
-2.00389299998003
);
negativeIntegersGeometric_helper(
-3,
"[-3, -3, -1, -2, -4, -3, -1, -6, -2, -1, -8, -1, -1, -6, -1, -1, -1, -3, -1, -5]",
"{-1=333030, -2=222156, -3=148589, -4=98029, -5=66010, -6=44029, -7=29428, -8=19470, -9=13078," +
" -10=8797}",
-3.003356999989909
);
negativeIntegersGeometric_helper(
-4,
"[-6, -1, -2, -4, -3, -1, -8, -1, -9, -8, -2, -3, -1, -8, -6, -6, -2, -2, -4, -1]",
"{-1=249593, -2=187157, -3=140530, -4=105260, -5=79490, -6=59545, -7=44447, -8=33455, -9=24992," +
" -10=18829}",
-4.007273999990233);
negativeIntegersGeometric_helper(
-5,
"[-6, -1, -2, -4, -4, -8, -18, -2, -3, -1, -8, -6, -6, -2, -6, -1, -2, -6, -1, -2]",
"{-1=199675, -2=160080, -3=127838, -4=102046, -5=82544, -6=65842, -7=52302, -8=42109, -9=33370," +
" -10=26704}",
-5.002148000008636
);
negativeIntegersGeometric_helper(
-10,
"[-6, -1, -2, -8, -8, -24, -8, -6, -6, -8, -9, -1, -2, -2, -4, -8, -20, -15, -7, -3]",
"{-1=100343, -2=89755, -3=81299, -4=72632, -5=65775, -6=58756, -7=52964, -8=47987, -9=42962," +
" -10=38405}",
-10.002680000005894
);
negativeIntegersGeometric_helper(
-100,
"[-6, -57, -6, -26, -53, -152, -184, -39, -89, -112, -17, -42, -96, -66, -22, -86, -33, -28, -24," +
" -16]",
"{-1=10197, -3=9995, -2=9909, -4=9645, -5=9638, -6=9529, -10=9264, -7=9236, -8=9183, -11=9132}",
-100.00996300000024
);
negativeIntegersGeometric_fail(0);
negativeIntegersGeometric_fail(5);
}
private static void nonzeroIntegersGeometric_helper(
int mean,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean,
double sampleAbsMean
) {
Iterable<Integer> xs = P.nonzeroIntegersGeometric(mean);
geometricHelper(xs, output, topSampleCount, sampleMean);
aeq(meanOfIntegers(map(Math::abs, xs)), sampleAbsMean);
}
private void nonzeroIntegersGeometric_fail(int meanSize) {
try {
P.nonzeroIntegersGeometric(meanSize);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testNonzeroIntegersGeometric() {
nonzeroIntegersGeometric_helper(
1,
"[-1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1]",
"{-1=500122, 1=499878}",
-2.439999999999994E-4,
1.000000000007918 //rounding error
);
nonzeroIntegersGeometric_helper(
2,
"[-1, -1, -1, 3, -1, 2, 3, -1, 3, 1, -1, -4, -1, 1, 1, -1, -5, 1, 2, -1]",
"{1=249397, -1=249334, -2=125532, 2=124765, -3=62734, 3=62602, 4=31581, -4=31011, 5=15775, -5=15725}",
4.610000000000048E-4,
2.00389299998003
);
nonzeroIntegersGeometric_helper(
3,
"[-3, -3, -1, 2, -4, 3, 1, -6, 2, 1, -8, -1, -1, 6, 1, -1, -1, 3, 1, -5]",
"{1=166856, -1=166174, -2=111318, 2=110838, 3=74330, -3=74259, -4=49170, 4=48859, 5=33025, -5=32985}",
-0.003314999999999991,
3.003356999989909
);
nonzeroIntegersGeometric_helper(
4,
"[-6, -1, -2, 4, -3, 1, 8, -1, 9, 8, -2, -3, -1, 8, 6, -6, -2, 2, 4, -1]",
"{-1=124963, 1=124630, -2=93780, 2=93377, 3=70541, -3=69989, -4=52748, 4=52512, -5=39799, 5=39691}",
0.0041719999999999275,
4.007273999990233
);
nonzeroIntegersGeometric_helper(
5,
"[-6, -1, -2, 4, -4, 8, 18, -2, 3, 1, -8, -6, -6, 2, 6, -1, -2, 6, 1, -2]",
"{-1=99902, 1=99773, 2=80317, -2=79763, 3=63969, -3=63869, 4=51064, -4=50982, -5=41291, 5=41253}",
-0.007923999999999843,
5.002148000008636
);
nonzeroIntegersGeometric_helper(
10,
"[-6, -1, -2, 8, -8, 24, 8, -6, 6, 8, -9, -1, -2, 2, 4, -8, -20, 15, 7, -3]",
"{1=50233, -1=50110, 2=44897, -2=44858, -3=40707, 3=40592, -4=36359, 4=36273, 5=33078, -5=32697}",
-0.011589999999999732,
10.002680000005894
);
nonzeroIntegersGeometric_helper(
100,
"[-6, -57, -6, 26, -53, 152, 184, -39, 89, 112, -17, -42, -96, 66, 22, -86, -33, 28, 24, -16]",
"{1=5124, -1=5073, -3=5027, -2=4989, 3=4968, 2=4920, -5=4832, -4=4831, 4=4814, 5=4806}",
0.09591699999999705,
100.00996300000024
);
nonzeroIntegersGeometric_fail(0);
nonzeroIntegersGeometric_fail(-5);
}
private static void integersGeometric_helper(
int mean,
@NotNull String output,
@NotNull String topSampleCount,
double sampleMean,
double sampleAbsMean
) {
Iterable<Integer> xs = P.integersGeometric(mean);
geometricHelper(xs, output, topSampleCount, sampleMean);
aeq(meanOfIntegers(map(Math::abs, xs)), sampleAbsMean);
}
private void integersGeometric_fail(int meanSize) {
try {
P.integersGeometric(meanSize);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
@Ignore
public void testIntegersGeometric() {
integersGeometric_helper(
0,
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]",
"{0=1000000}",
0.0,
0.0
);
integersGeometric_helper(
1,
"[-1, -1, -1, 0, -1, 0, 0, -1, 2, 0, -1, -1, -1, 1, 2, -1, -1, 0, 2, -1]",
"{-1=1000000}",
-1.000000000007918, //rounding error
0.0
);
integersGeometric_helper(
2,
"[-1, -1, -1, -3, -1, -2, -3, -1, -3, -1, -1, -4, -1, -1, -1, -1, -5, -1, -2, -1]",
"{-1=498731, -2=250297, -3=125336, -4=62592, -5=31500, -6=15746, -7=8002, -8=3890, -9=1922, -10=981}",
-2.00389299998003,
0.0
);
integersGeometric_helper(
3,
"[-3, -3, -1, -2, -4, -3, -1, -6, -2, -1, -8, -1, -1, -6, -1, -1, -1, -3, -1, -5]",
"{-1=333030, -2=222156, -3=148589, -4=98029, -5=66010, -6=44029, -7=29428, -8=19470, -9=13078," +
" -10=8797}",
-3.003356999989909,
0.0
);
integersGeometric_helper(
4,
"[-6, -1, -2, -4, -3, -1, -8, -1, -9, -8, -2, -3, -1, -8, -6, -6, -2, -2, -4, -1]",
"{-1=249593, -2=187157, -3=140530, -4=105260, -5=79490, -6=59545, -7=44447, -8=33455, -9=24992," +
" -10=18829}",
-4.007273999990233,
0.0
);
integersGeometric_helper(
5,
"[-6, -1, -2, -4, -4, -8, -18, -2, -3, -1, -8, -6, -6, -2, -6, -1, -2, -6, -1, -2]",
"{-1=199675, -2=160080, -3=127838, -4=102046, -5=82544, -6=65842, -7=52302, -8=42109, -9=33370," +
" -10=26704}",
-5.002148000008636,
0.0
);
integersGeometric_helper(
10,
"[-6, -1, -2, -8, -8, -24, -8, -6, -6, -8, -9, -1, -2, -2, -4, -8, -20, -15, -7, -3]",
"{-1=100343, -2=89755, -3=81299, -4=72632, -5=65775, -6=58756, -7=52964, -8=47987, -9=42962," +
" -10=38405}",
-10.002680000005894,
0.0
);
integersGeometric_helper(
100,
"[-6, -57, -6, -26, -53, -152, -184, -39, -89, -112, -17, -42, -96, -66, -22, -86, -33, -28, -24," +
" -16]",
"{-1=10197, -3=9995, -2=9909, -4=9645, -5=9638, -6=9529, -10=9264, -7=9236, -8=9183, -11=9132}",
-100.00996300000024,
0.0
);
integersGeometric_fail(0);
integersGeometric_fail(5);
}
@Test
public void testPositiveBytes() {
aeqit(take(20, P.positiveBytes()),
"[18, 88, 104, 6, 29, 29, 13, 13, 52, 56, 113, 52, 57, 71, 91, 59, 64, 66, 1, 26]");
}
@Test
@Ignore
public void testPositiveShorts() {
aeqit(take(20, P.positiveShorts()),
"[29559, 24497, 25521, 7601, 15393, 17782, 25443, 13977, 19844, 10977," +
" 6993, 15895, 13568, 24091, 18433, 27279, 26356, 29039, 23271, 17273]");
}
@Test
public void testPositiveIntegers() {
aeqit(take(20, P.positiveIntegers()),
"[838088639, 328782387, 1023352007, 1288498826, 596019284, 1251925389, 1626530542, 872910510," +
" 1604720617, 1168045472, 1535924, 405543310, 124070167, 1385792448, 1255589909, 742314043," +
" 149049931, 1532599744, 1364960949, 740140532]");
}
@Test
public void testPositiveLongs() {
aeqit(take(20, P.positiveLongs()),
"[7199126587670897765, 8790526798708989202, 5119766654749621017, 4474953112883356325," +
" 4662298945794479298, 13193478919435035, 1065754609235199870, 7661308888129625996," +
" 1280329148412410751, 6721818803979990042, 4947586878887127432, 7082175163031428867," +
" 2686229925919009542, 602148044581217176, 2626034444874753984, 4428434850933104875," +
" 926106523787202568, 7729238571771020305, 7971237095602901340, 2602655955979596862]");
}
private void positiveBigIntegers_int_helper(int meanBitSize, @NotNull String output) {
aeqit(take(20, P.withScale(meanBitSize).positiveBigIntegers()), output);
}
@Test
@Ignore
public void testPositiveBigIntegers_Int() {
positiveBigIntegers_int_helper(3, "[15, 1, 7, 3, 1, 2, 8, 1, 13, 5, 20, 2, 1, 1, 1, 1, 1, 1, 3, 1]");
positiveBigIntegers_int_helper(4, "[1, 1, 1, 6, 4, 94, 59, 4, 1, 1, 1, 43, 15, 1, 3, 1, 2, 103103, 393, 12]");
positiveBigIntegers_int_helper(5, "[1, 2, 2821, 1, 13, 1, 273, 1, 3, 3, 1, 3, 15, 2, 6, 14, 5, 7, 1, 1]");
positiveBigIntegers_int_helper(10,
"[418, 1, 886, 15, 2, 1023538995542242, 2527383, 11, 2, 3411, 10, 4891, 8, 2, 25, 3, 10, 349," +
" 110732294, 3877]");
positiveBigIntegers_int_helper(100,
"[631847851262602872164, 62178362933629457256170097449498832870026795417, 547758176," +
" 2346149950119691144404, 311, 4742738, 67302549518065217887062796935441749979, 53471, 4223," +
" 17312403, 316463874199, 6, 447122575, 1176, 704610823827," +
" 31430331193008341986440693101333088795173295035345951291600655076040609838446721240723225651953502" +
"51261283498014102904063, 7517586777550828054626795662503, 741109, 101419744017795180979313623318," +
" 25612091393]");
try {
P.withScale(2).positiveBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(0).positiveBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(-4).positiveBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
@Ignore
public void testPositiveBigIntegers() {
aeqit(take(20, P.positiveBigIntegers()),
"[65649474733, 50, 1752003, 108680047959250986, 2, 169829217569110637456607575012447814909456," +
" 8046132249267142822265255, 78549137, 3080," +
" 6955247343603701669934693326084685760295830262297267296665, 547758176, 2133810949," +
" 547945394950967, 4742738, 27183283269, 1631119, 1811559053982367, 595931, 13367, 20607]");
}
@Test
@Ignore
public void testNegativeBytes() {
aeqit(take(20, P.negativeBytes()),
"[-105, -128, -85, -93, -2, -84, -76, -46, -109, -36," +
" -36, -44, -11, -68, -100, -111, -79, -10, -124, -62]");
}
@Test
@Ignore
public void testNegativeShorts() {
aeqit(take(20, P.negativeShorts()),
"[-26695, -32710, -21548, -23768, -417, -21442, -19264, -11625, -27827, -9074," +
" -8998, -11245, -2562, -17159, -25537, -28322, -20208, -2536, -31687, -15831]");
}
@Test
@Ignore
public void testNegativeIntegers() {
aeqit(take(20, P.negativeIntegers()),
"[-796047920, -7618489, -1470662991, -1179662338, -1484637212, -1770087994, -647698373, -2045988837," +
" -947846915, -582804843, -1646292442, -141769040, -1282994601, -213515457, -1321491010, -767780260," +
" -1996736455, -2015128232, -1916151903, -81932857]");
}
@Test
@Ignore
public void testNegativeLongs() {
aeqit(take(20, P.negativeLongs()),
"[-3418999782456442809, -6316449450962204674, -7602470043748550772, -2781843328518141957," +
" -4070971502122296683, -7070772197709661375, -608893388310409322, -3297591106051422579," +
" -8575917774971103912, -8229809756225242051, -351898943428221388, -5035479974893608156," +
" -2087360320830562347, -4864443654894485421, -3626293116983244765, -6128126907599458534," +
" -4181052272311759209, -1935017808723883567, -3861844328646811360, -196660781681668032]");
}
private void negativeBigIntegers_intHelper(int meanBitSize, @NotNull String output) {
aeqit(take(20, P.withScale(meanBitSize).negativeBigIntegers()), output);
}
@Test
@Ignore
public void testNegativeBigIntegers_Int() {
negativeBigIntegers_intHelper(3,
"[-15, -1, -7, -3, -1, -2, -8, -1, -13, -5, -20, -2, -1, -1, -1, -1, -1, -1, -3, -1]");
negativeBigIntegers_intHelper(4,
"[-1, -1, -1, -6, -4, -94, -59, -4, -1, -1, -1, -43, -15, -1, -3, -1, -2, -103103, -393, -12]");
negativeBigIntegers_intHelper(5,
"[-1, -2, -2821, -1, -13, -1, -273, -1, -3, -3, -1, -3, -15, -2, -6, -14, -5, -7, -1, -1]");
negativeBigIntegers_intHelper(10,
"[-418, -1, -886, -15, -2, -1023538995542242, -2527383, -11, -2, -3411, -10, -4891, -8, -2, -25, -3," +
" -10, -349, -110732294, -3877]");
negativeBigIntegers_intHelper(100,
"[-631847851262602872164, -62178362933629457256170097449498832870026795417, -547758176," +
" -2346149950119691144404, -311, -4742738, -67302549518065217887062796935441749979, -53471, -4223," +
" -17312403, -316463874199, -6, -447122575, -1176, -704610823827," +
" -3143033119300834198644069310133308879517329503534595129160065507604060983844672124072322565195350" +
"251261283498014102904063, -7517586777550828054626795662503, -741109," +
" -101419744017795180979313623318, -25612091393]");
try {
P.withScale(2).negativeBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(0).negativeBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(-4).negativeBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
@Ignore
public void testNegativeBigIntegers() {
aeqit(take(20, P.negativeBigIntegers()),
"[-65649474733, -50, -1752003, -108680047959250986, -2, -169829217569110637456607575012447814909456," +
" -8046132249267142822265255, -78549137, -3080," +
" -6955247343603701669934693326084685760295830262297267296665, -547758176, -2133810949," +
" -547945394950967, -4742738, -27183283269, -1631119, -1811559053982367, -595931, -13367, -20607]");
}
@Test
@Ignore
public void testNaturalBytes() {
aeqit(take(20, P.naturalBytes()),
"[80, 71, 49, 126, 65, 100, 70, 12, 59, 123, 11, 121, 120, 27, 125, 21, 38, 65, 48, 22]");
}
@Test
@Ignore
public void testNaturalShorts() {
aeqit(take(20, P.naturalShorts()),
"[17872, 16455, 30385, 18430, 29121, 15332, 6598, 14220, 26683, 18427," +
" 10763, 19577, 16888, 12315, 253, 6805, 4646, 15169, 18096, 3990]");
}
@Test
@Ignore
public void testNaturalIntegers() {
aeqit(take(20, P.naturalIntegers()),
"[1351435728, 2139865159, 676820657, 967821310, 54555073, 662846436, 377395654, 1523693452," +
" 1499785275, 1189267451, 1179298315, 1473891449, 335757816, 101494811, 1199636733, 1564678805," +
" 501191206, 332315457, 2005714608, 2074906518]");
}
@Test
@Ignore
public void testNaturalLongs() {
aeqit(take(20, P.naturalLongs()),
"[5804372254398332999, 2906922585892571134, 234312252881255396, 1620901993106225036," +
" 6441528708336633851, 5065047696626797689, 1442068837050396699, 5152400534732479125," +
" 2152599839145114433, 8614478648544366486, 471066488414342743, 8378098296417551167," +
" 3854184673538224894, 2723679502578984382, 5925780930803353229, 5761072552197714005," +
" 647454261883671896, 993562280629533757, 8871473093426554420, 2417358956864889798]");
}
private void naturalBigIntegers_intHelper(int meanBitSize, @NotNull String output) {
aeqit(take(20, P.withScale(meanBitSize).naturalBigIntegers()), output);
}
@Test
@Ignore
public void testNaturalBigIntegers_Int() {
naturalBigIntegers_intHelper(3, "[7, 0, 3, 1, 0, 0, 0, 0, 5, 1, 4, 0, 0, 0, 0, 0, 0, 0, 1, 0]");
naturalBigIntegers_intHelper(4, "[0, 0, 0, 2, 0, 30, 27, 0, 0, 0, 0, 11, 7, 0, 1, 0, 0, 37567, 137, 4]");
naturalBigIntegers_intHelper(5, "[0, 0, 773, 0, 5, 0, 17, 0, 1, 1, 0, 1, 7, 0, 2, 6, 1, 3, 0, 0]");
naturalBigIntegers_intHelper(10,
"[162, 0, 374, 7, 0, 460589042120930, 430231, 3, 0, 1363, 2, 795, 0, 0, 9, 1, 2, 93, 43623430, 1829]");
naturalBigIntegers_intHelper(100,
"[41552040903897220452, 16506436767038741062304946427114988505778903449, 10887264," +
" 1165558329402279840980, 55, 548434, 24767253652947909954140971006470723547, 20703, 127, 535187," +
" 41585967255, 2, 178687119, 152, 154855009939," +
" 56078324121392560898815013813029700518762371070537161632940615106341336182783092944267721191521241" +
"9825380326041355410687, 2446984376637910448639982840999, 216821, 22191581503530843385769672982," +
" 8432222209]");
try {
P.withScale(2).naturalBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(0).naturalBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(-4).naturalBigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
@Ignore
public void testNaturalBigIntegers() {
aeqit(take(20, P.naturalBigIntegers()),
"[31289736365, 18, 703427, 36622453921323050, 0, 82716931637350390809983675509915152776720," +
" 3210428970808626123440551, 11440273, 1032," +
" 678145608217020906098903902877019344193474817833232783769, 10887264, 1060069125, 266470418240311," +
" 548434, 10003414085, 582543, 685659147139743, 71643, 5175, 4223]");
}
@Test
@Ignore
public void testBytes() {
aeqit(take(20, P.bytes()),
"[-48, 71, -79, -2, -63, -28, -58, -116, 59, -5, 11, 121, -8, 27, -3, -107, 38, 65, -80, -106]");
}
@Test
@Ignore
public void testShorts() {
aeqit(take(20, P.shorts()),
"[17872, -16313, 30385, -14338, 29121, 15332, -26170, -18548, -6085, -14341," +
" -22005, -13191, 16888, -20453, 253, 6805, -28122, -17599, -14672, -28778]");
}
@Test
@Ignore
public void testIntegers() {
aeqit(take(20, P.integers()),
"[-796047920, -7618489, -1470662991, -1179662338, 54555073, -1484637212, -1770087994, 1523693452," +
" -647698373, 1189267451, 1179298315, 1473891449, 335757816, -2045988837, -947846915, -582804843," +
" -1646292442, 332315457, -141769040, 2074906518]");
}
@Test
@Ignore
public void testLongs() {
aeqit(take(20, P.longs()),
"[-3418999782456442809, -6316449450962204674, 234312252881255396, -7602470043748550772," +
" -2781843328518141957, 5065047696626797689, 1442068837050396699, -4070971502122296683," +
" -7070772197709661375, -608893388310409322, 471066488414342743, 8378098296417551167," +
" 3854184673538224894, 2723679502578984382, -3297591106051422579, 5761072552197714005," +
" -8575917774971103912, -8229809756225242051, -351898943428221388, 2417358956864889798]");
}
private void bigIntegers_intHelper(int meanBitSize, @NotNull String output) {
aeqit(take(20, P.withScale(meanBitSize).bigIntegers()), output);
}
@Test
@Ignore
public void testBigIntegers_Int() {
bigIntegers_intHelper(3, "[7, -1, 1, -1, 0, 0, -1, -6, -1, 6, -1, 0, -1, 0, -1, 1, 1, 1, 0, -1]");
bigIntegers_intHelper(4, "[1, 1, -7, 4, -2, 0, 10, -1, 0, 0, -2, -8, -6, 3, 0, -1, 0, 0, -2, 4]");
bigIntegers_intHelper(5, "[1, 773, 2, 0, 24, -10, -1, -2, -1, 1, -3, 3, -2, 7, 10, 2, 3271, 120, 11, 0]");
bigIntegers_intHelper(10, "[-2, 11, -454, -19342463128, -3412, 13, -1, -55, 0, -4," +
" 0, 3, 35, -1, -43623431, -8, 0, 19579, -29, 4]");
bigIntegers_intHelper(100,
"[-88557569903630551599799955827784349169626451040329715964314, 202, 60318599134," +
" 1640702634687943479, -61191085979970053457695, 4254037577138942334193887, 12821954296221206544535," +
" -1638087117977, 3, 582, 230, 16168191, 26, 51481126197039749041591204, -71523839508501956928333," +
" 1325372505506602807026564, 3757547800543576, 4364599426705721714," +
" 113847612089673464000064561451248807, -400979282943760427063214761070268927754993666]");
try {
P.withScale(2).bigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(0).bigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
try {
P.withScale(-4).bigIntegers();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
@Ignore
public void testBigIntegers() {
aeqit(take(20, P.bigIntegers()),
"[31289736365, 1332686935725045463947306, -49775, -12910780249752364756422," +
" -23944809563965594065693683811078439336, 0, 320784164," +
" -88557569903630551599799955827784349169626451040329715964314, 202, 60318599134," +
" 1640702634687943479, 30595542989985026728847, -1, -1063509394284735583548472, 1," +
" 12821954296221206544535, 819043558988, -1, 3, 582]");
}
@Test
@Ignore
public void testAsciiCharacters() {
aeq(charsToString(take(100, P.asciiCharacters())),
"PG1~AdF\f;{\13yx\33}\25&A0\26zW\3?\n~\24>\\\rvU9X!=G4*FV:3ByK$$YU\32cE" +
"S\37#\f\32\34\27\16Q\13 \20@p:PN\t\30YDC\f\30Wp,.d72\6}K$*#`4RUYh>IE}");
}
@Test
@Ignore
public void testCharacters() {
aeq(charsToString(take(100, P.characters())),
"\u45d0\uc047\u76b1\uc7fe\u71c1\u3be4\u99c6\ub78c\ue83b\uc7fb\uaa0b\ucc79\u41f8\ub01b\u00fd\u1a95" +
"\u9226\ubb41\uc6b0\u8f96\u907a\u0e57\ufc03\u033f\ud08a\u32fe\u7414\ua5be\u9a5c\u468d\u70f6\u7055" +
"\u3839\u9558\ud7a1\u7c3d\ucdc7\u2634\u2f2a\u63c6\u0c56\ufa3a\udf33\u11c2\u5879\u04cb\u61a4\ua324" +
"\u34d9\u1fd5\u5b9a\u3ee3\u0645\u8053\ud19f\u0823\u850c\u6f1a\ueb1c\u8e97\u6f8e\u49d1\uf90b\u6120" +
"\u5210\u1040\ub3f0\ua6ba\u77d0\u01ce\ue509\ue198\u5959\u0f44\ueec3\u408c\u1c18\u24d7\ue870\u22ac" +
"\uf72e\u9064\u4137\ub132\u9186\u07fd\u1e4b\ub3a4\uad2a\u14a3\ue860\u0234\ub3d2\ue555\ubc59\u3a68" +
"\uf8be\uce49\ub345\u99fd");
}
@Test
@Ignore
public void testPositiveOrdinaryFloats() {
aeqit(take(20, P.positiveOrdinaryFloats()),
"[1.89613015E10, 1.1960635E-14, 3.3527607E-4, 5.655431E-37, 3.614718E-15, 2.0566479E-25," +
" 2.9515041E16, 4.02697717E15, 29027.99, 12970.511, 4.78944453E14, 6.62682E-27, 2.6460455E-35," +
" 66049.98, 8.7866956E17, 5.9178722E-21, 5.2186357E-27, 5.710558E33, 1.7919747E36, 5.174596E-35]");
}
@Test
@Ignore
public void testNegativeOrdinaryFloats() {
aeqit(take(20, P.negativeOrdinaryFloats()),
"[-1.89613015E10, -1.1960635E-14, -3.3527607E-4, -5.655431E-37, -3.614718E-15, -2.0566479E-25," +
" -2.9515041E16, -4.02697717E15, -29027.99, -12970.511, -4.78944453E14, -6.62682E-27," +
" -2.6460455E-35, -66049.98, -8.7866956E17, -5.9178722E-21, -5.2186357E-27, -5.710558E33," +
" -1.7919747E36, -5.174596E-35]");
}
@Test
@Ignore
public void testOrdinaryFloats() {
aeqit(take(20, P.ordinaryFloats()),
"[-1.89613015E10, -1.1960635E-14, -3.3527607E-4, 5.655431E-37, -3.614718E-15, -2.0566479E-25," +
" 2.9515041E16, -4.02697717E15, 29027.99, 12970.511, 4.78944453E14, 6.62682E-27, -2.6460455E-35," +
" -66049.98, -8.7866956E17, -5.9178722E-21, 5.2186357E-27, -5.710558E33, 1.7919747E36, 5.174596E-35]");
}
@Test
@Ignore
public void testFloats() {
aeqit(take(20, P.floats()),
"[-1.89613015E10, -1.1960635E-14, -3.3527607E-4, 5.655431E-37, -3.614718E-15, -2.0566479E-25," +
" 2.9515041E16, -4.02697717E15, 29027.99, 12970.511, 4.78944453E14, 6.62682E-27, -2.6460455E-35," +
" -66049.98, -8.7866956E17, -5.9178722E-21, 5.2186357E-27, -5.710558E33, 1.7919747E36, 5.174596E-35]");
}
@Test
@Ignore
public void testPositiveOrdinaryDoubles() {
aeqit(take(20, P.positiveOrdinaryDoubles()),
"[1.0846552561567438E80, 2.38197354700265E-114, 5.149568405861E-293, 2.4985843477357602E-200," +
" 4.3189997713962425E122, 4.225116780176157E30, 2.860204612775291E-212, 2.8252505782194046E36," +
" 8.566220677325717E-165, 7.422984534814424E267, 3.60536199254296E-277, 1.2019415773498463E252," +
" 4.813417096972919E-51, 1.3135493453396428E-126, 1.4224921830272466E88, 1.4069651251380964E77," +
" 2.1879373410803317E-265, 3.027783021197556E-242, 1.1079692399020062E285, 4.408373100689709E-147]");
}
@Test
@Ignore
public void testNegativeOrdinaryDoubles() {
aeqit(take(20, P.negativeOrdinaryDoubles()),
"[-1.0846552561567438E80, -2.38197354700265E-114, -5.149568405861E-293, -2.4985843477357602E-200," +
" -4.3189997713962425E122, -4.225116780176157E30, -2.860204612775291E-212, -2.8252505782194046E36," +
" -8.566220677325717E-165, -7.422984534814424E267, -3.60536199254296E-277, -1.2019415773498463E252," +
" -4.813417096972919E-51, -1.3135493453396428E-126, -1.4224921830272466E88, -1.4069651251380964E77," +
" -2.1879373410803317E-265, -3.027783021197556E-242, -1.1079692399020062E285," +
" -4.408373100689709E-147]");
}
@Test
@Ignore
public void testOrdinaryDoubles() {
aeqit(take(20, P.ordinaryDoubles()),
"[-1.0846552561567438E80, -2.38197354700265E-114, 5.149568405861E-293, -2.4985843477357602E-200," +
" -4.3189997713962425E122, 4.225116780176157E30, 2.860204612775291E-212, -2.8252505782194046E36," +
" -8.566220677325717E-165, -7.422984534814424E267, 3.60536199254296E-277, 1.2019415773498463E252," +
" 4.813417096972919E-51, 1.3135493453396428E-126, -1.4224921830272466E88, 1.4069651251380964E77," +
" -2.1879373410803317E-265, -3.027783021197556E-242, -1.1079692399020062E285," +
" 4.408373100689709E-147]");
}
@Test
@Ignore
public void testDoubles() {
aeqit(take(20, P.doubles()),
"[-1.0846552561567438E80, -2.38197354700265E-114, 5.149568405861E-293, -2.4985843477357602E-200," +
" -4.3189997713962425E122, 4.225116780176157E30, 2.860204612775291E-212, -2.8252505782194046E36," +
" -8.566220677325717E-165, -7.422984534814424E267, 3.60536199254296E-277, 1.2019415773498463E252," +
" 4.813417096972919E-51, 1.3135493453396428E-126, -1.4224921830272466E88, 1.4069651251380964E77," +
" -2.1879373410803317E-265, -3.027783021197556E-242, -1.1079692399020062E285," +
" 4.408373100689709E-147]");
}
private static double meanOfIntegers(@NotNull Iterable<Integer> xs) {
return sumDouble(map(i -> (double) i / DEFAULT_SAMPLE_SIZE, take(DEFAULT_SAMPLE_SIZE, xs)));
}
}
|
/**
* openecho Java-Pack
*/
package openecho.math;
import java.lang.reflect.Array;
import junit.framework.TestCase;
/**
* Unit Tests for SimpleImmutableMatrixTest.
*
* @author openecho
*/
public class SimpleImmutableMatrixTest extends TestCase {
public SimpleImmutableMatrixTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of getM method, of class SimpleImmutableMatrix.
*/
public void testGetM() {
System.out.println("getM");
int m = (int) Math.random()*100;
int n = (int) Math.random()*100;
Matrix instance = Matrix.random(m, n);
int expResult = m;
int result = instance.getM();
assertEquals(expResult, result);
}
/**
* Test of getN method, of class SimpleImmutableMatrix.
*/
public void testGetN() {
System.out.println("getN");
int m = (int) Math.random()*100;
int n = (int) Math.random()*100;
Matrix instance = Matrix.random(m, n);
int result = instance.getN();
int expResult = n;
assertEquals(expResult, result);
}
/**
* Test of getRow method, of class SimpleImmutableMatrix.
*/
public void testGetRow() {
System.out.println("getRow");
double[][] data = new double[][] {{1,2,3},{3,2,1},{1,2,3}};
int i = 1;
ImmutableMatrix instance = new ImmutableMatrix(data);
double[] expResult = data[1];
double[] result = instance.getRow(i);
for(int j=0;j<Array.getLength(expResult);j++) {
assertEquals(expResult[j], result[j]);
}
}
/**
* Test of getColumn method, of class SimpleImmutableMatrix.
*/
public void testGetColumn() {
System.out.println("getColumn");
double[][] data = new double[][] {{1,2,3},{3,2,1},{1,2,3}};
int i = 1;
ImmutableMatrix instance = new ImmutableMatrix(data);
double[] expResult = new double[] {2,2,2};
double[] result = instance.getColumn(i);
for(int j=0;j<Array.getLength(expResult);j++) {
assertEquals(expResult[j], result[j]);
}
}
/**
* Test of equals method, of class SimpleImmutableMatrix.
*/
public void testEquals() {
System.out.println("equals");
double[][] data = new double[][] {{1,2,3},{3,2,1},{1,2,3}};
Matrix a = Matrix.random(3, 3);
ImmutableMatrix b = new ImmutableMatrix(data);
ImmutableMatrix instance = new ImmutableMatrix(data);
boolean expResult = false;
boolean result = instance.equals(a);
assertEquals(expResult, result);
expResult = true;
result = instance.equals(b);
assertEquals(expResult, result);
}
/**
* Test of add method, of class SimpleImmutableMatrix.
*/
public void testAdd() {
System.out.println("add");
double[][] data = new double[][] {{1,2,3},{3,2,1},{1,2,3}};
ImmutableMatrix b = new ImmutableMatrix(data);
ImmutableMatrix instance = new ImmutableMatrix(data);
data = new double[][] {{2,4,6},{6,4,2},{2,4,6}};
ImmutableMatrix expResult = new ImmutableMatrix(data);
Matrix result = instance.add(b);
assertTrue(expResult.equals(result));
}
/**
* Test of subtract method, of class SimpleImmutableMatrix.
*/
public void testSubtract() {
System.out.println("minus");
double[][] data = new double[][] {{2,4,6},{6,4,2},{2,4,6}};
ImmutableMatrix instance = new ImmutableMatrix(data);
data = new double[][] {{1,2,3},{3,2,1},{1,2,3}};
ImmutableMatrix b = new ImmutableMatrix(data);
ImmutableMatrix expResult = new ImmutableMatrix(data);
Matrix result = instance.subtract(b);
assertTrue(expResult.equals(result));
}
/**
* Test of multiply method, of class SimpleImmutableMatrix.
*/
public void testMultiply() {
System.out.println("multiply");
double[][] data = new double[][] {{1,2,3}};
ImmutableMatrix b = new ImmutableMatrix(data);
System.out.println(b);
data = new double[][] {{4},{5},{6}};
ImmutableMatrix instance = new ImmutableMatrix(data);
System.out.println(instance);
data = new double[][] {{32}};
ImmutableMatrix expResult = new ImmutableMatrix(data);
Matrix result = b.multiply(instance);
System.out.println(result);
assertTrue(expResult.equals(result));
}
/**
* Test of transpose method, of class SimpleImmutableMatrix.
*/
public void testTranspose() {
System.out.println("transpose");
double[][] data = new double[][] {{1,2,3}};
ImmutableMatrix a = new ImmutableMatrix(data);
data = new double[][] {{1},{2},{3}};
ImmutableMatrix expResult = new ImmutableMatrix(data);
Matrix result = ImmutableMatrix.transpose(a);
assertTrue(expResult.equals(result));
}
/**
* Test of identity method, of class SimpleImmutableMatrix.
*/
public void testIdentity() {
System.out.println("identity");
int n = 3;
double[][] data = new double[][] {{1,0,0},{0,1,0},{0,0,1}};
ImmutableMatrix expResult = new ImmutableMatrix(data);;
Matrix result = ImmutableMatrix.identity(n);
assertTrue(expResult.equals(result));
}
/**
* Test of random method, of class SimpleImmutableMatrix.
*/
public void testRandom_int_int() {
System.out.println("random");
int m = 3;
int n = 3;
Matrix result = ImmutableMatrix.random(m, n);
assertEquals(m, result.getM());
assertEquals(n, result.getN());
}
/**
* Test of random method, of class SimpleImmutableMatrix.
*/
public void testRandom_4args() {
System.out.println("random");
int m = 3;
int n = 3;
Matrix result = ImmutableMatrix.random(m, n);
assertEquals(m, result.getM());
assertEquals(n, result.getN());
}
}
|
package osmTileMachine;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GenerateLowZoomLevelAction extends Action{
private TileSet tS;
private String name;
@Override
void runAction(Configuration sessionConfiguration) throws Exception {
// TODO Auto-generated method stub
MessagePrinter.notify(sessionConfiguration, "Generating tiles for lower zoom level: " + name);
tS.tileSetIteratorStart();
Tile t;
while (tS.tileSetIteratorHasNext())
{
t = tS.tileSetIteratorGetTile();
String targetFileName = sessionConfiguration.getTileDirectoryName() + File.separator + t.getFileName();
File targetFile = new File(targetFileName);
targetFile.getParentFile().mkdirs();
Tile source1Tile = t.getNextHigherZoomTile(1);
Tile source2Tile = t.getNextHigherZoomTile(2);
Tile source3Tile = t.getNextHigherZoomTile(3);
Tile source4Tile = t.getNextHigherZoomTile(4);
String source1TileFileName = sessionConfiguration.getTileDirectoryName() + File.separator + source1Tile.getFileName();
String source2TileFileName = sessionConfiguration.getTileDirectoryName() + File.separator + source2Tile.getFileName();
String source3TileFileName = sessionConfiguration.getTileDirectoryName() + File.separator + source3Tile.getFileName();
String source4TileFileName = sessionConfiguration.getTileDirectoryName() + File.separator + source4Tile.getFileName();
File source1File = new File(source1TileFileName);
File source2File = new File(source2TileFileName);
File source3File = new File(source3TileFileName);
File source4File = new File(source4TileFileName);
MessagePrinter.debug(sessionConfiguration, "Tile: " + t.toString());
MessagePrinter.debug(sessionConfiguration, "in1: " + source1File.getCanonicalFile().toString());
MessagePrinter.debug(sessionConfiguration, "in2: " + source2File.getCanonicalFile().toString());
MessagePrinter.debug(sessionConfiguration, "in3: " + source3File.getCanonicalFile().toString());
MessagePrinter.debug(sessionConfiguration, "in4: " + source4File.getCanonicalFile().toString());
MessagePrinter.debug(sessionConfiguration, "out: " + targetFile.getCanonicalFile().toString());
BufferedImage imgQ1 = null;
try {
imgQ1 = ImageIO.read(source1File);
} catch (IOException e) {
}
BufferedImage imgQ2 = null;
try {
imgQ2 = ImageIO.read(source2File);
} catch (IOException e) {
}
BufferedImage imgQ3 = null;
try {
imgQ3 = ImageIO.read(source3File);
} catch (IOException e) {
}
BufferedImage imgQ4 = null;
try {
imgQ4 = ImageIO.read(source4File);
} catch (IOException e) {
}
BufferedImage imgStiched = new BufferedImage(512, 512, BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = imgStiched.getGraphics();
// G.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer)
g.setColor(Color.black);
g.fillRect(0, 0, 512, 512);
g.drawImage(imgQ1, 0, 255, 256, 512, 0, 0, 255, 255, Color.black, null);
g.drawImage(imgQ2, 0, 0, 256, 256, 0, 0, 255, 255, Color.black,null);
g.drawImage(imgQ3, 255, 255, 512, 512, 0, 0, 255, 255, Color.black,null);
g.drawImage(imgQ4, 255, 0, 512, 256, 0, 0, 255, 255, Color.black,null);
imgStiched = scaleWithInstance(imgStiched, 256, 256, Image.SCALE_AREA_AVERAGING);
ImageIO.write(imgStiched, "png", targetFile);
}
}
private static BufferedImage scaleWithInstance(BufferedImage source, int desiredWidth, int desiredHeight, int scaleType){
Image temp1 = source.getScaledInstance(desiredWidth, desiredHeight, scaleType);
BufferedImage image = new BufferedImage(desiredWidth, desiredHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D)image.getGraphics();
g.drawImage(temp1, 0, 0, null);
return image;
}
public GenerateLowZoomLevelAction (TileSet tileSet, String n)
{
tS = tileSet;
name = n;
}
@Override
String getActionInHumanReadableFormat() {
// TODO Auto-generated method stub
return "Generate low zoom level tiles: "+name;
}
}
|
package org.influxdb.impl;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.influxdb.InfluxDB;
import org.influxdb.TestUtils;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ChunkingExceptionTest {
@Test
public void testChunkingIOException() throws IOException, InterruptedException {
testChunkingException(new IOException(), "java.io.IOException");
}
@Test
public void testChunkingEOFException() throws IOException, InterruptedException {
testChunkingException(new EOFException(), "DONE");
}
public void testChunkingException(Exception ex, String message) throws IOException, InterruptedException {
InfluxDBService influxDBService = mock(InfluxDBService.class);
JsonAdapter<QueryResult> adapter = mock(JsonAdapter.class);
Call<ResponseBody> call = mock(Call.class);
ResponseBody responseBody = mock(ResponseBody.class);
when(influxDBService.query(any(String.class), any(String.class), any(String.class), any(String.class), anyInt())).thenReturn(call);
when(responseBody.source()).thenReturn(new Buffer());
doThrow(ex).when(adapter).fromJson(any(JsonReader.class));
String url = "http://" + TestUtils.getInfluxIP() + ":" + TestUtils.getInfluxPORT(true);
InfluxDB influxDB = new InfluxDBImpl(url, "admin", "admin", new OkHttpClient.Builder(), influxDBService, adapter) {
@Override
public String version() {
return "9.99";
}
};
String dbName = "write_unittest_" + System.currentTimeMillis();
final BlockingQueue<QueryResult> queue = new LinkedBlockingQueue<>();
Query query = new Query("SELECT * FROM disk", dbName);
influxDB.query(query, 2, new Consumer<QueryResult>() {
@Override
public void accept(QueryResult result) {
queue.add(result);
}
});
ArgumentCaptor<Callback<ResponseBody>> argumentCaptor = ArgumentCaptor.forClass(Callback.class);
verify(call).enqueue(argumentCaptor.capture());
Callback<ResponseBody> callback = argumentCaptor.getValue();
callback.onResponse(call, Response.success(responseBody));
QueryResult result = queue.poll(20, TimeUnit.SECONDS);
Assert.assertNotNull(result);
Assert.assertEquals(message, result.getError());
}
}
|
package org.java_websocket.issues;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
org.java_websocket.issues.Issue609Test.class,
org.java_websocket.issues.Issue621Test.class,
org.java_websocket.issues.Issue580Test.class,
org.java_websocket.issues.Issue256Test.class,
org.java_websocket.issues.Issue661Test.class
})
/**
* Start all tests for issues
*/
public class AllIssueTests {
}
|
package org.javafunk.funk;
import org.hamcrest.Matchers;
import org.javafunk.funk.functors.Predicate;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.javafunk.funk.Literals.iterable;
import static org.javafunk.funk.Literals.list;
import static org.javafunk.funk.Literals.listWith;
public class EagerlyAnyAllNoneTest {
@Test
public void shouldReturnTrueIfAnyElementsSatisfyThePredicateFunction() {
// Given
List<Integer> inputNumbers = listWith(5, 10, 15, 20);
// When
Boolean result = Eagerly.any(inputNumbers, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 15;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnFalseIfNoElementsSatisfyThePredicateFunction() {
// Given
List<Integer> items = listWith(5, 10, 15, 20);
// When
Boolean result = Eagerly.any(items, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 25;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnFalseForAnyIfTheSuppliedIterableIsEmpty() throws Exception {
// Given
Iterable<String> items = iterable();
// When
Boolean result = Eagerly.any(items, new Predicate<String>(){
@Override public boolean evaluate(String input) {
return input.length() > 5;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnTrueIfAllElementsSatisfyThePredicateFunction() {
// Given
List<String> items = listWith("dog", "cat", "fish", "budgie");
// When
Boolean result = Eagerly.all(items, new Predicate<String>() {
@Override
public boolean evaluate(String item) {
return item.length() > 2;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnTrueIfAnyOfTheElementsDoNotSatisfyThePredicateFunction() {
// Given
List<String> items = listWith("dog", "cat", "fish", "budgie");
// When
Boolean result = Eagerly.all(items, new Predicate<String>() {
@Override
public boolean evaluate(String item) {
return item.length() > 3;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnTrueForAllIfTheSuppliedIterableIsEmpty() {
// Given
List<String> items = list();
// When
Boolean result = Eagerly.all(items, new Predicate<String>() {
@Override
public boolean evaluate(String item) {
return item.length() > 3;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnTrueIfNoneOfTheElementsMatchesThePredicateFunction() {
// Given
List<Integer> items = listWith(1, 3, 5, 7);
// When
Boolean result = Eagerly.none(items, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return isEven(item);
}
private boolean isEven(Integer item) {
return item % 2 == 0;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnFalseIfAnyOfTheElementsMatchesTePredicateFunction() {
// Given
List<Integer> items = listWith(1, 3, 6, 7);
// When
Boolean result = Eagerly.none(items, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return isEven(item);
}
private boolean isEven(Integer item) {
return item % 2 == 0;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnTrueForNoneIfTheSuppliedIterableIsEmpty() throws Exception {
// Given
Iterable<String> items = iterable();
// When
Boolean result = Eagerly.none(items, new Predicate<String>() {
@Override public boolean evaluate(String input) {
return input.length() < 5;
}
});
// Then
assertThat(result, is(result));
}
}
|
package org.fountanio.juancode.out;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Console extends JFrame {
private JTextArea output = new JTextArea("Speed Civilization Console\n");
private JScrollPane sp = new JScrollPane(output);
private JTextField input = new JTextField();
private boolean timeFlag = true;
public Console() {
super("SpeedCivilization Console");
output.setEditable(false);
setLayout(new BorderLayout()); // no gaps needed
add(sp, BorderLayout.CENTER);
add(input, BorderLayout.SOUTH);
setSize(new Dimension(400, 400));
output.setWrapStyleWord(true);
}
/** Allow insertion of time before new line **/
public void insertTimeBeforeOutput(boolean timeFlag) {
this.timeFlag = timeFlag;
}
public void println(String t) {
if (timeFlag)
output.append("\n" + Calendar.getInstance().getTime() + "> " + t);
else
output.append("\n" + t);
}
public void print(String t) {
output.append(t);
}
public void clear() {
output.setText("Speed Civilization Console\n");
}
public void clearInput() {
in = "";
}
private String in = "Could Not Get Input"; // default
public String getInput() {
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
in = input.getText();
}
});
return in;
}
public void errorln(String s) {
if (isVisible()) {
println(s);
} else {
setVisible(true);
println(s);
}
}
}
|
package org.skife.muckery.circuits;
import net.jodah.failsafe.AsyncFailsafe;
import net.jodah.failsafe.CircuitBreaker;
import net.jodah.failsafe.CircuitBreakerOpenException;
import net.jodah.failsafe.Failsafe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class FailsafeTest {
private Service service;
private ScheduledExecutorService clock = Executors.newScheduledThreadPool(2);
@Before
public void setUp() throws Exception {
service = new Service();
}
@After
public void tearDown() throws Exception {
clock.shutdown();
service.close();
}
@Test
public void testFoo() throws Exception {
CircuitBreaker cb = new CircuitBreaker().failOn(RuntimeException.class)
.withDelay(1, TimeUnit.SECONDS)
.withFailureThreshold(1, 1);
AsyncFailsafe<?> fs = Failsafe.with(cb)
.with(clock)
.withFallback(Failsafer.bounce());
CompletableFuture<String> f = fs.future(() -> service.execute(() -> "hello"));
f.get();
assertThat(f).isCompletedWithValue("hello");
f = fs.future(() -> service.execute(() -> {
throw new RuntimeException("NooOoOooO");
}));
assertThatThrownBy(f::get).hasCauseInstanceOf(RuntimeException.class);
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
f = fs.future(() -> service.execute(() -> "yes"));
assertThatThrownBy(f::get).hasCauseInstanceOf(CircuitBreakerOpenException.class);
}
}
|
package ulcrs.controllers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import spark.Request;
import spark.Response;
import ulcrs.models.session.Session;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SessionController.class)
public class SessionControllerTest {
private static final String WORKSPACE_PATH = "../sessions/";
private static final String TEST_WORKSPACE_PATH = "src/test/resources/sessions/";
private SessionController sessionControllerTest;
@Mock
private Request requestMock;
@Mock
private Response responseMock;
private File directoryTest;
private FileReader fileReaderTest;
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
sessionControllerTest = new SessionController();
directoryTest = new File(TEST_WORKSPACE_PATH);
fileReaderTest = new FileReader(TEST_WORKSPACE_PATH + "2.json");
Mockito.when(requestMock.params(Mockito.eq(":name"))).thenReturn("2");
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
.withArguments(Mockito.eq(WORKSPACE_PATH)).thenReturn(directoryTest);
PowerMockito.whenNew(FileReader.class).withParameterTypes(String.class)
.withArguments(Mockito.eq(WORKSPACE_PATH + "2.json")).thenReturn(fileReaderTest);
}
@Test
public void successGetSessionList() throws Exception {
List<String> getSessionListResult = Whitebox.invokeMethod(sessionControllerTest, "getSessionList",
requestMock, responseMock);
PowerMockito.verifyNew(File.class).withArguments(Mockito.eq(WORKSPACE_PATH));
List<String> expectedFilenameList = new ArrayList<>();
expectedFilenameList.add("session_1511824120.json");
expectedFilenameList.add("session_1511824113.json");
expectedFilenameList.add("2.json");
expectedFilenameList.add("1.json");
Assert.assertEquals(expectedFilenameList, getSessionListResult);
}
@Test
public void failGetSession() throws Exception {
Mockito.when(requestMock.params(Mockito.eq(":name"))).thenReturn("3.json");
PowerMockito.whenNew(FileReader.class).withParameterTypes(String.class)
.withArguments(Mockito.eq(WORKSPACE_PATH + "3.json")).thenThrow(new FileNotFoundException());
Session getSessionResult = Whitebox.invokeMethod(sessionControllerTest, "getSession",
requestMock, responseMock);
Assert.assertEquals(null, getSessionResult);
}
@Test
public void successGetSession() throws Exception {
Session getSessionResult = Whitebox.invokeMethod(sessionControllerTest, "getSession",
requestMock, responseMock);
PowerMockito.verifyNew(FileReader.class).withArguments(Mockito.eq(WORKSPACE_PATH + "2.json"));
Assert.assertEquals("2.json", getSessionResult.getName());
}
@Test
public void successSaveSession() throws Exception {
// TODO: implement test case
Assert.assertTrue(true);
// Boolean updateSessionResult = Whitebox.invokeMethod(sessionControllerTest, "saveSession",
// requestMock, responseMock);
// Assert.assertEquals(false, updateSessionResult);
}
@Test
public void successDeleteSession() throws Exception {
// TODO: implement test case
Assert.assertTrue(true);
// Boolean deleteSessionResult = Whitebox.invokeMethod(sessionControllerTest, "deleteSession",
// requestMock, responseMock);
// Assert.assertEquals(false, deleteSessionResult);
}
}
|
package com.puttysoftware.tap.adventure.parser1;
class Commands {
static final char ADVENTURE_FILE_TYPE_ID = '!';
static final char ADVENTURE_FORMAT_VERSION = '^';
static final char ADVENTURE_NAME = '~';
static final char ADVENTURE_SUMMARY = '$';
static final char ADVENTURE_FILE_VERSION = '&';
static final char ADVENTURE_AUTHOR_NAME = '%';
static final char ADVENTURE_AUTHOR_CONTACT = '@';
static final char ADVENTURE_LAST_UPDATED = '*';
static final char ARGUMENT_1 = '1';
static final char ARGUMENT_2 = '2';
static final char ARGUMENT_3 = '3';
static final char ARGUMENT_4 = '4';
static final char ARGUMENT_5 = '5';
static final char ARGUMENT_6 = '6';
static final char ARGUMENT_7 = '7';
static final char ARGUMENT_8 = '8';
static final char ARGUMENT_9 = '9';
static final char ARGUMENT_10 = '0';
static final char CONTINUATION = '/';
static final char FIRST_ROOM_NAME = 'F';
static final char FINAL_ROOM_NAME_HINT = 'f';
static final char ROOM_NAME = 'N';
static final char ROOM_EXIT = 'n';
static final char ROOM_COMMAND = 'C';
static final char ROOM_COMMAND_ONCE = 'c';
static final char ROOM_DESCRIPTION_TEXT = 'D';
static final char ROOM_DESCRIPTION_TEXT_ONCE = 'd';
static final char ROOM_WARP = 'W';
static final char ROOM_WARP_ONCE = 'w';
static final char WIN_GAME = 'K';
static final char LOSE_GAME = 'k';
static final char ADD_PLAYER_OBJECT = 'A';
static final char ADD_ROOM_OBJECT = 'a';
static final char REMOVE_PLAYER_OBJECT = 'R';
static final char REMOVE_ROOM_OBJECT = 'r';
static final char ALTER_STATE_PLAYER_OBJECT = 'L';
static final char ALTER_STATE_ROOM_OBJECT = 'l';
static final char TEST_PRESENCE_PLAYER_OBJECT = 'P';
static final char TEST_PRESENCE_ROOM_OBJECT = 'p';
static final char TEST_STATE_PLAYER_OBJECT = 'S';
static final char TEST_STATE_ROOM_OBJECT = 's';
static final char EQUIP_PLAYER_OBJECT = 'E';
static final char TEST_PRESENCE_EQUIPPED_PLAYER_OBJECT = 'e';
static final char UNEQUIP_PLAYER_OBJECT = 'U';
static final char TEST_STATE_EQUIPPED_PLAYER_OBJECT = 'u';
static final char ALTER_STATE_EQUIPPED_PLAYER_OBJECT = 'Q';
static final char DEFINE_INITIAL_EQUIPPED_PLAYER_OBJECT = 'q';
static final char DEFINE_INITIAL_ROOM_OBJECT = 'O';
static final char DEFINE_INITIAL_PLAYER_OBJECT = 'o';
static final char DEFINE_GLOBAL_COMMAND = 'G';
static final char DEFINE_GLOBAL_COMMAND_ONCE = 'g';
static final char ACTIVATE_GLOBAL_COMMAND = 'V';
static final char DEACTIVATE_GLOBAL_COMMAND = 'v';
static final char DEFINE_BAD_COMMAND_RESPONSE = 'B';
static final char DEFINE_ROOM_BAD_COMMAND_RESPONSE = 'b';
static final char DEFINE_HINT = 'H';
static final char DEFINE_ROOM_HINT = 'h';
static final char JUMP_TO_SUBROUTINE = 'J';
static final char JUMP_TO_SUBROUTINE_ONCE = 'j';
static final char SUBROUTINE_BEGINS = 'M';
static final char SUBROUTINE_ENDS = 'm';
static final char SUCCESS_RETURN_SUBROUTINE = 'T';
static final char FAILURE_RETURN_SUBROUTINE = 't';
static final char BEGIN_QUEST = 'Z';
static final char END_QUEST = 'z';
static final char SET_QUEST_STATUS = 'Y';
static final char TEST_QUEST_STATUS_EQUAL = 'y';
static final char TEST_QUEST_STATUS_GREATER = 'X';
static final char TEST_QUEST_STATUS_LESS = 'x';
static final char INCREMENT_QUEST_STATUS = 'I';
static final char DECREMENT_QUEST_STATUS = 'i';
static final char DEFINE_SYNONYM = '=';
static final char SHOW_INVENTORY = '+';
static final char SHOW_EQUIPMENT = '-';
static final char SHOW_QUEST_STATUS = ':';
static final char SHOW_QUEST_DETAILS = ';';
static final char SHOW_STATISTICS = '_';
// ... other characters here ...
}
|
package de.qualicen.maven.ui_tests;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.sql.Timestamp;
import SpecmatePageClasses.CEGEditorElements;
import SpecmatePageClasses.CommonControlElements;
import SpecmatePageClasses.ProjectExplorerElements;
import SpecmatePageClasses.RequirementOverviewElements;
public class TestModelEditor {
public static void executeTest(WebDriver driver) {
Actions builder = new Actions(driver);
ProjectExplorerElements projectExplorer = new ProjectExplorerElements(driver);
RequirementOverviewElements requirementOverview = new RequirementOverviewElements(driver);
CEGEditorElements cegEditor = new CEGEditorElements(driver, builder);
CommonControlElements commonControl = new CommonControlElements(driver);
// Navigation to requirement
projectExplorer.expand("Evaluation");
projectExplorer.open("Erlaubnis Autofahren");
// Creating and opening new model
String modelName = "Model By Automated UI Test" + new Timestamp(System.currentTimeMillis());
requirementOverview.createModelFromRequirement(modelName);
// Adding nodes to the CEG
WebElement nodeAlter = cegEditor.createNode("Alter", ">17",100,100);//results in x=15, y=60
WebElement nodeFS = cegEditor.createNode("Führerschein", "vorhanden",100,300);//results in x=15, y=27
WebElement nodeAutofahren = cegEditor.createNode("Autofahren", "erlaubt", 300, 200);
// Connecting created nodes
cegEditor.connect(nodeAlter, nodeAutofahren);
cegEditor.connect(nodeFS, nodeAutofahren);
cegEditor.changeTypeToOR(nodeAutofahren);
cegEditor.changeTypeToAND(nodeAutofahren);
// Save CEG
commonControl.save();
// Create test specification
cegEditor.generateTestSpecification();
}
}
|
package com.github.mati1979.play.hysterix.web;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.mati1979.play.hysterix.HysterixContext;
import com.github.mati1979.play.hysterix.event.HysterixStatisticsEvent;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import play.libs.EventSource;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.List;
public class HysterixController extends Controller {
private final HysterixContext hysterixContext;
private List<EventSource> activeEventSources;
public HysterixController(final HysterixContext hysterixContext) {
this.hysterixContext = hysterixContext;
activeEventSources = Lists.newArrayList();
hysterixContext.getEventBus().register(new Subscriber());
}
public Result index() {
final EventSource eventSource = new EventSource() {
@Override
public void onConnected() {
activeEventSources.add(this);
onDisconnected(() -> activeEventSources.remove(this));
}
};
return ok(eventSource);
}
public Result clearActiveEventSources() {
activeEventSources.clear();
return ok(String.valueOf(activeEventSources.size() == 0));
}
private class Subscriber {
@Subscribe
public void onEvent(final HysterixStatisticsEvent event) {
final ObjectNode data = Json.newObject();
data.put("type", "HystrixCommand");
data.put("name", event.getEvent().getHysterixCommand().getCommandKey());
data.put("group", (String) event.getEvent().getHysterixCommand().getCommandGroupKey().orElse(""));
data.put("currentTime", event.getEvent().getCurrentTime());
data.put("errorPercentage", event.getStats().getErrorPercentage());
data.put("isCircuitBreakerOpen", false);
data.put("errorCount", event.getStats().getErrorCount());
data.put("requestCount", event.getStats().getTotalCount());
data.put("rollingCountCollapsedRequests", 0);
data.put("rollingCountExceptionsThrown", event.getStats().getRollingCountExceptionsThrown());
data.put("rollingCountFailure", event.getStats().getRollingCountFailure());
data.put("rollingCountFallbackFailure", event.getStats().getRollingCountFailure());
data.put("rollingCountFallbackRejection", 0);
data.put("rollingCountFallbackSuccess", event.getStats().getRollingCountFallbackSuccess());
data.put("rollingCountResponsesFromCache", event.getStats().getRollingCountResponsesFromCache());
data.put("rollingCountSemaphoreRejected", 0);
data.put("rollingCountShortCircuited", 0);
data.put("rollingCountSuccess", event.getStats().getRollingCountSuccess());
data.put("rollingCountThreadPoolRejected", 0);
data.put("rollingCountTimeout", event.getStats().getRollingTimeoutCount());
data.put("currentConcurrentExecutionCount", 0);
data.put("latencyExecute_mean", event.getStats().getAverageExecutionTime());
final ObjectNode percentiles = Json.newObject();
percentiles.put("0", 0);
percentiles.put("25", 0);
percentiles.put("50", 0);
percentiles.put("75", 0);
percentiles.put("90", 0);
percentiles.put("95", 0);
percentiles.put("99", 0);
percentiles.put("99.5", 0);
percentiles.put("100", 0);
data.put("latencyExecute", percentiles);
data.put("latencyTotal_mean", event.getStats().getAverageExecutionTime());
data.put("latencyTotal", percentiles);
data.put("propertyValue_circuitBreakerRequestVolumeThreshold", 0);
data.put("propertyValue_circuitBreakerSleepWindowInMilliseconds", 0);
data.put("propertyValue_circuitBreakerErrorThresholdPercentage", 0);
data.put("propertyValue_circuitBreakerForceOpen", false);
data.put("propertyValue_circuitBreakerForceClosed", false);
data.put("propertyValue_circuitBreakerEnabled", false);
data.put("propertyValue_executionIsolationStrategy", "THREAD");
data.put("propertyValue_executionIsolationThreadTimeoutInMilliseconds", "2000");
data.put("propertyValue_executionIsolationThreadInterruptOnTimeout", true);
data.putNull("propertyValue_executionIsolationThreadPoolKeyOverride");
data.put("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", 20);
data.put("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", 20);
data.put("propertyValue_metricsRollingStatisticalWindowInMilliseconds", 10000);
data.put("propertyValue_requestCacheEnabled", hysterixContext.getHysterixSettings().isRequestCacheEnabled());
data.put("propertyValue_requestLogEnabled", hysterixContext.getHysterixSettings().isLogRequestStatistics());
data.put("reportingHosts", 1);
activeEventSources.stream().forEach(eventSource -> eventSource.send(EventSource.Event.event(data)));
}
}
}
|
package oap.storage;
import lombok.SneakyThrows;
import oap.concurrent.Threads;
import oap.concurrent.scheduler.PeriodicScheduled;
import oap.concurrent.scheduler.Scheduled;
import oap.concurrent.scheduler.Scheduler;
import oap.io.Files;
import oap.io.IoStreams;
import oap.json.Binder;
import oap.reflect.TypeRef;
import org.slf4j.Logger;
import java.io.Closeable;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static oap.io.IoStreams.DEFAULT_BUFFER;
import static oap.util.Collections.anyMatch;
import static org.slf4j.LoggerFactory.getLogger;
public class FilePersistence<T> implements Closeable, Storage.DataListener<T> {
private static final byte[] BEGIN_ARRAY = "[".getBytes();
private static final byte[] END_ARRAY = "]".getBytes();
private static final byte[] ITEM_SEP = ",".getBytes();
private final long fsync;
private final MemoryStorage<T> storage;
private final Lock lock = new ReentrantLock();
private final Logger log;
private PeriodicScheduled scheduled;
private Path path;
public FilePersistence( Path path, long fsync, MemoryStorage<T> storage ) {
this.path = path;
this.fsync = fsync;
this.storage = storage;
this.log = getLogger( toString() );
}
public void start() {
storage.addDataListener( this );
load();
this.scheduled = Scheduler.scheduleWithFixedDelay( getClass(), fsync, this::fsync );
}
private void load() {
Threads.synchronously( lock, () -> {
Files.ensureFile( path );
if( Files.exists( path ) ) {
Binder.json.unmarshal( new TypeRef<List<Metadata<T>>>() {
}, IoStreams.in( path ) )
.forEach( m -> {
String id = storage.identifier.get( m.object );
storage.data.put( id, m );
} );
}
log.info( storage.data.size() + " object(s) loaded." );
} );
}
@SneakyThrows
private synchronized void fsync( long last ) {
Threads.synchronously( lock, () -> {
log.trace( "fsync: last: {}, storage length: {}", last, storage.data.size() );
if( anyMatch( storage.data.values(), m -> m.modified > last ) ) {
log.debug( "fsync storing {}...", path );
OutputStream out = IoStreams.out( path, IoStreams.Encoding.from( path ), DEFAULT_BUFFER, false, true );
out.write( BEGIN_ARRAY );
Iterator<Metadata<T>> it = storage.data.values().iterator();
while( it.hasNext() ) {
Binder.json.marshal( out, it.next() );
if( it.hasNext() ) out.write( ITEM_SEP );
}
out.write( END_ARRAY );
out.close();
log.debug( "fsync storing {}... done", path );
}
} );
}
@Override
public void close() {
storage.removeDataListener( this );
Threads.synchronously( lock, () -> {
Scheduled.cancel( scheduled );
} );
fsync( scheduled.lastExecuted() );
}
@Override
public String toString() {
return getClass().getSimpleName() + ":" + path;
}
@Override
public void fsync() {
fsync( scheduled.lastExecuted() );
}
}
|
package org.openlca.app.cloud.ui.diff;
import java.util.ArrayList;
import org.openlca.app.cloud.index.Diff;
import org.openlca.app.cloud.index.DiffType;
import org.openlca.cloud.model.data.Dataset;
import org.openlca.cloud.model.data.FetchRequestData;
import org.openlca.core.model.ModelType;
import com.google.gson.JsonObject;
public class DiffResult {
public final FetchRequestData remote;
public final Diff local;
public JsonObject mergedData;
public boolean overwriteLocalChanges;
public boolean overwriteRemoteChanges;
public DiffResult(Diff local, FetchRequestData remote) {
this.local = local != null ? local.copy() : null;
this.remote = remote;
}
public Dataset getDataset() {
if (remote != null)
return toDataset(remote);
return local.getDataset();
}
private Dataset toDataset(FetchRequestData data) {
Dataset dataset = new Dataset();
dataset.categoryType = data.categoryType;
dataset.categoryRefId = data.categoryRefId;
dataset.categories = data.categories != null ? new ArrayList<>(data.categories) : null;
dataset.type = data.type;
dataset.refId = data.refId;
dataset.name = data.name;
dataset.lastChange = data.lastChange;
dataset.version = data.version;
return dataset;
}
public boolean noAction() {
if (local == null && remote == null)
return true;
if (local == null || remote == null)
return false;
if (local.type == DiffType.DELETED)
return remote.isDeleted();
return !remote.isDeleted() && local.getDataset().equals(remote);
}
public boolean conflict() {
if (local == null || remote == null)
return false;
switch (local.type) {
case NEW:
return local.getDataset().type != ModelType.CATEGORY || !local.dataset.equals(remote);
case CHANGED:
return remote.isDeleted() || !local.dataset.equals(remote);
case DELETED:
return remote.isAdded() || !local.dataset.equals(remote);
case NO_DIFF:
return false;
}
return false;
}
void reset() {
overwriteLocalChanges = false;
overwriteRemoteChanges = false;
mergedData = null;
}
@Override
public String toString() {
String l = "null";
if (local != null) {
l = "modelType: " + local.getDataset().type;
l += ", name: " + local.getDataset().name;
l += ", type: " + local.type;
}
String r = "null";
if (remote != null) {
r = "modelType: " + remote.type;
r += ", name: " + remote.name;
}
String text = "local: {" + l + "}, remote: {" + r + "}";
return text;
}
}
|
// This file is part of the "Java-DAP" project, a Java implementation
// of the OPeNDAP Data Access Protocol.
// with or without modification, are permitted provided
// that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// - Neither the name of the OPeNDAP nor the names of its contributors may
// be used to endorse or promote products derived from this software
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package opendap.servlet;
import java.io.*;
import java.util.*;
import java.util.zip.DeflaterOutputStream;
import javax.servlet.*;
import javax.servlet.http.*;
import opendap.dap.*;
import opendap.servers.*;
import opendap.dap.parsers.ParseException;
import opendap.util.Debug;
import ucar.nc2.constants.CDM;
import ucar.nc2.util.EscapeStrings;
/**
* AbstractServlet is the base servlet class for an OPeNDAP
* servers.
* Default handlers for all of the acceptable OPeNDAP client
* requests are here.
* <p/>
* Each of the request handlers appears as an adjunct method to
* the doGet() method of the base servlet class. In order to
* reduce the bulk of this file, many of these methods have been
* in wrapper classes in this package (opendap.servlet).
* <p/>
* This is an abstract class because it is left to the individual
* server development efforts to write the getDDS() and
* getServerVersion() methods. The getDDS() method is intended to
* be where the server specific OPeNDAP server data types are
* used via their associated class factory.
* <p/>
* This code relies on the <code>javax.servlet.ServletConfig</code>
* interface (in particular the <code>getInitParameter()</code> method)
* to record detailed configuration information used by
* the servlet and it's children.
* <p/>
* The servlet should be started in the servlet engine with the following
* initParameters for the tomcat servlet engine:
* <pre>
* <servlet>
* <servlet-name>
* dts
* </servlet-name>
* <servlet-class>
* opendap.servers.test.dts
* </servlet-class>
* <init-param>
* <param-name>INFOcache</param-name>
* <param-value>/home/Datasets/info</param-value>
* </init-param>
* <init-param>
* <param-name>DDScache</param-name>
* <param-value>/home/Datasets/dds</param-value>
* </init-param>
* <init-param>
* <param-name>DAScache</param-name>
* <param-value>/home/Datasets/das</param-value>
* </init-param>
* <init-param>
* <param-name>DDXcache</param-name>
* <param-value>/home/Datasets/ddx</param-value>
* </init-param>
* </servlet>
*
* </pre>
* <p/>
* Obviously the actual values of these parameters will depend on your particular
* file system.
* <h3>See the file <i>SERVLETS</i> in the top level directory of the
* software distribution for more detailed information about servlet
* configuration. </h3>
* Also, the method <code>processDodsURL()</code> could be overloaded
* if some kind of special processing of the incoming request is needed
* to ascertain the OPeNDAP URL information.
*
* @author Nathan David Potter
* @author jcaron 2/7/07 merge changes
* @see opendap.servlet.GetAsciiHandler
* @see opendap.servlet.GetDirHandler
* @see opendap.servlet.GetHTMLInterfaceHandler
* @see opendap.servlet.GetInfoHandler
* @see opendap.servlet.ReqState
* @see opendap.servlet.ParsedRequest
* @see opendap.servlet.GuardedDataset
*/
public abstract class AbstractServlet extends javax.servlet.http.HttpServlet {
// Statics
static final boolean debug = false;
// Define an overall logger for everyone to use
// Start with a default logger, but allow an application to change it later
static public org.slf4j.Logger log
= org.slf4j.LoggerFactory.getLogger(AbstractServlet.class);
static public void setLog(Class cl) {
log = org.slf4j.LoggerFactory.getLogger(cl);
}
static public void printDODSException(opendap.dap.DAP2Exception de) {
de.printStackTrace();
}
static public void printThrowable(Throwable t) {
AbstractServlet.log.error(t.getMessage());
t.printStackTrace();
}
protected boolean allowDeflate = true;
private boolean track = false;
private Object syncLock = new Object();
private int HitCounter = 0;
/**
* Keep a copy of the servlet config
*/
//private ServletConfig servletConfig = null;
/**
* Keep a copy of the servlet context
*/
//private ServletContext servletContext = null;
/**
* path to the root of the servlet in tomcat webapps directory
*/
protected String rootpath = "";
// Constructor(s)
public AbstractServlet() {
}
protected void setRootpath(String rootPath) {
this.rootpath = rootPath;
}
// Get/Set
/**
* Getter function for rootpath
*
* @return rootpath
*
public String getRootPath() {
return rootpath;
} */
/**
* This function must be implemented locally for each OPeNDAP server. It should
* return a String containing the OPeNDAP Server Version...
*
* @return The Server Version String
*/
public abstract String getServerVersion();
protected abstract opendap.servlet.GuardedDataset getDataset(opendap.servlet.ReqState rs)
throws Exception;
/* public void init() throws ServletException {
super.init();
// debuggering
String debugOn = getInitParameter("DebugOn");
if (debugOn != null) {
StringTokenizer toker = new StringTokenizer(debugOn);
while (toker.hasMoreTokens())
Debug.set(toker.nextToken(), true);
}
servletConfig = this.getServletConfig();
servletContext = servletConfig.getServletContext();
rootpath = servletContext.getRealPath("/");
} */
public void parseExceptionHandler(ParseException pe, HttpServletResponse response) {
log.error("DODSServlet.parseExceptionHandler", pe);
if (Debug.isSet("showException")) {
log.debug(pe.toString());
pe.printStackTrace();
printThrowable(pe);
}
//LogStream.out.println(pe);
//pe.printStackTrace(LogStream.out);
try {
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
// response.setContentType("text/plain"); LOOK do we needLogStream.out
// Strip any double quotes out of the parser error message.
// These get stuck in auto-magically by the javacc generated parser
// code and they break our error parser (bummer!)
String msg = pe.getMessage().replace('\"', '\'');
DAP2Exception de2 = new DAP2Exception(opendap.dap.DAP2Exception.CANNOT_READ_FILE, msg);
de2.print(eOut);
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
}
public void dap2ExceptionHandler(DAP2Exception de, HttpServletResponse response) {
log.info("DODSServlet.dodsExceptionHandler (" + de.getErrorCode() + ") " + de.getErrorMessage());
if (Debug.isSet("showException")) {
de.print(System.err);
de.printStackTrace(System.err);
printDODSException(de);
}
try {
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
de.print(eOut);
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
}
public void IOExceptionHandler(IOException e, ReqState rs) {
HttpServletResponse response = rs.getResponse();
try {
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
// Strip any double quotes out of the parser error message.
// These get stuck in auto-magically by the javacc generated parser
// code and they break our error parser (bummer!)
String msg = e.getMessage();
if (msg != null)
msg = msg.replace('\"', '\'');
DAP2Exception de2 = new DAP2Exception(opendap.dap.DAP2Exception.CANNOT_READ_FILE, msg);
de2.print(eOut);
if (Debug.isSet("showException")) {
// Error message
log.error("DODServlet ERROR (IOExceptionHandler): " + e);
log.error(rs.toString());
if (track) {
RequestDebug reqD = (RequestDebug) rs.getUserObject();
log.error(" request number: " + reqD.reqno + " thread: " + reqD.threadDesc);
}
e.printStackTrace();
printThrowable(e);
}
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
}
public void anyExceptionHandler(Throwable e, ReqState rs) {
HttpServletResponse response = rs.getResponse();
try {
log.error("DODServlet ERROR (anyExceptionHandler): " + e);
log.error(rs.toString());
if (track) {
RequestDebug reqD = (RequestDebug) rs.getUserObject();
log.error(" request number: " + reqD.reqno + " thread: " + reqD.threadDesc);
}
e.printStackTrace();
printThrowable(e);
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
// Strip any double quotes out of the parser error message.
// These get stuck in auto-magically by the javacc generated parser
// code and they break our error parser (bummer!)
String msg = e.getMessage();
if (msg != null)
msg = msg.replace('\"', '\'');
DAP2Exception de2 = new DAP2Exception(opendap.dap.DAP2Exception.UNDEFINED_ERROR, msg);
de2.print(eOut);
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
}
public void sendDODSError(HttpServletRequest request,
HttpServletResponse response,
String clientMsg,
String serverMsg)
throws IOException, ServletException {
response.setContentType("text/plain");
response.setHeader("XDODS-Server", getServerVersion());
response.setHeader("Content-Description", "dods-error");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "none");
ServletOutputStream Out = response.getOutputStream();
DAP2Exception de = new DAP2Exception(opendap.dap.DAP2Exception.UNKNOWN_ERROR, clientMsg);
de.print(Out);
response.setStatus(HttpServletResponse.SC_OK);
log.error(serverMsg);
}
public void doGetDAS(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("doGetDAS for dataset: " + rs.getDataSet());
}
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (ds == null) return;
rs.getResponse().setContentType("text/plain");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-das");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
OutputStream Out = new BufferedOutputStream(rs.getResponse().getOutputStream());
DAS myDAS = ds.getDAS();
myDAS.print(Out);
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
if (Debug.isSet("showResponse")) {
//log.debug("DAS=\n");
//myDAS.print(LogStream.out);
}
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetDDS(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse"))
log.debug("doGetDDS for dataset: " + rs.getDataSet());
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (null == ds) return;
rs.getResponse().setContentType("text/plain");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
OutputStream Out = new BufferedOutputStream(rs.getResponse().getOutputStream());
// Utilize the getDDS() method to get a parsed and populated DDS
// for this server.
ServerDDS myDDS = ds.getDDS();
if (rs.getConstraintExpression().equals("")) { // No Constraint Expression?
// Send the whole DDS
myDDS.print(Out);
Out.flush();
} else { // Otherwise, send the constrained DDS
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator(myDDS);
ce.parseConstraint(rs);
// Send the constrained DDS back to the client
PrintWriter pw = new PrintWriter(new OutputStreamWriter(Out, Util.UTF8));
myDDS.printConstrained(pw);
pw.flush();
}
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
if (Debug.isSet("showResponse")) {
if (rs.getConstraintExpression().equals("")) { // No Constraint Expression?
log.debug("Unconstrained DDS=\n");
//myDDS.print();
} else {
log.debug("Constrained DDS=\n");
//myDDS.printConstrained();
}
}
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException pe) {
IOExceptionHandler(pe, rs);
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetDDX(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse"))
log.debug("doGetDDX for dataset: " + rs.getDataSet());
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (null == ds) return;
rs.getResponse().setContentType("text/plain");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-ddx");
// Commented because of a bug in the OPeNDAP C++ stuff...
// rs.getResponse().setHeader("Content-Encoding", "plain");
OutputStream Out = new BufferedOutputStream(rs.getResponse().getOutputStream());
// Utilize the getDDS() method to get a parsed and populated DDS
// for this server.
ServerDDS myDDS = ds.getDDS();
if (rs.getConstraintExpression().equals("")) { // No Constraint Expression?
// Send the whole DDS
myDDS.printXML(Out);
Out.flush();
} else { // Otherwise, send the constrained DDS
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator(myDDS);
ce.parseConstraint(rs);
// Send the constrained DDS back to the client
PrintWriter pw = new PrintWriter(new OutputStreamWriter(Out, Util.UTF8));
myDDS.printConstrainedXML(pw);
pw.flush();
}
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
if (Debug.isSet("showResponse")) {
if (rs.getConstraintExpression().equals("")) { // No Constraint Expression?
log.debug("Unconstrained DDX=\n");
myDDS.printXML(System.out);
} else {
log.debug("Constrained DDX=\n");
myDDS.printConstrainedXML(System.out);
}
}
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException pe) {
IOExceptionHandler(pe, rs);
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetBLOB(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("doGetBLOB For: " + rs.getDataSet());
}
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (null == ds) return;
rs.getResponse().setContentType("application/octet-stream");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-blob");
ServletOutputStream sOut = rs.getResponse().getOutputStream();
OutputStream bOut;
DeflaterOutputStream dOut = null;
if (rs.getAcceptsCompressed() && allowDeflate) {
rs.getResponse().setHeader("Content-Encoding", "deflate");
dOut = new DeflaterOutputStream(sOut);
bOut = new BufferedOutputStream(dOut);
} else {
// Commented out because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
bOut = new BufferedOutputStream(sOut);
}
// Utilize the getDDS() method to get a parsed and populated DDS
// for this server.
ServerDDS myDDS = ds.getDDS();
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator(myDDS);
ce.parseConstraint(rs.getConstraintExpression(), rs.getRequestURL().toString());
// Send the binary data back to the client
DataOutputStream sink = new DataOutputStream(bOut);
ce.send(myDDS.getEncodedName(), sink, ds);
sink.flush();
// Finish up sending the compressed stuff, but don't
// close the stream (who knows what the Servlet may expect!)
if (null != dOut)
dOut.finish();
bOut.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException ioe) {
IOExceptionHandler(ioe, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetDAP2Data(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("doGetDAP2Data For: " + rs.getDataSet());
}
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (null == ds) return;
rs.getResponse().setContentType("application/octet-stream");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-data");
ServletOutputStream sOut = rs.getResponse().getOutputStream();
OutputStream bOut;
DeflaterOutputStream dOut = null;
if (rs.getAcceptsCompressed() && allowDeflate) {
rs.getResponse().setHeader("Content-Encoding", "deflate");
dOut = new DeflaterOutputStream(sOut);
bOut = new BufferedOutputStream(dOut);
} else {
// Commented out because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
bOut = new BufferedOutputStream(sOut);
}
// Utilize the getDDS() method to get a parsed and populated DDS
// for this server.
ServerDDS myDDS = ds.getDDS();
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator(myDDS);
ce.parseConstraint(rs);
// debug
//log.debug("CE DDS = ");
// myDDS.printConstrained(LogStream.out);
// Send the constrained DDS back to the client
PrintWriter pw = new PrintWriter(new OutputStreamWriter(bOut, Util.UTF8));
myDDS.printConstrained(pw);
// Send the Data delimiter back to the client
//pw.println("Data:"); // JCARON CHANGED
pw.flush();
bOut.write("\nData:\n".getBytes(CDM.utf8Charset)); // JCARON CHANGED
bOut.flush();
// Send the binary data back to the client
DataOutputStream sink = new DataOutputStream(bOut);
ce.send(myDDS.getEncodedName(), sink, ds);
sink.flush();
// Finish up tsending the compressed stuff, but don't
// close the stream (who knows what the Servlet may expect!)
if (null != dOut)
dOut.finish();
bOut.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException ioe) {
IOExceptionHandler(ioe, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetDIR(ReqState rs)
throws Exception {
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods-directory");
try {
GetDirHandler di = new GetDirHandler();
di.sendDIR(rs);
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (Throwable t) {
anyExceptionHandler(t, rs);
}
}
public void doGetVER(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("Sending Version Tag.");
}
rs.getResponse().setContentType("text/plain");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-version");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
pw.println("Server Version: " + getServerVersion());
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
public void doGetHELP(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("Sending Help Page.");
}
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-help");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
printHelpPage(pw);
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
public void badURL(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("Sending Bad URL Page.");
}
//log.info("DODSServlet.badURL " + rs.getRequest().getRequestURI());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setHeader("Content-Description", "dods-error");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
printBadURLPage(pw);
printHelpPage(pw);
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
public void doGetASC(ReqState rs) throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("doGetASC For: " + rs.getDataSet());
}
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (ds == null) return;
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/plain");
rs.getResponse().setHeader("Content-Description", "dods-ascii");
if (debug)
log.debug("Sending OPeNDAP ASCII Data For: " + rs + " CE: '" + rs.getConstraintExpression() + "'");
ServerDDS dds = ds.getDDS();
//dds = url.getData(ce, null, new asciiFactory()); previous way
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator(dds);
// i think this makes the dds constrained
ce.parseConstraint(rs);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
dds.printConstrained(pw);
pw.println("
AsciiWriter writer = new AsciiWriter(); // could be static
writer.toASCII(pw, dds, ds);
// the way that getDAP2Data works
// DataOutputStream sink = new DataOutputStream(bOut);
// ce.send(myDDS.getName(), sink, ds);
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetINFO(ReqState rs)
throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("doGetINFO For: " + rs.getDataSet());
}
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (null == ds) return;
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods-description");
GetInfoHandler di = new GetInfoHandler();
di.sendINFO(pw, ds, rs);
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException pe) {
IOExceptionHandler(pe, rs);
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetHTML(ReqState rs)
throws Exception {
GuardedDataset ds = null;
try {
ds = getDataset(rs);
if (ds == null) return;
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods-form");
// Utilize the getDDS() method to get a parsed and populated DDS
// for this server.
ServerDDS myDDS = ds.getDDS();
DAS das = ds.getDAS();
GetHTMLInterfaceHandler di = new GetHTMLInterfaceHandler();
di.sendDataRequestForm(rs, rs.getDataSet(), myDDS, das);
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} catch (ParseException pe) {
parseExceptionHandler(pe, rs.getResponse());
} catch (DAP2Exception de) {
dap2ExceptionHandler(de, rs.getResponse());
} catch (IOException pe) {
IOExceptionHandler(pe, rs);
} catch (Throwable t) {
anyExceptionHandler(t, rs);
} finally { // release lock if needed
if (ds != null) ds.release();
}
}
public void doGetCatalog(ReqState rs)
throws Exception {
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/xml");
rs.getResponse().setHeader("Content-Description", "dods-catalog");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
printCatalog(rs, pw);
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
// to be overridden by servers that implement catalogs
protected void printCatalog(ReqState rs, PrintWriter os) throws IOException {
os.println("Catalog not available for this server");
os.println("Server version = " + getServerVersion());
}
public void doDebug(ReqState rs) throws IOException {
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods_debug");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
pw.println("<title>Debugging</title>");
pw.println("<body><pre>");
StringTokenizer tz = new StringTokenizer(rs.getConstraintExpression(), "=;");
while (tz.hasMoreTokens()) {
String cmd = tz.nextToken();
pw.println("Cmd= " + cmd);
if (cmd.equals("help")) {
pw.println(" help;log;logEnd;logShow");
pw.println(" showFlags;showInitParameters;showRequest");
pw.println(" on|off=(flagName)");
doDebugCmd(cmd, tz, pw); // for subclasses
} else if (cmd.equals("on"))
Debug.set(tz.nextToken(), true);
else if (cmd.equals("off"))
Debug.set(tz.nextToken(), false);
else if (cmd.equals("showFlags")) {
Iterator iter = Debug.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
pw.println(" " + key + " " + Debug.isSet(key));
}
} else if (cmd.equals("showInitParameters"))
pw.println(rs.toString());
else if (cmd.equals("showRequest"))
probeRequest(pw, rs);
else if (!doDebugCmd(cmd, tz, pw)) { // for subclasses
pw.println(" unrecognized command");
}
}
pw.println("
pw.println("Logging is on");
Iterator iter = Debug.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
boolean val = Debug.isSet(key);
if (val)
pw.println(" " + key + " " + Debug.isSet(key));
}
pw.println("</pre></body>");
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
protected boolean doDebugCmd(String cmd, StringTokenizer tz, PrintWriter pw) {
return false;
}
public void doGetSystemProps(ReqState rs)
throws Exception {
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods-status");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
pw.println("<html>");
pw.println("<title>System Properties</title>");
pw.println("<hr>");
pw.println("<body><h2>System Properties</h2>");
pw.println("<h3>Date: " + new Date() + "</h3>");
Properties sysp = System.getProperties();
Enumeration e = sysp.propertyNames();
pw.println("<ul>");
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = System.getProperty(name);
pw.println("<li>" + name + ": " + value + "</li>");
}
pw.println("</ul>");
pw.println("<h3>Runtime Info:</h3>");
Runtime rt = Runtime.getRuntime();
pw.println("JVM Max Memory: " + (rt.maxMemory() / 1024) / 1000. + " MB (JVM Maximum Allowable Heap)<br>");
pw.println("JVM Total Memory: " + (rt.totalMemory() / 1024) / 1000. + " MB (JVM Heap size)<br>");
pw.println("JVM Free Memory: " + (rt.freeMemory() / 1024) / 1000. + " MB (Unused part of heap)<br>");
pw.println("JVM Used Memory: " + ((rt.totalMemory() - rt.freeMemory()) / 1024) / 1000. + " MB (Currently active memory)<br>");
pw.println("<hr>");
pw.println("</body>");
pw.println("</html>");
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
public void doGetStatus(ReqState rs)
throws Exception {
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/html");
rs.getResponse().setHeader("Content-Description", "dods-status");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
pw.println("<title>Server Status</title>");
pw.println("<body><ul>");
printStatus(pw);
pw.println("</ul></body>");
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
}
// to be overridden by servers that implement status report
protected void printStatus(PrintWriter os) throws IOException {
os.println("<h2>Server version = " + getServerVersion() + "</h2>");
os.println("<h2>Number of Requests Received = " + HitCounter + "</h2>");
if (track) {
int n = prArr.size();
int pending = 0;
StringBuilder preqs = new StringBuilder();
for (int i = 0; i < n; i++) {
ReqState rs = (ReqState) prArr.get(i);
RequestDebug reqD = (RequestDebug) rs.getUserObject();
if (!reqD.done) {
preqs.append("<pre>
preqs.append("Request[");
preqs.append(reqD.reqno);
preqs.append("](");
preqs.append(reqD.threadDesc);
preqs.append(") is pending.\n");
preqs.append(rs.toString());
preqs.append("</pre>");
pending++;
}
}
os.println("<h2>" + pending + " Pending Request(s)</h2>");
os.println(preqs.toString());
}
}
public void probeRequest(PrintWriter ps, ReqState rs) {
Enumeration e;
int i;
ps.println("
ps.println("The HttpServletRequest object is actually a: " + rs.getRequest().getClass().getName());
ps.println("");
ps.println("HttpServletRequest Interface:");
ps.println(" getAuthType: " + rs.getRequest().getAuthType());
ps.println(" getMethod: " + rs.getRequest().getMethod());
ps.println(" getPathInfo: " + rs.getRequest().getPathInfo());
ps.println(" getPathTranslated: " + rs.getRequest().getPathTranslated());
ps.println(" getRequestURL: " + rs.getRequest().getRequestURL());
ps.println(" getQueryString: " + rs.getRequest().getQueryString());
ps.println(" getRemoteUser: " + rs.getRequest().getRemoteUser());
ps.println(" getRequestedSessionId: " + rs.getRequest().getRequestedSessionId());
ps.println(" getRequestURI: " + rs.getRequest().getRequestURI());
ps.println(" getServletPath: " + rs.getRequest().getServletPath());
ps.println(" isRequestedSessionIdFromCookie: " + rs.getRequest().isRequestedSessionIdFromCookie());
ps.println(" isRequestedSessionIdValid: " + rs.getRequest().isRequestedSessionIdValid());
ps.println(" isRequestedSessionIdFromURL: " + rs.getRequest().isRequestedSessionIdFromURL());
ps.println("");
i = 0;
e = rs.getRequest().getHeaderNames();
ps.println(" Header Names:");
while (e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Header[" + i + "]: " + s);
ps.println(": " + rs.getRequest().getHeader(s));
}
ps.println("");
ps.println("ServletRequest Interface:");
ps.println(" getCharacterEncoding: " + rs.getRequest().getCharacterEncoding());
ps.println(" getContentType: " + rs.getRequest().getContentType());
ps.println(" getContentLength: " + rs.getRequest().getContentLength());
ps.println(" getProtocol: " + rs.getRequest().getProtocol());
ps.println(" getScheme: " + rs.getRequest().getScheme());
ps.println(" getServerName: " + rs.getRequest().getServerName());
ps.println(" getServerPort: " + rs.getRequest().getServerPort());
ps.println(" getRemoteAddr: " + rs.getRequest().getRemoteAddr());
ps.println(" getRemoteHost: " + rs.getRequest().getRemoteHost());
//ps.println(" getRealPath: "+rs.getRequest().getRealPath());
ps.println(".............................");
ps.println("");
i = 0;
e = rs.getRequest().getAttributeNames();
ps.println(" Attribute Names:");
while (e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s);
ps.println(" Type: " + rs.getRequest().getAttribute(s));
}
ps.println(".............................");
ps.println("");
i = 0;
e = rs.getRequest().getParameterNames();
ps.println(" Parameter Names:");
while (e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Parameter[" + i + "]: " + s);
ps.println(" Value: " + rs.getRequest().getParameter(s));
}
ps.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
ps.println(" . . . . . . . . . Servlet Infomation API . . . . . . . . . . . . . .");
ps.println("");
ps.println("Servlet Context:");
ps.println("");
/* i = 0;
e = servletContext.getAttributeNames();
ps.println(" Attribute Names:");
while (e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s);
ps.println(" Type: " + servletContext.getAttribute(s));
}
ps.println(" ServletContext.getRealPath(\".\"): " + servletContext.getRealPath("."));
ps.println(" ServletContext.getMajorVersion(): " + servletContext.getMajorVersion());
// ps.println("ServletContext.getMimeType(): " + sc.getMimeType());
ps.println(" ServletContext.getMinorVersion(): " + servletContext.getMinorVersion());
// ps.println("ServletContext.getRealPath(): " + sc.getRealPath()); */
ps.println(".............................");
ps.println("Servlet Config:");
ps.println("");
ServletConfig scnfg = getServletConfig();
i = 0;
e = scnfg.getInitParameterNames();
ps.println(" InitParameters:");
while (e.hasMoreElements()) {
String p = (String) e.nextElement();
ps.print(" InitParameter[" + i + "]: " + p);
ps.println(" Value: " + scnfg.getInitParameter(p));
i++;
}
ps.println("");
ps.println("
ps.println("");
}
public String getServerName() {
// Ascertain the name of this server.
String servletName = this.getClass().getName();
return (servletName);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
// setHeader("Last-Modified", (new Date()).toString() );
boolean isDebug = false;
ReqState rs = null;
RequestDebug reqD = null;
try {
rs = getRequestState(request, response);
if (rs != null) {
if (Debug.isSet("probeRequest")) {
probeRequest(new PrintWriter(new OutputStreamWriter(System.out, Util.UTF8), true), rs);
}
String ds = rs.getDataSet();
String suff = rs.getRequestSuffix();
isDebug = ((ds != null) && ds.equals("debug") && (suff != null) && suff.equals(""));
}
synchronized (syncLock) {
if (!isDebug) {
long reqno = HitCounter++;
if (track) {
reqD = new RequestDebug(reqno, Thread.currentThread().toString());
rs.setUserObject(reqD);
if (prArr == null) prArr = new ArrayList(10000);
prArr.add((int) reqno, rs);
}
if (Debug.isSet("showRequest")) {
log.debug("
log.debug("Server: " + getServerName() + " Request #" + reqno);
log.debug("Client: " + rs.getRequest().getRemoteHost());
log.debug(rs.toString());
log.debug("Request dataset: '" + rs.getDataSet() + "' suffix: '" + rs.getRequestSuffix() +
"' CE: '" + rs.getConstraintExpression() + "'");
}
}
} // synch
if (rs != null) {
String dataSet = rs.getDataSet();
String requestSuffix = rs.getRequestSuffix();
if (dataSet == null) {
doGetDIR(rs);
} else if (dataSet.equals("/")) {
doGetDIR(rs);
} else if (dataSet.equals("")) {
doGetDIR(rs);
} else if (dataSet.equalsIgnoreCase("/version") || dataSet.equalsIgnoreCase("/version/")) {
doGetVER(rs);
} else if (dataSet.equalsIgnoreCase("/help") || dataSet.equalsIgnoreCase("/help/")) {
doGetHELP(rs);
} else if (dataSet.equalsIgnoreCase("/" + requestSuffix)) {
doGetHELP(rs);
} else if (requestSuffix.equalsIgnoreCase("dds")) {
doGetDDS(rs);
} else if (requestSuffix.equalsIgnoreCase("das")) {
doGetDAS(rs);
} else if (requestSuffix.equalsIgnoreCase("ddx")) {
doGetDDX(rs);
} else if (requestSuffix.equalsIgnoreCase("blob")) {
doGetBLOB(rs);
} else if (requestSuffix.equalsIgnoreCase("dods")) {
doGetDAP2Data(rs);
} else if (requestSuffix.equalsIgnoreCase("asc") ||
requestSuffix.equalsIgnoreCase("ascii")) {
doGetASC(rs);
} else if (requestSuffix.equalsIgnoreCase("info")) {
doGetINFO(rs);
} else if (requestSuffix.equalsIgnoreCase("html") || requestSuffix.equalsIgnoreCase("htm")) {
doGetHTML(rs);
} else if (requestSuffix.equalsIgnoreCase("ver") || requestSuffix.equalsIgnoreCase("version")) {
doGetVER(rs);
} else if (requestSuffix.equalsIgnoreCase("help")) {
doGetHELP(rs);
/* JC added
} else if (dataSet.equalsIgnoreCase("catalog") && requestSuffix.equalsIgnoreCase("xml")) {
doGetCatalog(rs);
} else if (dataSet.equalsIgnoreCase("status")) {
doGetStatus(rs);
} else if (dataSet.equalsIgnoreCase("systemproperties")) {
doGetSystemProps(rs);
} else if (isDebug) {
doDebug(rs); */
} else if (requestSuffix.equals("")) {
badURL(rs);
} else {
badURL(rs);
}
} else {
badURL(rs);
}
if (reqD != null) reqD.done = true;
} catch (Throwable e) {
anyExceptionHandler(e, rs);
}
}
/**
* @param request
* @return the request state
*/
protected ReqState getRequestState(HttpServletRequest request, HttpServletResponse response) {
ReqState rs = null;
// The url and query strings will come to us in encoded form
// (see HTTPmethod.newMethod())
String baseurl = request.getRequestURL().toString();
baseurl = EscapeStrings.unescapeURL(baseurl);
String query = request.getQueryString();
query = EscapeStrings.unescapeURLQuery(query);
try {
rs = new ReqState(request, response, rootpath, getServerName(), baseurl, query);
} catch (Exception bue) {
rs = null;
}
return rs;
}
private void printHelpPage(PrintWriter pw) {
pw.println("<h3>OPeNDAP Server Help</h3>");
pw.println("To access most of the features of this OPeNDAP server, append");
pw.println("one of the following a eight suffixes to a URL: .das, .dds, .dods, .ddx, .blob, .info,");
pw.println(".ver or .help. Using these suffixes, you can ask this server for:");
pw.println("<dl>");
pw.println("<dt> das </dt> <dd> Dataset Attribute Structure (DAS)</dd>");
pw.println("<dt> dds </dt> <dd> Dataset Descriptor Structure (DDS)</dd>");
pw.println("<dt> dods </dt> <dd> DataDDS object (A constrained DDS populated with data)</dd>");
pw.println("<dt> ddx </dt> <dd> XML version of the DDS/DAS</dd>");
pw.println("<dt> blob </dt> <dd> Serialized binary data content for requested data set, " +
"with the constraint expression applied.</dd>");
pw.println("<dt> info </dt> <dd> info object (attributes, types and other information)</dd>");
pw.println("<dt> html </dt> <dd> html form for this dataset</dd>");
pw.println("<dt> ver </dt> <dd> return the version number of the server</dd>");
pw.println("<dt> help </dt> <dd> help information (this text)</dd>");
pw.println("</dl>");
pw.println("For example, to request the DAS object from the FNOC1 dataset at URI/GSO (a");
pw.println("test dataset) you would appand `.das' to the URL:");
pw.println("http://opendap.gso.url.edu/cgi-bin/nph-nc/data/fnoc1.nc.das.");
pw.println("<p><b>Note</b>: Many OPeNDAP clients supply these extensions for you so you don't");
pw.println("need to append them (for example when using interfaces supplied by us or");
pw.println("software re-linked with a OPeNDAP client-library). Generally, you only need to");
pw.println("add these if you are typing a URL directly into a WWW browser.");
pw.println("<p><b>Note</b>: If you would like version information for this server but");
pw.println("don't know a specific data file or data set name, use `/version' for the");
pw.println("filename. For example: http://opendap.gso.url.edu/cgi-bin/nph-nc/version will");
pw.println("return the version number for the netCDF server used in the first example. ");
pw.println("<p><b>Suggestion</b>: If you're typing this URL into a WWW browser and");
pw.println("would like information about the dataset, use the `.info' extension.");
pw.println("<p>If you'd like to see a data values, use the `.html' extension and submit a");
pw.println("query using the customized form.");
}
private void printBadURLPage(PrintWriter pw) {
pw.println("<h3>Error in URL</h3>");
pw.println("The URL extension did not match any that are known by this");
pw.println("server. Below is a list of the five extensions that are be recognized by");
pw.println("all OPeNDAP servers. If you think that the server is broken (that the URL you");
pw.println("submitted should have worked), then please contact the");
pw.println("OPeNDAP user support coordinator at: ");
pw.println("<a href=\"mailto:[email protected]\">[email protected]</a><p>");
}
|
package step.functions;
import java.util.Map;
import javax.json.JsonObject;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import step.core.accessors.AbstractOrganizableObject;
import step.core.dynamicbeans.DynamicValue;
/**
* This class encapsulates all the configuration parameters of functions (aka Keywords)
* which can also be defined on the configuration dialog of Keywords in the UI
*
*/
@JsonTypeInfo(use=Id.CLASS,property="type")
public class Function extends AbstractOrganizableObject {
protected DynamicValue<Integer> callTimeout = new DynamicValue<>(180000);
protected JsonObject schema;
protected boolean executeLocally;
protected Map<String, String> tokenSelectionCriteria;
protected boolean managed;
protected boolean useCustomTemplate=false;
protected String htmlTemplate;
public Map<String, String> getTokenSelectionCriteria() {
return tokenSelectionCriteria;
}
/**
* Defines additional selection criteria of agent token on which the function should be executed
*
* @param tokenSelectionCriteria a map containing the additional selection criteria as key-value pairs
*/
public void setTokenSelectionCriteria(Map<String, String> tokenSelectionCriteria) {
this.tokenSelectionCriteria = tokenSelectionCriteria;
}
/**
* @return if the function has to be executed on a local token
*/
public boolean isExecuteLocally() {
return executeLocally;
}
/**
* Defines if the function has to be executed on a local token
*
* @param executeLocally
*/
public void setExecuteLocally(boolean executeLocally) {
this.executeLocally = executeLocally;
}
public DynamicValue<Integer> getCallTimeout() {
return callTimeout;
}
/**
* @param callTimeout the call timeout of the function in ms
*/
public void setCallTimeout(DynamicValue<Integer> callTimeout) {
this.callTimeout = callTimeout;
}
public JsonObject getSchema() {
return schema;
}
public void setSchema(JsonObject schema) {
this.schema = schema;
}
public boolean requiresLocalExecution() {
return executeLocally;
}
public boolean isManaged() {
return managed;
}
public void setManaged(boolean managed) {
this.managed = managed;
}
public boolean isUseCustomTemplate() {
return useCustomTemplate;
}
public void setUseCustomTemplate(boolean customTemplate) {
this.useCustomTemplate = customTemplate;
}
public String getHtmlTemplate() {
return htmlTemplate;
}
public void setHtmlTemplate(String customTemplateContent) {
this.htmlTemplate = customTemplateContent;
if (htmlTemplate != null && !htmlTemplate.isEmpty()) {
this.setUseCustomTemplate(true);
}
}
}
|
package cn.cerc.mis.core;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import cn.cerc.core.ClassConfig;
import cn.cerc.core.ClassResource;
import cn.cerc.core.ISession;
import cn.cerc.core.LanguageResource;
import cn.cerc.db.core.IAppConfig;
import cn.cerc.db.core.IHandle;
import cn.cerc.db.core.ISessionOwner;
import cn.cerc.db.core.ITokenManage;
import cn.cerc.db.core.ServerConfig;
import cn.cerc.db.core.SupportHandle;
import cn.cerc.mis.SummerMIS;
import cn.cerc.mis.config.ApplicationConfig;
import cn.cerc.mis.language.Language;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Application {
private static final ClassResource res = new ClassResource(Application.class, SummerMIS.ID);
private static final ClassConfig config = new ClassConfig(Application.class, SummerMIS.ID);
// tomcat JSESSION.ID
public static final String sessionId = "sessionId";
// token id
// FIXME RequestDataTokensql LoginID_
public static final String TOKEN = "ID";
// user id
public static final String userId = "UserID";
public static final String userCode = "UserCode";
public static final String userName = "UserName";
public static final String roleCode = "RoleCode";
public static final String bookNo = "BookNo";
public static final String deviceLanguage = "language";
public static final String ProxyUsers = "ProxyUsers";
public static final String clientIP = "clientIP";
public static final String loginTime = "loginTime";
public static final String webclient = "webclient";
// FIXME: 2019/12/7
public static final String App_Language = getAppLanguage(); // cn/en
public static final String PATH_FORMS = "application.pathForms";
public static final String PATH_SERVICES = "application.pathServices";
public static final String FORM_WELCOME = "application.formWelcome";
public static final String FORM_DEFAULT = "application.formDefault";
public static final String FORM_LOGOUT = "application.formLogout";
public static final String FORM_VERIFY_DEVICE = "application.formVerifyDevice";
public static final String JSPFILE_LOGIN = "application.jspLoginFile";
public static final String FORM_ID = "formId";
private static ApplicationContext context;
private static String staticPath;
static {
staticPath = config.getString("app.static.path", "");
}
public static void init(String packageId) {
if (context != null)
return;
String xmlFile = String.format("%s-spring.xml", packageId);
if (packageId == null)
xmlFile = "application.xml";
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile);
context = ctx;
}
public static ApplicationContext getContext() {
return context;
}
private static String getAppLanguage() {
return LanguageResource.appLanguage;
}
public static void setContext(ApplicationContext applicationContext) {
if (context != applicationContext) {
if (context == null) {
} else {
log.warn("applicationContext overload!");
}
context = applicationContext;
}
}
public static ApplicationContext get(ServletContext servletContext) {
setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext));
return context;
}
public static ApplicationContext get(ServletRequest request) {
setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()));
return context;
}
@Deprecated
public static <T> T getBean(String beanId, Class<T> requiredType) {
return context.getBean(beanId, requiredType);
}
public static <T> T getBean(Class<T> requiredType, String... beans) {
for (String key : beans) {
if (!context.containsBean(key)) {
continue;
}
return context.getBean(key, requiredType);
}
return null;
}
/**
* ISessionOwner session
*
* ITokenManage tokenManage, tokenManageDefault
*
* @param <T>
* @param requiredType
* @param session
* @return
*/
public static <T> T getBeanDefault(Class<T> requiredType, ISession session) {
String[] items = requiredType.getName().split("\\.");
String itemId = items[items.length - 1];
String classId = itemId;
if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) {
classId = itemId.substring(1);
}
String beanId = classId.substring(0, 1).toLowerCase() + classId.substring(1);
T result = getBean(requiredType, beanId, beanId + "Default");
// session
if ((session != null) && (result instanceof ISessionOwner)) {
((ISessionOwner) result).setSession(session);
}
return result;
}
public static <T> T getBean(Class<T> requiredType) {
String[] items = requiredType.getName().split("\\.");
String itemId = items[items.length - 1];
String beanId;
if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) {
beanId = itemId;
} else {
beanId = itemId.substring(0, 1).toLowerCase() + itemId.substring(1);
}
return context.getBean(beanId, requiredType);
}
@Deprecated
public static IHandle getHandle() {
return new Handle(createSession());
}
public static ISession createSession() {
return getBeanDefault(ISession.class, null);
}
/**
* ClassResourceAppConfigDefault
*
* @return
*/
@Deprecated
public static IAppConfig getAppConfig() {
return getBeanDefault(IAppConfig.class, null);
}
@Deprecated // getBean
public static <T> T get(IHandle handle, Class<T> requiredType) {
return getBean(handle, requiredType);
}
public static <T> T getBean(IHandle handle, Class<T> requiredType) {
T bean = getBean(requiredType);
if (bean != null && handle != null) {
if (bean instanceof IHandle) {
((IHandle) bean).setSession(handle.getSession());
}
}
return bean;
}
public static IService getService(IHandle handle, String serviceCode) {
IService bean = context.getBean(serviceCode, IService.class);
if (bean != null && handle != null) {
bean.setHandle(handle);
}
return bean;
}
public static IPassport getPassport(ISession session) {
return getBeanDefault(IPassport.class, session);
}
public static IPassport getPassport(ISessionOwner owner) {
return getBeanDefault(IPassport.class, owner.getSession());
}
public static ISystemTable getSystemTable() {
return getBeanDefault(ISystemTable.class, null);
}
public static IForm getForm(HttpServletRequest req, HttpServletResponse resp, String formId) {
if (formId == null || "".equals(formId) || "service".equals(formId)) {
return null;
}
setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext()));
if (!context.containsBean(formId)) {
throw new RuntimeException(String.format("form %s not find!", formId));
}
IForm form = context.getBean(formId, IForm.class);
if (form != null) {
form.setRequest(req);
form.setResponse(resp);
}
return form;
}
public static String getLanguage() {
String lang = ServerConfig.getInstance().getProperty(deviceLanguage);
if (lang == null || "".equals(lang) || App_Language.equals(lang)) {
return App_Language;
} else if (Language.en_US.equals(lang)) {
return lang;
} else {
throw new RuntimeException("not support language: " + lang);
}
}
public static String getFormView(HttpServletRequest req, HttpServletResponse resp, String formId, String funcCode, String... pathVariables) {
req.setAttribute("logon", false);
IFormFilter formFilter = Application.getBean(IFormFilter.class, "AppFormFilter");
if (formFilter != null) {
try {
if (formFilter.doFilter(resp, formId, funcCode)) {
return null;
}
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
ISession session = null;
try {
IForm form = Application.getForm(req, resp, formId);
if (form == null) {
outputErrorPage(req, resp, new RuntimeException("error servlet:" + req.getServletPath()));
return null;
}
AppClient client = new AppClient();
client.setRequest(req);
req.setAttribute("_showMenu_", !AppClient.ee.equals(client.getDevice()));
form.setClient(client);
session = Application.createSession();
session.setProperty(Application.sessionId, req.getSession().getId());
session.setProperty(Application.deviceLanguage, client.getLanguage());
IHandle handle = new Handle(session);
req.setAttribute("myappHandle", handle);
form.setId(formId);
form.setHandle(handle);
form.setPathVariables(pathVariables);
// Form
if (form.allowGuestUser()) {
return form.getView(funcCode);
}
if (session.logon()) {
if (!Application.getPassport(session).pass(form)) {
resp.setContentType("text/html;charset=UTF-8");
JsonPage output = new JsonPage(form);
output.setResultMessage(false, res.getString(1, ""));
output.execute();
return null;
}
} else {
IAppLogin appLogin = Application.getBeanDefault(IAppLogin.class, session);
if (!appLogin.pass(form)) {
return appLogin.getJspFile();
}
}
if (form.isSecurityDevice()) {
return form.getView(funcCode);
}
ISecurityDeviceCheck deviceCheck = Application.getBeanDefault(ISecurityDeviceCheck.class, session);
switch (deviceCheck.pass(form)) {
case PASS:
return form.getView(funcCode);
case CHECK:
return "redirect:" + config.getString(Application.FORM_VERIFY_DEVICE, "VerifyDevice");
default:
resp.setContentType("text/html;charset=UTF-8");
JsonPage output = new JsonPage(form);
output.setResultMessage(false, res.getString(2, ""));
output.execute();
return null;
}
} catch (Exception e) {
outputErrorPage(req, resp, e);
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public static void outputView(HttpServletRequest request, HttpServletResponse response, String url) throws IOException, ServletException {
if (url == null)
return;
if (url.startsWith("redirect:")) {
String redirect = url.substring(9);
redirect = response.encodeRedirectURL(redirect);
response.sendRedirect(redirect);
return;
}
// jsp
String jspFile = String.format("/WEB-INF/%s/%s", config.getString(Application.PATH_FORMS, "forms"), url);
request.getServletContext().getRequestDispatcher(jspFile).forward(request, response);
}
public static void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e) {
Throwable err = e.getCause();
if (err == null) {
err = e;
}
IAppErrorPage errorPage = Application.getBeanDefault(IAppErrorPage.class, null);
if (errorPage != null) {
String result = errorPage.getErrorPage(request, response, err);
if (result != null) {
String url = String.format("/WEB-INF/%s/%s", config.getString(Application.PATH_FORMS, "forms"), result);
try {
request.getServletContext().getRequestDispatcher(url).forward(request, response);
} catch (ServletException | IOException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
}
}
} else {
log.warn("not define bean: errorPage");
log.error(err.getMessage());
err.printStackTrace();
}
}
/**
* token
*
* @param handle
* @return
*/
public static String getToken(IHandle handle) {
return (String) handle.getProperty(Application.TOKEN);
}
public static String getStaticPath() {
return staticPath;
}
public static ITokenManage getTokenManage(ISession session) {
return getBeanDefault(ITokenManage.class, session);
}
public static String getHomePage() {
return config.getString(Application.FORM_DEFAULT, "default");
}
}
|
package oap.dictionary;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toList;
public interface Dictionary {
int getOrDefault( String id, int defaultValue );
Integer get( String id );
String getOrDefault( int externlId, String defaultValue );
boolean containsValueWithId( String id );
List<String> ids();
int[] externalIds();
Map<String, Object> getProperties();
Optional<? extends Dictionary> getValueOpt( String name );
Dictionary getValue( String name );
Dictionary getValue( int externalId );
List<? extends Dictionary> getValues();
default List<Dictionary> getValues( Predicate<Dictionary> p ) {
return getValues().stream().filter( p ).collect( toList() );
}
String getId();
<T> Optional<T> getProperty( String name );
default <T> T getPropertyOrThrow( String name ) {
return this.<T>getProperty( name )
.orElseThrow( () -> new IllegalArgumentException( getId() + ": not found" ) );
}
boolean isEnabled();
int getExternalId();
boolean containsProperty( String name );
@SuppressWarnings( "unchecked" )
default List<String> getTags() {
return ( List<String> ) getProperty( "tags" ).orElse( Collections.emptyList() );
}
}
|
package graph;
import generaltools.ArrayTools;
import graphtools.EdmondsKarpMaxFlowMinCut;
import hashtools.TwoKeyHash;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import mathtools.MapleTools;
import mathtools.Subsets;
import org.jgrapht.WeightedGraph;
import org.jgrapht.alg.EdmondsKarpMaximumFlow;
import org.jgrapht.alg.MinSourceSinkCut;
import org.jgrapht.alg.StoerWagnerMinimumCut;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.DirectedWeightedMultigraph;
import filetools.WriteFile;
import returntools.Tuple2;
import syst.Instance;
import syst.Systm;
import syst.Variable;
public class BinaryGraph {
private Systm sys;
private DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> graph;
private final Variable source = new Variable("S");
private final Variable sink = new Variable("T");
private final String[] biLabels;
private boolean isAE; //is from an alpha expansion
/* * * * * * * * * *
* CONSTRUCTORS *
* * * * * * * * * */
/**
* @param s A binary Systm
*/
public BinaryGraph(Systm s, boolean ae){
// Instantiate the Systm and make the hats
sys = s;
sys.makeHats();
if (ae){
biLabels = Systm.binaryLabels;
if (!sys.getIsBinary()){
System.out.println("Must have a binary Systm to make a BinaryGraph!");
System.exit(0);
}else{
// Make the flow network from the normal form energy
createNonSubmodularFlowNetworkAE();
//printGraphCompact();
}
}else{
biLabels = null;
if (!sys.getIsBinary()){
System.out.println("Must have a binary Systm to make a BinaryGraph!");
System.exit(0);
}else{
// Make the flow network from the normal form energy
createNonSubmodularFlowNetworkNonAE();
printGraphCompact();
}
}
}
public BinaryGraph(Systm s, boolean ae, WriteFile wr){
// Instantiate the Systm and make the hats
sys = s;
sys.makeHats();
if (ae){
biLabels = Systm.binaryLabels;
if (!sys.getIsBinary()){
System.out.println("Must have a binary Systm to make a BinaryGraph!");
System.exit(0);
}else{
// Make the flow network from the normal form energy
createNonSubmodularFlowNetworkAE();
//printGraphCompact();
}
}else{
biLabels = null;
if (!sys.getIsBinary()){
System.out.println("Must have a binary Systm to make a BinaryGraph!");
System.exit(0);
}else{
// Make the flow network from the normal form energy
createNonSubmodularFlowNetworkNonAE();
printGraphCompact(wr);
}
}
}
/* * * * * * *
* THE CUT *
* * * * * * */
/**
* Does the graph cut on the flow network to find the minimum
* energy configuration. If some Variables are not assigned we
* do the brute force minimization on just those unassigned
* Variables.
* @return The array of {0,1} indicating the output of
* the cut. There may be some -1 in the array if the cut
* algorithm failed to label everything and what it didn't
* label was too large for brute force (currently >25 elements)
*/
public HashMap<Variable,Integer> doCut(){
System.out.println("Doing the cut!");
EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge> F =
new EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge>(graph);
Vector<Variable> vars = sys.getVars();
Double constantNF = sys.getConstantNF();
F.calculateMinimumCut(source, sink);
F.calculateMinimumCutValue();
System.out.println();
Map <Variable,Integer> minCut = F.getMinimumCut();
Double minCutValue = F.getMinimumCutValue();
Vector<Variable> S = new Vector<Variable>();
Vector<Variable> T = new Vector<Variable>();
Vector<Variable> U = new Vector<Variable>();
Iterator<Variable> it = vars.iterator();
int[] varSeq = new int[sys.getVars().size()]; int ind = 0;
HashMap<Variable,Integer> varHM = new HashMap<Variable,Integer>();
while (it.hasNext()){
Variable gr = it.next();
if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){
S.add(gr);
varSeq[ind] = 0;
varHM.put(gr, 0);
}else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){
T.add(gr);
varSeq[ind] = 1;
varHM.put(gr, 1);
}else{
U.add(gr);
varSeq[ind] = -1;
varHM.put(gr, -1);
}
ind++;
}
//System.out.println("flow: "+F.getMaximumFlow().toString());
System.out.println("flow value: "+F.getMaximumFlowValue().toString());
System.out.println("cut: "+minCut.toString());
System.out.println("cut value: "+minCutValue);
//System.out.println("cut constant: "+constantNF);
System.out.println("cut + constant: " + (minCutValue+constantNF));
System.out.println();
printST(S,T);
System.out.println("UNKNOWN groups: "+Arrays.deepToString(U.toArray()));
System.out.println("
Tuple2<Double,int[]> better = bruteLeftOver(varSeq);
if (better != null){
Double minValue = better.getFirst();
int[] varSeq2 = better.getSecond();
HashMap<Variable,Integer> varHM2 = new HashMap<Variable,Integer>();
Vector<Variable> S2 = new Vector<Variable>();
Vector<Variable> T2 = new Vector<Variable>();
Vector<Variable> U2 = new Vector<Variable>();
//TODO: Here I'm just picking the first of the minimizers
// since they are all the same minimum value. Should probably
// pick more carefully
//for (int i=0; i<varSeq2.length; i++){
for (int i=0; i<vars.size(); i++){
Variable gr = vars.get(i);
if (varSeq2[i] == 0){
S2.add(gr); //System.out.println("S"+gr.toString());
//protSeq[ind] = 0;
varHM2.put(gr, 0);
}else if (varSeq2[i] == 1){
T2.add(gr); //System.out.println("T"+gr.toString());
//protSeq[ind] = 1;
varHM2.put(gr, 1);
}else{
U2.add(gr); //System.out.println("U"+gr.toString());
//protSeq[ind] = -1;
varHM2.put(gr, -1);
}
ind++;
}
System.out.println();
System.out.println("After brute force on the leftover we got...");
System.out.println("minimum energy: "+minValue);
printST(S2,T2);
System.out.println("UNKNOWN groups: "+Arrays.deepToString(U2.toArray()));
System.out.println("=====================================================");
System.out.println();
return varHM2;
}else{
System.out.println("=====================================================");
return varHM;
}
}
public HashMap<Variable,Instance> doCutNonAE(){
System.out.println("Doing the cut!");
EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge> F =
new EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge>(graph);
Vector<Variable> vars = sys.getVars();
Double constantNF = sys.getConstantNF();
F.calculateMinimumCut(source, sink);
F.calculateMinimumCutValue();
System.out.println();
Map <Variable,Integer> minCut = F.getMinimumCut();
Double minCutValue = F.getMinimumCutValue();
Vector<Variable> S = new Vector<Variable>();
Vector<Variable> T = new Vector<Variable>();
Vector<Variable> U = new Vector<Variable>();
Iterator<Variable> it = vars.iterator();
int[] varSeq = new int[sys.getVars().size()]; int ind = 0;
HashMap<Variable,Instance> varHM = new HashMap<Variable,Instance>();
while (it.hasNext()){
Variable gr = it.next();
if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){
S.add(gr);
varSeq[ind] = 0;
varHM.put(gr, gr.getInstances().get(0));
}else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){
T.add(gr);
varSeq[ind] = 1;
varHM.put(gr, gr.getInstances().get(1));
}else{
U.add(gr);
varSeq[ind] = -1;
varHM.put(gr, null);
}
ind++;
}
System.out.println("flow: "+F.getMaximumFlow().toString());
System.out.println("flow value: "+F.getMaximumFlowValue().toString());
System.out.println("cut: "+minCut.toString());
System.out.println("cut value: "+minCutValue);
//System.out.println("cut constant: "+constantNF);
System.out.println("cut + constant: " + (minCutValue+constantNF));
System.out.println();
printST(S,T);
System.out.println("UNKNOWN groups: "+Arrays.deepToString(U.toArray()));
System.out.println("
Tuple2<Double,int[]> better = bruteLeftOver(varSeq);
if (better != null){
Double minValue = better.getFirst();
int[] varSeq2 = better.getSecond();
HashMap<Variable,Instance> varHM2 = new HashMap<Variable,Instance>();
Vector<Variable> S2 = new Vector<Variable>();
Vector<Variable> T2 = new Vector<Variable>();
Vector<Variable> U2 = new Vector<Variable>();
//TODO: Here I'm just picking the first of the minimizers
// since they are all the same minimum value. Should probably
// pick more carefully
//for (int i=0; i<varSeq2.length; i++){
for (int i=0; i<vars.size(); i++){
Variable gr = vars.get(i);
if (varSeq2[i] == 0){
S2.add(gr); //System.out.println("S"+gr.toString());
//protSeq[ind] = 0;
varHM2.put(gr, gr.getInstances().get(0));
}else if (varSeq2[i] == 1){
T2.add(gr); //System.out.println("T"+gr.toString());
//protSeq[ind] = 1;
varHM2.put(gr, gr.getInstances().get(1));
}else{
U2.add(gr); //System.out.println("U"+gr.toString());
//protSeq[ind] = -1;
varHM2.put(gr, null);
}
ind++;
}
System.out.println();
System.out.println("After brute force on the leftover we got...");
System.out.println("minimum energy: "+minValue);
printST(S2,T2);
System.out.println("UNKNOWN groups: "+Arrays.deepToString(U2.toArray()));
System.out.println("=====================================================");
System.out.println();
return varHM2;
}else{
System.out.println("=====================================================");
return varHM;
}
}
public HashMap<Variable,Instance> doCutNonAE(WriteFile wr){
System.out.println("Doing the cut!");
EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge> F =
new EdmondsKarpMaxFlowMinCut<Variable, DefaultWeightedEdge>(graph);
Vector<Variable> vars = sys.getVars();
Double constantNF = sys.getConstantNF();
F.calculateMinimumCut(source, sink);
F.calculateMinimumCutValue();
System.out.println();
Map <Variable,Integer> minCut = F.getMinimumCut();
Double minCutValue = F.getMinimumCutValue();
Vector<Variable> S = new Vector<Variable>();
Vector<Variable> T = new Vector<Variable>();
Vector<Variable> U = new Vector<Variable>();
Iterator<Variable> it = vars.iterator();
int[] varSeq = new int[sys.getVars().size()]; int ind = 0;
HashMap<Variable,Instance> varHM = new HashMap<Variable,Instance>();
while (it.hasNext()){
Variable gr = it.next();
if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){
S.add(gr);
varSeq[ind] = 0;
varHM.put(gr, gr.getInstances().get(0));
}else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){
T.add(gr);
varSeq[ind] = 1;
varHM.put(gr, gr.getInstances().get(1));
}else{
U.add(gr);
varSeq[ind] = -1;
varHM.put(gr, null);
}
ind++;
}
wr.writeln("RESULTS");
wr.writeln("flow: "+F.getMaximumFlow().toString());
wr.writeln("flow value: "+F.getMaximumFlowValue().toString());
wr.writeln("cut: "+minCut.toString());
wr.writeln("cut value: "+minCutValue);
//System.out.println("cut constant: "+constantNF);
wr.writeln("cut + constant: " + (minCutValue+constantNF));
wr.writeln();
printST(S,T,wr);
wr.writeln("UNKNOWN groups: "+Arrays.deepToString(U.toArray()));
wr.writeln("
Tuple2<Double,int[]> better = bruteLeftOver(varSeq, wr);
if (better != null){
Double minValue = better.getFirst();
int[] varSeq2 = better.getSecond();
HashMap<Variable,Instance> varHM2 = new HashMap<Variable,Instance>();
Vector<Variable> S2 = new Vector<Variable>();
Vector<Variable> T2 = new Vector<Variable>();
Vector<Variable> U2 = new Vector<Variable>();
//TODO: Here I'm just picking the first of the minimizers
// since they are all the same minimum value. Should probably
// pick more carefully
//for (int i=0; i<varSeq2.length; i++){
for (int i=0; i<vars.size(); i++){
Variable gr = vars.get(i);
if (varSeq2[i] == 0){
S2.add(gr); //System.out.println("S"+gr.toString());
//protSeq[ind] = 0;
varHM2.put(gr, gr.getInstances().get(0));
}else if (varSeq2[i] == 1){
T2.add(gr); //System.out.println("T"+gr.toString());
//protSeq[ind] = 1;
varHM2.put(gr, gr.getInstances().get(1));
}else{
U2.add(gr); //System.out.println("U"+gr.toString());
//protSeq[ind] = -1;
varHM2.put(gr, null);
}
ind++;
}
wr.writeln();
wr.writeln("After brute force on the leftover we got...");
wr.writeln("minimum energy: "+minValue);
printST(S2,T2,wr);
wr.writeln("UNKNOWN groups: "+Arrays.deepToString(U2.toArray()));
wr.writeln("=====================================================");
wr.writeln();
return varHM2;
}else{
wr.writeln("=====================================================");
return varHM;
}
}
// THE ONE THAT YOU WANT
public HashMap<Variable,Instance> doCutNonAE(WriteFile main, WriteFile sec){
System.out.println("Doing the cut!");
MinSourceSinkCut<Variable, DefaultWeightedEdge> MSSC =
new MinSourceSinkCut<Variable, DefaultWeightedEdge>(graph);
EdmondsKarpMaximumFlow<Variable, DefaultWeightedEdge> F =
new EdmondsKarpMaximumFlow<Variable, DefaultWeightedEdge>(graph);
Vector<Variable> vars = sys.getVars();
Double constantNF = sys.getConstantNF();
// F.calculateMinimumCut(source, sink);
// F.calculateMinimumCutValue();
F.calculateMaximumFlow(source, sink);
MSSC.computeMinCut(source, sink);
System.out.println();
// Map <Variable,Integer> minCut = F.getMinimumCut();
Set<Variable> SRC = MSSC.getSourcePartition();
Set<Variable> SNK = MSSC.getSinkPartition();
// Double minCutValue = F.getMinimumCutValue();
Double minCutValue = MSSC.getCutWeight();
if (minCutValue - F.getMaximumFlowValue() > 0.00001){
throw new IllegalArgumentException(
"maxflow != mincut");
}
Vector<Variable> S = new Vector<Variable>();
Vector<Variable> T = new Vector<Variable>();
Vector<Variable> U = new Vector<Variable>();
Iterator<Variable> it = vars.iterator();
int[] varSeq = new int[sys.getVars().size()]; int ind = 0;
HashMap<Variable,Instance> varHM = new HashMap<Variable,Instance>();
while (it.hasNext()){
Variable gr = it.next();
// if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){
if (SRC.contains(gr) && SNK.contains(gr.getHat())){
S.add(gr);
varSeq[ind] = 0;
varHM.put(gr, gr.getInstances().get(0));
// }else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){
}else if (SNK.contains(gr) && SRC.contains(gr.getHat())){
T.add(gr);
varSeq[ind] = 1;
varHM.put(gr, gr.getInstances().get(1));
}else{
U.add(gr);
varSeq[ind] = -1;
varHM.put(gr, null);
}
ind++;
}
main.writeln("RESULTS");
// main.writeln("flow: "+F.getMaximumFlow().toString());
main.writeln("flow: "+F.getMaximumFlow().toString());
main.writeln("flow value: "+F.getMaximumFlowValue().toString());
// main.writeln("cut: "+minCut.toString());
main.writeln("cut:");
main.writeln(" SRC = "+SRC.toString());
main.writeln(" SNK = "+SNK.toString());
main.writeln("cut value: "+minCutValue);
//System.out.println("cut constant: "+constantNF);
main.writeln("cut + constant: " + (minCutValue+constantNF));
main.writeln();
printST(S,T,main);
main.writeln("UNKNOWN groups: "+Arrays.deepToString(U.toArray()));
main.writeln("
Tuple2<Double,int[]> better = bruteLeftOver(varSeq, main, sec);
if (better != null){
Double minValue = better.getFirst();
int[] varSeq2 = better.getSecond();
HashMap<Variable,Instance> varHM2 = new HashMap<Variable,Instance>();
Vector<Variable> S2 = new Vector<Variable>();
Vector<Variable> T2 = new Vector<Variable>();
Vector<Variable> U2 = new Vector<Variable>();
//TODO: Here I'm just picking the first of the minimizers
// since they are all the same minimum value. Should probably
// pick more carefully
//for (int i=0; i<varSeq2.length; i++){
for (int i=0; i<vars.size(); i++){
Variable gr = vars.get(i);
if (varSeq2[i] == 0){
S2.add(gr); //System.out.println("S"+gr.toString());
//protSeq[ind] = 0;
varHM2.put(gr, gr.getInstances().get(0));
}else if (varSeq2[i] == 1){
T2.add(gr); //System.out.println("T"+gr.toString());
//protSeq[ind] = 1;
varHM2.put(gr, gr.getInstances().get(1));
}else{
U2.add(gr); //System.out.println("U"+gr.toString());
//protSeq[ind] = -1;
varHM2.put(gr, null);
}
ind++;
}
main.writeln();
main.writeln("After brute force on the leftover we got...");
main.writeln("minimum energy: "+minValue);
printST(S2,T2,main);
main.writeln("UNKNOWN groups: "+Arrays.deepToString(U2.toArray()));
main.writeln("=====================================================");
main.writeln();
return varHM2;
}else{
main.writeln("=====================================================");
return varHM;
}
}
/**
* @param varSeq Array of {-1,0,1} indicating the output of the cut algorithm
* @return The result of doing a brute force minimization on the
* unassigned Variables (indicated by "-1" in varSeq). Outputs the new
* minimum energy as well as the configuration that realizes this minimum.
*/
private Tuple2<Double, int[]> bruteLeftOver(int[] varSeq) {
int[] unassigned = MapleTools.select(-1, varSeq);
int n = unassigned.length;
System.out.println("There are "+n+" unassigned residues.");
if (n==0){
//System.out.println("There are no unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("NO ");
return null;
}
if (n>25){
System.out.println("Can't do brute that high! There are "+n+" unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("XX ");
// wr.write(n+" ");
return null;
}
Subsets S = new Subsets(n);
double currentMin = Double.POSITIVE_INFINITY;
int[] currentMinimizer = new int[n];
while (S.hasNext()){
int[] subset = S.next();
int[] fullSub = varSeq.clone();
for (int j=0; j<n; j++){
fullSub[unassigned[j]] = subset[j];
}
double energy;
if (isAE){
energy = sys.evaluateBinaryEnergy(fullSub,true); //System.out.println(Arrays.toString(subsetVectors[i])+" "+energy);
}else{
energy = sys.evaluateEnergy(fullSub, true);
}
//if (verb){
// System.out.println(energy + " " + Arrays.toString(subsetVectors[i]));
if (energy<currentMin){
currentMin = energy;
currentMinimizer = fullSub.clone();
}else if (energy == currentMin){
currentMinimizer = ArrayTools.concat(currentMinimizer,fullSub);
}
}
Tuple2<Double,int[]> Ret = new Tuple2<Double,int[]>(currentMin, currentMinimizer);
return Ret;
}
private Tuple2<Double, int[]> bruteLeftOver(int[] varSeq, WriteFile wr) {
int[] unassigned = MapleTools.select(-1, varSeq);
int n = unassigned.length;
wr.writeln("There are "+n+" unassigned residues.");
if (n==0){
//System.out.println("There are no unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("NO ");
return null;
}
if (n>25){
wr.writeln("Can't do brute that high! There are "+n+" unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("XX ");
// wr.write(n+" ");
return null;
}
Subsets S = new Subsets(n);
double currentMin = Double.POSITIVE_INFINITY;
int[] currentMinimizer = new int[n];
while (S.hasNext()){
int[] subset = S.next();
int[] fullSub = varSeq.clone();
for (int j=0; j<n; j++){
fullSub[unassigned[j]] = subset[j];
}
double energy;
if (isAE){
energy = sys.evaluateBinaryEnergy(fullSub,true); //System.out.println(Arrays.toString(subsetVectors[i])+" "+energy);
}else{
energy = sys.evaluateEnergy(fullSub, true);
}
//if (verb){
// System.out.println(energy + " " + Arrays.toString(subsetVectors[i]));
if (energy<currentMin){
currentMin = energy;
currentMinimizer = fullSub.clone();
}else if (energy == currentMin){
currentMinimizer = ArrayTools.concat(currentMinimizer,fullSub);
}
}
Tuple2<Double,int[]> Ret = new Tuple2<Double,int[]>(currentMin, currentMinimizer);
return Ret;
}
private Tuple2<Double, int[]> bruteLeftOver(int[] varSeq, WriteFile wr, WriteFile sec) {
int[] unassigned = MapleTools.select(-1, varSeq);
int n = unassigned.length;
wr.writeln("There are "+n+" unassigned residues.");
sec.writeln(sys.getVars().size()+" "+n);
if (n==0){
//System.out.println("There are no unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("NO ");
return null;
}
if (n>25){
wr.writeln("Can't do brute that high! There are "+n+" unassigned residues.");
// long endBrute = System.currentTimeMillis();
// System.out.println("Took "+(endBrute - startBrute)+" ms to do the brute force minimization on the unassigned residues.");
// //time.write("brute "+(endBrute-startBrute)+" ");
// time.write("XX ");
// wr.write(n+" ");
return null;
}
Subsets S = new Subsets(n);
double currentMin = Double.POSITIVE_INFINITY;
int[] currentMinimizer = new int[n];
while (S.hasNext()){
int[] subset = S.next();
int[] fullSub = varSeq.clone();
for (int j=0; j<n; j++){
fullSub[unassigned[j]] = subset[j];
}
double energy;
if (isAE){
energy = sys.evaluateBinaryEnergy(fullSub,true); //System.out.println(Arrays.toString(subsetVectors[i])+" "+energy);
}else{
energy = sys.evaluateEnergy(fullSub, true);
}
//if (verb){
// System.out.println(energy + " " + Arrays.toString(subsetVectors[i]));
if (energy<currentMin){
currentMin = energy;
currentMinimizer = fullSub.clone();
}else if (energy == currentMin){
currentMinimizer = ArrayTools.concat(currentMinimizer,fullSub);
}
}
Tuple2<Double,int[]> Ret = new Tuple2<Double,int[]>(currentMin, currentMinimizer);
return Ret;
}
/* * * * * * * *
* MAKE GRAPH *
* * * * * * * */
/**
* Creates the flow network for the general binary Systm
* of this BinaryGraph object.
*/
private void createNonSubmodularFlowNetworkNonAE(){
System.out.println("Making the binary energy flow network for the binary Systm.");
// Get the variables and normal form binary energy
Vector<Variable> vars = sys.getVars();
TwoKeyHash<Instance,Double> matrixNF = sys.getBinaryNF();
// This will be the flow network
DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> g =
new DirectedWeightedMultigraph<Variable, DefaultWeightedEdge>(DefaultWeightedEdge.class);
int n = vars.size();
g.addVertex(source);
g.addVertex(sink);
// Weight the edges as indicated in the Minimizing Non-Submodular Energy paper.
for(int i = 0; i<=n-1; i++){
Variable vi = vars.get(i); //System.out.println(vi);
Variable viHat = vi.getHat(); //System.out.println(viHat);
Vector<Instance> viInsts = vi.getInstances();
Instance vi0 = viInsts.get(0);
Instance vi1 = viInsts.get(1);
g.addVertex(vi);
g.addVertex(viHat);
Double E0 = vi0.getEnergyNF();
Double E1 = vi1.getEnergyNF();
g.addEdge(vi,sink);
g.setEdgeWeight(g.getEdge(vi, sink),0.5*E0);
g.addEdge(source,viHat);
g.setEdgeWeight(g.getEdge(source,viHat), 0.5*E0);
g.addEdge(source,vi);
g.setEdgeWeight(g.getEdge(source,vi),0.5*E1);
g.addEdge(viHat, sink);
g.setEdgeWeight(g.getEdge(viHat,sink),0.5*E1);
}
for(int p=0; p<=n-1; p++){
for(int q=p+1; q<=n-1 && p!=q; q++){
Variable vp = vars.get(p);
Vector<Instance> vpInsts = vp.getInstances();
Instance vp0 = vpInsts.get(0); Instance vp1 = vpInsts.get(1);
Variable vpHat = vp.getHat();
Variable vq = vars.get(q);
Vector<Instance> vqInsts = vq.getInstances();
Instance vq0 = vqInsts.get(0); Instance vq1 = vqInsts.get(1);
Variable vqHat = vq.getHat();
//System.out.println(vp.toString()+" ["+vp0.toString()+", "+vp1.toString()+"] "+vq.toString()+" ["+vq0.toString()+", "+vq1.toString()+"]");
Double E01 = matrixNF.get(vp0, vq1);
Double E10 = matrixNF.get(vp1, vq0);
Double E00 = matrixNF.get(vp0, vq0);
Double E11 = matrixNF.get(vp1, vq1);
g.addEdge(vp,vq);
g.addEdge(vqHat,vpHat);
g.setEdgeWeight(g.getEdge(vp,vq), 0.5*E01);
g.setEdgeWeight(g.getEdge(vqHat,vpHat), 0.5*E01);
g.addEdge(vq,vp);
g.addEdge(vpHat,vqHat);
g.setEdgeWeight(g.getEdge(vq,vp),0.5*E10);
g.setEdgeWeight(g.getEdge(vpHat,vqHat), 0.5*E10);
g.addEdge(vp,vqHat);
g.addEdge(vq,vpHat);
g.setEdgeWeight(g.getEdge(vp,vqHat),0.5*E00);
g.setEdgeWeight(g.getEdge(vq,vpHat), 0.5*E00);
g.addEdge(vqHat,vp);
g.addEdge(vpHat,vq);
g.setEdgeWeight(g.getEdge(vqHat,vp),0.5*E11);
g.setEdgeWeight(g.getEdge(vpHat,vq),0.5*E11);
}
}
graph = addWeights(g);
}
/**
* Creates the flow network for the binary Systm (created for
* the alpha-expansion) of this BinaryGraph object.
*/
private void createNonSubmodularFlowNetworkAE() {
System.out.println("Making the binary energy flow network for the alpha-expansion.");
// Get the variables and normal form binary energy
Vector<Variable> vars = sys.getVars();
TwoKeyHash<Instance,Double> matrixNF = sys.getBinaryNF();
// This will be the flow network
DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> g =
new DirectedWeightedMultigraph<Variable, DefaultWeightedEdge>(DefaultWeightedEdge.class);
int n = vars.size();
g.addVertex(source);
g.addVertex(sink);
// Weight the edges as indicated in the Minimizing Non-Submodular Energy paper.
for(int i = 0; i<=n-1; i++){
Variable vi = vars.get(i); //System.out.println(vi);
Variable viHat = vi.getHat(); //System.out.println(viHat);
Instance vi0 = vi.getInstance(biLabels[0]);
Instance vi1 = vi.getInstance(biLabels[1]);
g.addVertex(vi);
g.addVertex(viHat);
Double E0 = vi0.getEnergyNF();
Double E1 = vi1.getEnergyNF();
g.addEdge(vi,sink);
g.setEdgeWeight(g.getEdge(vi, sink),0.5*E0);
g.addEdge(source,viHat);
g.setEdgeWeight(g.getEdge(source,viHat), 0.5*E0);
g.addEdge(source,vi);
g.setEdgeWeight(g.getEdge(source,vi),0.5*E1);
g.addEdge(viHat, sink);
g.setEdgeWeight(g.getEdge(viHat,sink),0.5*E1);
}
for(int p=0; p<=n-1; p++){
for(int q=p+1; q<=n-1 && p!=q; q++){
Variable vp = vars.get(p);
Instance vp0 = vp.getInstance(biLabels[0]); Instance vp1 = vp.getInstance(biLabels[1]);
Variable vpHat = vp.getHat();
Variable vq = vars.get(q);
Instance vq0 = vq.getInstance(biLabels[0]); Instance vq1 = vq.getInstance(biLabels[1]);
Variable vqHat = vq.getHat();
Double E01 = matrixNF.get(vp0, vq1);
Double E10 = matrixNF.get(vp1, vq0);
Double E00 = matrixNF.get(vp0, vq0);
Double E11 = matrixNF.get(vp1, vq1);
g.addEdge(vp,vq);
g.addEdge(vqHat,vpHat);
g.setEdgeWeight(g.getEdge(vp,vq), 0.5*E01);
g.setEdgeWeight(g.getEdge(vqHat,vpHat), 0.5*E01);
g.addEdge(vq,vp);
g.addEdge(vpHat,vqHat);
g.setEdgeWeight(g.getEdge(vq,vp),0.5*E10);
g.setEdgeWeight(g.getEdge(vpHat,vqHat), 0.5*E10);
g.addEdge(vp,vqHat);
g.addEdge(vq,vpHat);
g.setEdgeWeight(g.getEdge(vp,vqHat),0.5*E00);
g.setEdgeWeight(g.getEdge(vq,vpHat), 0.5*E00);
g.addEdge(vqHat,vp);
g.addEdge(vpHat,vq);
g.setEdgeWeight(g.getEdge(vqHat,vp),0.5*E11);
g.setEdgeWeight(g.getEdge(vpHat,vq),0.5*E11);
}
}
graph = addWeights(g);
}
/**
* @param g A flow network with possible multi-edges
* @return The same flow network with all multi-edges
* collapsed into a single edge having weight equal
* to the sum of the original weights.
*/
private DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> addWeights(
DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> g) {
DirectedWeightedMultigraph<Variable, DefaultWeightedEdge> g1 =
new DirectedWeightedMultigraph<Variable, DefaultWeightedEdge>(DefaultWeightedEdge.class);
Set<Variable> vertices = g.vertexSet();
for(Variable v: vertices){
for(Variable w: vertices){
g1.addVertex(v);
g1.addVertex(w);
Set<DefaultWeightedEdge> edges = g.getAllEdges(v, w);
Double newWt = new Double(0);
for(DefaultWeightedEdge e: edges){
newWt += g.getEdgeWeight(e);
}
if(newWt != 0){
g1.addEdge(v,w);
g1.setEdgeWeight(g1.getEdge(v,w), newWt);
}
}
}
return g1;
}
/* * * * * * * *
* PRINTING *
* * * * * * * */
/**
* Prints out the number of vertices as well as the edges with weights
* Number of vertices first followed by each edge and weight
* on subsequent lines (one line per edge)
*/
public void printGraph() {
Set<Variable> vertices = graph.vertexSet();
System.out.println("There are "+vertices.size() +" vertices.");
System.out.println("The edges with weights are:");
for(Variable v: vertices){
for(Variable w: vertices){
Set<DefaultWeightedEdge> edges = graph.getAllEdges(v, w);
for(DefaultWeightedEdge e: edges){
double wt = graph.getEdgeWeight(e);
System.out.println(v.toString()+", "+ w.toString() +", "+ wt);
}
}
}
}
/**
* Prints out the vertex set and edge set with weights on one line.
* [vertex set], {(v1,v2)=wt...}
* where (v1,v2) is an edge with weight wt
*/
public void printGraphCompact(){
Set<Variable> vertices = graph.vertexSet();
String toPrint = " ";
toPrint = toPrint.concat(vertices.toString()+", {");
for(Variable v: vertices){
for(Variable w: vertices){
Set<DefaultWeightedEdge> edges = graph.getAllEdges(v, w);
for(DefaultWeightedEdge e: edges){
double wt = graph.getEdgeWeight(e);
toPrint = toPrint.concat("("+v.toString()+", "+ w.toString() +")= "+ wt+", ");
}
}
}
toPrint = toPrint.substring(0,toPrint.length()-2);
toPrint = toPrint.concat("}");
System.out.println(toPrint);
}
public void printGraphCompact(WriteFile wr){
Set<Variable> vertices = graph.vertexSet();
// sort the vertices alphabetically
Comparator<Variable> comparator = new Comparator<Variable>() {
public int compare(Variable o1, Variable o2) {
return o1.getName().toString().compareTo(o2.getName().toString());
}
};
SortedSet<Variable> sorted_keys = new TreeSet<Variable>(comparator);
sorted_keys.addAll(vertices);
// run through the vertices to print
String toPrintVerts = "Vertices:\n";
String toPrintEdges = "Edges:\n";
for(Variable vtx1: sorted_keys){
String vname = vtx1.toString();
String vnameTranslate = "";
if (vname.equals("S"))
vnameTranslate = "S";
else if (vname.equals("T"))
vnameTranslate = "T";
else if (vname.substring(vname.length()-2).equals("_H")){
vnameTranslate = vname.substring(0, vname.length()-2)+"_PROTONATED";
}else{
vnameTranslate = vname+"_DEPROTONATED";
}
toPrintVerts += (vnameTranslate+"\n");
for (Variable vtx2 : sorted_keys){
if (vtx1.equals(vtx2))
continue;
String wname = vtx2.toString();
String wnameTranslate = "";
if (wname.equals("S"))
wnameTranslate = "S";
else if (wname.equals("T"))
wnameTranslate = "T";
else if (wname.substring(wname.length()-2).equals("_H")){
wnameTranslate = wname.substring(0, wname.length()-2)+"_DEPROTONATED";
}else{
wnameTranslate = wname+"_PROTONATED";
}
Set<DefaultWeightedEdge> edges = graph.getAllEdges(vtx1, vtx2);
for(DefaultWeightedEdge e: edges){
double wt = graph.getEdgeWeight(e);
toPrintEdges += ("("+vnameTranslate+", "+ wnameTranslate +")= "+ Math.round(wt*10000.0)/10000.0+"\n");
}
}
}
// String toPrint = " ";
// toPrint = toPrint.concat(vertices.toString()+", {");
// for(Variable v: vertices){
// for(Variable w: vertices){
// Set<DefaultWeightedEdge> edges = graph.getAllEdges(v, w);
// for(DefaultWeightedEdge e: edges){
// double wt = graph.getEdgeWeight(e);
// toPrint = toPrint.concat("("+v.toString()+", "+ w.toString() +")= "+ wt+", ");
// toPrint = toPrint.substring(0,toPrint.length()-2);
// toPrint = toPrint.concat("}");
wr.writeln("Flow network:");
wr.writeln(toPrintVerts);
wr.writeln(toPrintEdges);
}
/**
* Prints out the configuration given by the S and T sets
* @param S Vector of Variables assigned to "0"
* @param T Vector of Variables assigned to "1"
*/
private void printST(Vector<Variable> S, Vector<Variable> T) {
System.out.print("0 instances: ");
for (int i=0; i<S.size(); i++){
Variable iGrp = S.get(i);
Instance iGrp0;
if (isAE){
iGrp0 = iGrp.getInstance(biLabels[0]);
}else{
iGrp0 = iGrp.getInstances().get(0);
}
System.out.print(iGrp0.toString()+", ");
} System.out.println();
System.out.print("1 instances: ");
for (int i=0; i<T.size(); i++){
Variable iGrp = T.get(i);
Instance iGrp1;
if (isAE){
iGrp1 = iGrp.getInstance(biLabels[1]);
}else{
iGrp1 = iGrp.getInstances().get(1);
}
System.out.print(iGrp1.toString()+", ");
} System.out.println();
}
private void printST(Vector<Variable> S, Vector<Variable> T, WriteFile wr) {
wr.write("0 instances: ");
for (int i=0; i<S.size(); i++){
Variable iGrp = S.get(i);
Instance iGrp0;
if (isAE){
iGrp0 = iGrp.getInstance(biLabels[0]);
}else{
iGrp0 = iGrp.getInstances().get(0);
}
wr.write(iGrp0.toString()+", ");
} wr.writeln();
wr.write("1 instances: ");
for (int i=0; i<T.size(); i++){
Variable iGrp = T.get(i);
Instance iGrp1;
if (isAE){
iGrp1 = iGrp.getInstance(biLabels[1]);
}else{
iGrp1 = iGrp.getInstances().get(1);
}
wr.write(iGrp1.toString()+", ");
} wr.writeln();
}
}
|
package org.gluu.service;
import java.util.List;
import javax.inject.Inject;
import org.gluu.model.custom.script.CustomScriptType;
import org.gluu.model.custom.script.model.CustomScript;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.search.filter.Filter;
import org.gluu.service.custom.script.AbstractCustomScriptService;
import org.gluu.util.OxConstants;
import org.gluu.util.StringHelper;
import org.python.jline.internal.Log;
/**
* @author Mougang T.Gasmyr
*
*/
public class ScriptService {
@Inject
private OrganizationService organizationService;
@Inject
private PersistenceEntryManager persistenceEntryManager;
@Inject
protected AbstractCustomScriptService customScriptService;
public CustomScript getScriptByInum(String inum) {
CustomScript result = null;
try {
result = persistenceEntryManager.find(CustomScript.class, customScriptService.buildDn(inum));
} catch (Exception ex) {
Log.error("Failed to find script by inum {}", inum, ex);
}
return result;
}
public List<CustomScript> findCustomAuthScripts(String pattern, int sizeLimit) {
String[] targetArray = new String[] { pattern };
Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);
Filter scriptTypeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE,
CustomScriptType.PERSON_AUTHENTICATION);
Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,
Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit);
}
public List<CustomScript> findCustomAuthScripts(int sizeLimit) {
Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE,
CustomScriptType.PERSON_AUTHENTICATION.getValue());
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,
sizeLimit);
}
public List<CustomScript> findOtherCustomScripts(String pattern, int sizeLimit) {
String[] targetArray = new String[] { pattern };
Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);
Filter scriptTypeFilter = Filter.createNOTFilter(
Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION));
Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,
Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit);
}
public List<CustomScript> findScriptByType(CustomScriptType type, int sizeLimit) {
Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,
sizeLimit);
}
public List<CustomScript> findScriptByType(CustomScriptType type) {
Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter, null);
}
public List<CustomScript> findScriptByPatternAndType(String pattern, CustomScriptType type, int sizeLimit) {
String[] targetArray = new String[] { pattern };
Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);
Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);
Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,
Filter.createANDFilter(searchFilter, typeFilter), sizeLimit);
}
public List<CustomScript> findScriptByPatternAndType(String pattern, CustomScriptType type) {
String[] targetArray = new String[] { pattern };
Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);
Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);
Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,
Filter.createANDFilter(searchFilter, typeFilter), null);
}
public List<CustomScript> findOtherCustomScripts(int sizeLimit) {
Filter searchFilter = Filter.createNOTFilter(
Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION));
return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,
sizeLimit);
}
public String getDnForCustomScript(String inum) {
String orgDn = organizationService.getDnForOrganization(null);
if (StringHelper.isEmpty(inum)) {
return String.format("ou=scripts,%s", orgDn);
}
return String.format("inum=%s,ou=scripts,%s", inum, orgDn);
}
public String baseDn() {
return String.format("ou=scripts,%s", organizationService.getDnForOrganization(null));
}
}
|
package org.jfree.data.time.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.data.general.SeriesChangeEvent;
import org.jfree.data.general.SeriesChangeListener;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Day;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.Month;
import org.jfree.data.time.MonthConstants;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesDataItem;
import org.jfree.data.time.Year;
/**
* A collection of test cases for the {@link TimeSeries} class.
*/
public class TimeSeriesTests extends TestCase implements SeriesChangeListener {
/** A time series. */
private TimeSeries seriesA;
/** A time series. */
private TimeSeries seriesB;
/** A time series. */
private TimeSeries seriesC;
/** A flag that indicates whether or not a change event was fired. */
private boolean gotSeriesChangeEvent = false;
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(TimeSeriesTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public TimeSeriesTests(String name) {
super(name);
}
/**
* Common test setup.
*/
protected void setUp() {
this.seriesA = new TimeSeries("Series A");
try {
this.seriesA.add(new Year(2000), new Integer(102000));
this.seriesA.add(new Year(2001), new Integer(102001));
this.seriesA.add(new Year(2002), new Integer(102002));
this.seriesA.add(new Year(2003), new Integer(102003));
this.seriesA.add(new Year(2004), new Integer(102004));
this.seriesA.add(new Year(2005), new Integer(102005));
}
catch (SeriesException e) {
System.err.println("Problem creating series.");
}
this.seriesB = new TimeSeries("Series B");
try {
this.seriesB.add(new Year(2006), new Integer(202006));
this.seriesB.add(new Year(2007), new Integer(202007));
this.seriesB.add(new Year(2008), new Integer(202008));
}
catch (SeriesException e) {
System.err.println("Problem creating series.");
}
this.seriesC = new TimeSeries("Series C");
try {
this.seriesC.add(new Year(1999), new Integer(301999));
this.seriesC.add(new Year(2000), new Integer(302000));
this.seriesC.add(new Year(2002), new Integer(302002));
}
catch (SeriesException e) {
System.err.println("Problem creating series.");
}
}
/**
* Sets the flag to indicate that a {@link SeriesChangeEvent} has been
* received.
*
* @param event the event.
*/
public void seriesChanged(SeriesChangeEvent event) {
this.gotSeriesChangeEvent = true;
}
/**
* Check that cloning works.
*/
public void testClone() {
TimeSeries series = new TimeSeries("Test Series");
RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002);
try {
series.add(jan1st2002, new Integer(42));
}
catch (SeriesException e) {
System.err.println("Problem adding to series.");
}
TimeSeries clone = null;
try {
clone = (TimeSeries) series.clone();
clone.setKey("Clone Series");
try {
clone.update(jan1st2002, new Integer(10));
}
catch (SeriesException e) {
e.printStackTrace();
}
}
catch (CloneNotSupportedException e) {
assertTrue(false);
}
int seriesValue = series.getValue(jan1st2002).intValue();
int cloneValue = Integer.MAX_VALUE;
if (clone != null) {
cloneValue = clone.getValue(jan1st2002).intValue();
}
assertEquals(42, seriesValue);
assertEquals(10, cloneValue);
assertEquals("Test Series", series.getKey());
if (clone != null) {
assertEquals("Clone Series", clone.getKey());
}
else {
assertTrue(false);
}
}
/**
* Another test of the clone() method.
*/
public void testClone2() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2007), 100.0);
s1.add(new Year(2008), null);
s1.add(new Year(2009), 200.0);
TimeSeries s2 = null;
try {
s2 = (TimeSeries) s1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(s1.equals(s2));
// check independence
s2.addOrUpdate(new Year(2009), 300.0);
assertFalse(s1.equals(s2));
s1.addOrUpdate(new Year(2009), 300.0);
assertTrue(s1.equals(s2));
}
/**
* Add a value to series A for 1999. It should be added at index 0.
*/
public void testAddValue() {
try {
this.seriesA.add(new Year(1999), new Integer(1));
}
catch (SeriesException e) {
System.err.println("Problem adding to series.");
}
int value = this.seriesA.getValue(0).intValue();
assertEquals(1, value);
}
/**
* Tests the retrieval of values.
*/
public void testGetValue() {
Number value1 = this.seriesA.getValue(new Year(1999));
assertNull(value1);
int value2 = this.seriesA.getValue(new Year(2000)).intValue();
assertEquals(102000, value2);
}
/**
* Tests the deletion of values.
*/
public void testDelete() {
this.seriesA.delete(0, 0);
assertEquals(5, this.seriesA.getItemCount());
Number value = this.seriesA.getValue(new Year(2000));
assertNull(value);
}
/**
* Basic tests for the delete() method.
*/
public void testDelete2() {
TimeSeries s1 = new TimeSeries("Series");
s1.add(new Year(2000), 13.75);
s1.add(new Year(2001), 11.90);
s1.add(new Year(2002), null);
s1.addChangeListener(this);
this.gotSeriesChangeEvent = false;
s1.delete(new Year(2001));
assertTrue(this.gotSeriesChangeEvent);
assertEquals(2, s1.getItemCount());
assertEquals(null, s1.getValue(new Year(2001)));
// try deleting a time period that doesn't exist...
this.gotSeriesChangeEvent = false;
s1.delete(new Year(2006));
assertFalse(this.gotSeriesChangeEvent);
// try deleting null
try {
s1.delete(null);
fail("Expected IllegalArgumentException.");
}
catch (IllegalArgumentException e) {
// expected
}
}
/**
* Some checks for the delete(int, int) method.
*/
public void testDelete3() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2011), 1.1);
s1.add(new Year(2012), 2.2);
s1.add(new Year(2013), 3.3);
s1.add(new Year(2014), 4.4);
s1.add(new Year(2015), 5.5);
s1.add(new Year(2016), 6.6);
s1.delete(2, 5);
assertEquals(2, s1.getItemCount());
assertEquals(new Year(2011), s1.getTimePeriod(0));
assertEquals(new Year(2012), s1.getTimePeriod(1));
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(2.2, s1.getMaxY(), EPSILON);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count and a new value is added.
*/
public void testDelete_RegularTimePeriod() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2010), 1.1);
s1.add(new Year(2011), 2.2);
s1.add(new Year(2012), 3.3);
s1.add(new Year(2013), 4.4);
s1.delete(new Year(2010));
s1.delete(new Year(2013));
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
TimeSeries s1 = new TimeSeries("A test");
s1.add(new Year(2000), 13.75);
s1.add(new Year(2001), 11.90);
s1.add(new Year(2002), null);
s1.add(new Year(2005), 19.32);
s1.add(new Year(2007), 16.89);
TimeSeries s2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(s1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray())
);
s2 = (TimeSeries) in.readObject();
in.close();
}
catch (Exception e) {
System.out.println(e.toString());
}
assertTrue(s1.equals(s2));
}
/**
* Tests the equals method.
*/
public void testEquals() {
TimeSeries s1 = new TimeSeries("Time Series 1");
TimeSeries s2 = new TimeSeries("Time Series 2");
boolean b1 = s1.equals(s2);
assertFalse("b1", b1);
s2.setKey("Time Series 1");
boolean b2 = s1.equals(s2);
assertTrue("b2", b2);
RegularTimePeriod p1 = new Day();
RegularTimePeriod p2 = p1.next();
s1.add(p1, 100.0);
s1.add(p2, 200.0);
boolean b3 = s1.equals(s2);
assertFalse("b3", b3);
s2.add(p1, 100.0);
s2.add(p2, 200.0);
boolean b4 = s1.equals(s2);
assertTrue("b4", b4);
s1.setMaximumItemCount(100);
boolean b5 = s1.equals(s2);
assertFalse("b5", b5);
s2.setMaximumItemCount(100);
boolean b6 = s1.equals(s2);
assertTrue("b6", b6);
s1.setMaximumItemAge(100);
boolean b7 = s1.equals(s2);
assertFalse("b7", b7);
s2.setMaximumItemAge(100);
boolean b8 = s1.equals(s2);
assertTrue("b8", b8);
}
/**
* Tests a specific bug report where null arguments in the constructor
* cause the equals() method to fail. Fixed for 0.9.21.
*/
public void testEquals2() {
TimeSeries s1 = new TimeSeries("Series", null, null);
TimeSeries s2 = new TimeSeries("Series", null, null);
assertTrue(s1.equals(s2));
}
/**
* Some tests to ensure that the createCopy(RegularTimePeriod,
* RegularTimePeriod) method is functioning correctly.
*/
public void testCreateCopy1() {
TimeSeries series = new TimeSeries("Series");
series.add(new Month(MonthConstants.JANUARY, 2003), 45.0);
series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0);
series.add(new Month(MonthConstants.JUNE, 2003), 35.0);
series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0);
series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0);
try {
// copy a range before the start of the series data...
TimeSeries result1 = series.createCopy(
new Month(MonthConstants.NOVEMBER, 2002),
new Month(MonthConstants.DECEMBER, 2002));
assertEquals(0, result1.getItemCount());
// copy a range that includes only the first item in the series...
TimeSeries result2 = series.createCopy(
new Month(MonthConstants.NOVEMBER, 2002),
new Month(MonthConstants.JANUARY, 2003));
assertEquals(1, result2.getItemCount());
// copy a range that begins before and ends in the middle of the
// series...
TimeSeries result3 = series.createCopy(
new Month(MonthConstants.NOVEMBER, 2002),
new Month(MonthConstants.APRIL, 2003));
assertEquals(2, result3.getItemCount());
TimeSeries result4 = series.createCopy(
new Month(MonthConstants.NOVEMBER, 2002),
new Month(MonthConstants.DECEMBER, 2003));
assertEquals(5, result4.getItemCount());
TimeSeries result5 = series.createCopy(
new Month(MonthConstants.NOVEMBER, 2002),
new Month(MonthConstants.MARCH, 2004));
assertEquals(5, result5.getItemCount());
TimeSeries result6 = series.createCopy(
new Month(MonthConstants.JANUARY, 2003),
new Month(MonthConstants.JANUARY, 2003));
assertEquals(1, result6.getItemCount());
TimeSeries result7 = series.createCopy(
new Month(MonthConstants.JANUARY, 2003),
new Month(MonthConstants.APRIL, 2003));
assertEquals(2, result7.getItemCount());
TimeSeries result8 = series.createCopy(
new Month(MonthConstants.JANUARY, 2003),
new Month(MonthConstants.DECEMBER, 2003));
assertEquals(5, result8.getItemCount());
TimeSeries result9 = series.createCopy(
new Month(MonthConstants.JANUARY, 2003),
new Month(MonthConstants.MARCH, 2004));
assertEquals(5, result9.getItemCount());
TimeSeries result10 = series.createCopy(
new Month(MonthConstants.MAY, 2003),
new Month(MonthConstants.DECEMBER, 2003));
assertEquals(3, result10.getItemCount());
TimeSeries result11 = series.createCopy(
new Month(MonthConstants.MAY, 2003),
new Month(MonthConstants.MARCH, 2004));
assertEquals(3, result11.getItemCount());
TimeSeries result12 = series.createCopy(
new Month(MonthConstants.DECEMBER, 2003),
new Month(MonthConstants.DECEMBER, 2003));
assertEquals(1, result12.getItemCount());
TimeSeries result13 = series.createCopy(
new Month(MonthConstants.DECEMBER, 2003),
new Month(MonthConstants.MARCH, 2004));
assertEquals(1, result13.getItemCount());
TimeSeries result14 = series.createCopy(
new Month(MonthConstants.JANUARY, 2004),
new Month(MonthConstants.MARCH, 2004));
assertEquals(0, result14.getItemCount());
}
catch (CloneNotSupportedException e) {
assertTrue(false);
}
}
/**
* Some tests to ensure that the createCopy(int, int) method is
* functioning correctly.
*/
public void testCreateCopy2() {
TimeSeries series = new TimeSeries("Series");
series.add(new Month(MonthConstants.JANUARY, 2003), 45.0);
series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0);
series.add(new Month(MonthConstants.JUNE, 2003), 35.0);
series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0);
series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0);
try {
// copy just the first item...
TimeSeries result1 = series.createCopy(0, 0);
assertEquals(new Month(1, 2003), result1.getTimePeriod(0));
// copy the first two items...
result1 = series.createCopy(0, 1);
assertEquals(new Month(2, 2003), result1.getTimePeriod(1));
// copy the middle three items...
result1 = series.createCopy(1, 3);
assertEquals(new Month(2, 2003), result1.getTimePeriod(0));
assertEquals(new Month(11, 2003), result1.getTimePeriod(2));
// copy the last two items...
result1 = series.createCopy(3, 4);
assertEquals(new Month(11, 2003), result1.getTimePeriod(0));
assertEquals(new Month(12, 2003), result1.getTimePeriod(1));
// copy the last item...
result1 = series.createCopy(4, 4);
assertEquals(new Month(12, 2003), result1.getTimePeriod(0));
}
catch (CloneNotSupportedException e) {
assertTrue(false);
}
// check negative first argument
boolean pass = false;
try {
/* TimeSeries result = */ series.createCopy(-1, 1);
}
catch (IllegalArgumentException e) {
pass = true;
}
catch (CloneNotSupportedException e) {
pass = false;
}
assertTrue(pass);
// check second argument less than first argument
pass = false;
try {
/* TimeSeries result = */ series.createCopy(1, 0);
}
catch (IllegalArgumentException e) {
pass = true;
}
catch (CloneNotSupportedException e) {
pass = false;
}
assertTrue(pass);
TimeSeries series2 = new TimeSeries("Series 2");
try {
TimeSeries series3 = series2.createCopy(99, 999);
assertEquals(0, series3.getItemCount());
}
catch (CloneNotSupportedException e) {
assertTrue(false);
}
}
/**
* Test the setMaximumItemCount() method to ensure that it removes items
* from the series if necessary.
*/
public void testSetMaximumItemCount() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2000), 13.75);
s1.add(new Year(2001), 11.90);
s1.add(new Year(2002), null);
s1.add(new Year(2005), 19.32);
s1.add(new Year(2007), 16.89);
assertTrue(s1.getItemCount() == 5);
s1.setMaximumItemCount(3);
assertTrue(s1.getItemCount() == 3);
TimeSeriesDataItem item = s1.getDataItem(0);
assertTrue(item.getPeriod().equals(new Year(2002)));
assertEquals(16.89, s1.getMinY(), EPSILON);
assertEquals(19.32, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the addOrUpdate() method.
*/
public void testAddOrUpdate() {
TimeSeries s1 = new TimeSeries("S1");
s1.setMaximumItemCount(2);
s1.addOrUpdate(new Year(2000), 100.0);
assertEquals(1, s1.getItemCount());
s1.addOrUpdate(new Year(2001), 101.0);
assertEquals(2, s1.getItemCount());
s1.addOrUpdate(new Year(2001), 102.0);
assertEquals(2, s1.getItemCount());
s1.addOrUpdate(new Year(2002), 103.0);
assertEquals(2, s1.getItemCount());
}
/**
* Test the add branch of the addOrUpdate() method.
*/
public void testAddOrUpdate2() {
TimeSeries s1 = new TimeSeries("S1");
s1.setMaximumItemCount(2);
s1.addOrUpdate(new Year(2010), 1.1);
s1.addOrUpdate(new Year(2011), 2.2);
s1.addOrUpdate(new Year(2012), 3.3);
assertEquals(2, s1.getItemCount());
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Test that the addOrUpdate() method won't allow multiple time period
* classes.
*/
public void testAddOrUpdate3() {
TimeSeries s1 = new TimeSeries("S1");
s1.addOrUpdate(new Year(2010), 1.1);
assertEquals(Year.class, s1.getTimePeriodClass());
boolean pass = false;
try {
s1.addOrUpdate(new Month(1, 2009), 0.0);
}
catch (SeriesException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some more checks for the addOrUpdate() method.
*/
public void testAddOrUpdate4() {
TimeSeries ts = new TimeSeries("S");
TimeSeriesDataItem overwritten = ts.addOrUpdate(new Year(2009), 20.09);
assertNull(overwritten);
overwritten = ts.addOrUpdate(new Year(2009), 1.0);
assertEquals(new Double(20.09), overwritten.getValue());
assertEquals(new Double(1.0), ts.getValue(new Year(2009)));
// changing the overwritten record shouldn't affect the series
overwritten.setValue(null);
assertEquals(new Double(1.0), ts.getValue(new Year(2009)));
TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2010), 20.10);
overwritten = ts.addOrUpdate(item);
assertNull(overwritten);
assertEquals(new Double(20.10), ts.getValue(new Year(2010)));
// changing the item that was added should not change the series
item.setValue(null);
assertEquals(new Double(20.10), ts.getValue(new Year(2010)));
}
/**
* A test for the bug report 1075255.
*/
public void testBug1075255() {
TimeSeries ts = new TimeSeries("dummy");
ts.add(new FixedMillisecond(0L), 0.0);
TimeSeries ts2 = new TimeSeries("dummy2");
ts2.add(new FixedMillisecond(0L), 1.0);
try {
ts.addAndOrUpdate(ts2);
}
catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
assertEquals(1, ts.getItemCount());
}
/**
* A test for bug 1832432.
*/
public void testBug1832432() {
TimeSeries s1 = new TimeSeries("Series");
TimeSeries s2 = null;
try {
s2 = (TimeSeries) s1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(s1 != s2);
assertTrue(s1.getClass() == s2.getClass());
assertTrue(s1.equals(s2));
// test independence
s1.add(new Day(1, 1, 2007), 100.0);
assertFalse(s1.equals(s2));
}
/**
* Some checks for the getIndex() method.
*/
public void testGetIndex() {
TimeSeries series = new TimeSeries("Series");
assertEquals(-1, series.getIndex(new Month(1, 2003)));
series.add(new Month(1, 2003), 45.0);
assertEquals(0, series.getIndex(new Month(1, 2003)));
assertEquals(-1, series.getIndex(new Month(12, 2002)));
assertEquals(-2, series.getIndex(new Month(2, 2003)));
series.add(new Month(3, 2003), 55.0);
assertEquals(-1, series.getIndex(new Month(12, 2002)));
assertEquals(0, series.getIndex(new Month(1, 2003)));
assertEquals(-2, series.getIndex(new Month(2, 2003)));
assertEquals(1, series.getIndex(new Month(3, 2003)));
assertEquals(-3, series.getIndex(new Month(4, 2003)));
}
/**
* Some checks for the getDataItem(int) method.
*/
public void testGetDataItem1() {
TimeSeries series = new TimeSeries("S");
// can't get anything yet...just an exception
boolean pass = false;
try {
/*TimeSeriesDataItem item =*/ series.getDataItem(0);
}
catch (IndexOutOfBoundsException e) {
pass = true;
}
assertTrue(pass);
series.add(new Year(2006), 100.0);
TimeSeriesDataItem item = series.getDataItem(0);
assertEquals(new Year(2006), item.getPeriod());
pass = false;
try {
/*item = */series.getDataItem(-1);
}
catch (IndexOutOfBoundsException e) {
pass = true;
}
assertTrue(pass);
pass = false;
try {
/*item = */series.getDataItem(1);
}
catch (IndexOutOfBoundsException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the getDataItem(RegularTimePeriod) method.
*/
public void testGetDataItem2() {
TimeSeries series = new TimeSeries("S");
assertNull(series.getDataItem(new Year(2006)));
// try a null argument
boolean pass = false;
try {
/* TimeSeriesDataItem item = */ series.getDataItem(null);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the removeAgedItems() method.
*/
public void testRemoveAgedItems() {
TimeSeries series = new TimeSeries("Test Series");
series.addChangeListener(this);
assertEquals(Long.MAX_VALUE, series.getMaximumItemAge());
assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount());
this.gotSeriesChangeEvent = false;
// test empty series
series.removeAgedItems(true);
assertEquals(0, series.getItemCount());
assertFalse(this.gotSeriesChangeEvent);
// test series with one item
series.add(new Year(1999), 1.0);
series.setMaximumItemAge(0);
this.gotSeriesChangeEvent = false;
series.removeAgedItems(true);
assertEquals(1, series.getItemCount());
assertFalse(this.gotSeriesChangeEvent);
// test series with two items
series.setMaximumItemAge(10);
series.add(new Year(2001), 2.0);
this.gotSeriesChangeEvent = false;
series.setMaximumItemAge(2);
assertEquals(2, series.getItemCount());
assertEquals(0, series.getIndex(new Year(1999)));
assertFalse(this.gotSeriesChangeEvent);
series.setMaximumItemAge(1);
assertEquals(1, series.getItemCount());
assertEquals(0, series.getIndex(new Year(2001)));
assertTrue(this.gotSeriesChangeEvent);
}
/**
* Some checks for the removeAgedItems(long, boolean) method.
*/
public void testRemoveAgedItems2() {
long y2006 = 1157087372534L; // milliseconds somewhere in 2006
TimeSeries series = new TimeSeries("Test Series");
series.addChangeListener(this);
assertEquals(Long.MAX_VALUE, series.getMaximumItemAge());
assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount());
this.gotSeriesChangeEvent = false;
// test empty series
series.removeAgedItems(y2006, true);
assertEquals(0, series.getItemCount());
assertFalse(this.gotSeriesChangeEvent);
// test a series with 1 item
series.add(new Year(2004), 1.0);
series.setMaximumItemAge(1);
this.gotSeriesChangeEvent = false;
series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true);
assertEquals(1, series.getItemCount());
assertFalse(this.gotSeriesChangeEvent);
series.removeAgedItems(y2006, true);
assertEquals(0, series.getItemCount());
assertTrue(this.gotSeriesChangeEvent);
// test a series with two items
series.setMaximumItemAge(2);
series.add(new Year(2003), 1.0);
series.add(new Year(2005), 2.0);
assertEquals(2, series.getItemCount());
this.gotSeriesChangeEvent = false;
assertEquals(2, series.getItemCount());
series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true);
assertEquals(2, series.getItemCount());
assertFalse(this.gotSeriesChangeEvent);
series.removeAgedItems(y2006, true);
assertEquals(1, series.getItemCount());
assertTrue(this.gotSeriesChangeEvent);
}
/**
* Calling removeAgedItems() on an empty series should not throw any
* exception.
*/
public void testRemoveAgedItems3() {
TimeSeries s = new TimeSeries("Test");
boolean pass = true;
try {
s.removeAgedItems(0L, true);
}
catch (Exception e) {
pass = false;
}
assertTrue(pass);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count.
*/
public void testRemoveAgedItems4() {
TimeSeries s1 = new TimeSeries("S1");
s1.setMaximumItemAge(2);
s1.add(new Year(2010), 1.1);
s1.add(new Year(2011), 2.2);
s1.add(new Year(2012), 3.3);
s1.add(new Year(2013), 2.5);
assertEquals(3, s1.getItemCount());
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Check that the item bounds are determined correctly after a call to
* removeAgedItems().
*/
public void testRemoveAgedItems5() {
TimeSeries s1 = new TimeSeries("S1");
s1.setMaximumItemAge(4);
s1.add(new Year(2010), 1.1);
s1.add(new Year(2011), 2.2);
s1.add(new Year(2012), 3.3);
s1.add(new Year(2013), 2.5);
s1.removeAgedItems(new Year(2015).getMiddleMillisecond(), true);
assertEquals(3, s1.getItemCount());
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some simple checks for the hashCode() method.
*/
public void testHashCode() {
TimeSeries s1 = new TimeSeries("Test");
TimeSeries s2 = new TimeSeries("Test");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(new Day(1, 1, 2007), 500.0);
s2.add(new Day(1, 1, 2007), 500.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(new Day(2, 1, 2007), null);
s2.add(new Day(2, 1, 2007), null);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(new Day(5, 1, 2007), 111.0);
s2.add(new Day(5, 1, 2007), 111.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(new Day(9, 1, 2007), 1.0);
s2.add(new Day(9, 1, 2007), 1.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
}
/**
* Test for bug report 1864222.
*/
public void testBug1864222() {
TimeSeries s = new TimeSeries("S");
s.add(new Day(19, 8, 2005), 1);
s.add(new Day(31, 1, 2006), 1);
boolean pass = true;
try {
s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006));
}
catch (CloneNotSupportedException e) {
pass = false;
}
assertTrue(pass);
}
private static final double EPSILON = 0.0000000001;
/**
* Some checks for the getMinY() method.
*/
public void testGetMinY() {
TimeSeries s1 = new TimeSeries("S1");
assertTrue(Double.isNaN(s1.getMinY()));
s1.add(new Year(2008), 1.1);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(new Year(2009), 2.2);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(new Year(2000), 99.9);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(new Year(2002), -1.1);
assertEquals(-1.1, s1.getMinY(), EPSILON);
s1.add(new Year(2003), null);
assertEquals(-1.1, s1.getMinY(), EPSILON);
s1.addOrUpdate(new Year(2002), null);
assertEquals(1.1, s1.getMinY(), EPSILON);
}
/**
* Some checks for the getMaxY() method.
*/
public void testGetMaxY() {
TimeSeries s1 = new TimeSeries("S1");
assertTrue(Double.isNaN(s1.getMaxY()));
s1.add(new Year(2008), 1.1);
assertEquals(1.1, s1.getMaxY(), EPSILON);
s1.add(new Year(2009), 2.2);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.add(new Year(2000), 99.9);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(new Year(2002), -1.1);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(new Year(2003), null);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.addOrUpdate(new Year(2000), null);
assertEquals(2.2, s1.getMaxY(), EPSILON);
}
/**
* A test for the clear method.
*/
public void testClear() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2009), 1.1);
s1.add(new Year(2010), 2.2);
assertEquals(2, s1.getItemCount());
s1.clear();
assertEquals(0, s1.getItemCount());
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count and a new value is added.
*/
public void testAdd() {
TimeSeries s1 = new TimeSeries("S1");
s1.setMaximumItemCount(2);
s1.add(new Year(2010), 1.1);
s1.add(new Year(2011), 2.2);
s1.add(new Year(2012), 3.3);
assertEquals(2, s1.getItemCount());
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the update(RegularTimePeriod...method).
*/
public void testUpdate_RegularTimePeriod() {
TimeSeries s1 = new TimeSeries("S1");
s1.add(new Year(2010), 1.1);
s1.add(new Year(2011), 2.2);
s1.add(new Year(2012), 3.3);
s1.update(new Year(2012), 4.4);
assertEquals(4.4, s1.getMaxY(), EPSILON);
s1.update(new Year(2010), 0.5);
assertEquals(0.5, s1.getMinY(), EPSILON);
s1.update(new Year(2012), null);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.update(new Year(2010), null);
assertEquals(2.2, s1.getMinY(), EPSILON);
}
/**
* Create a TimeSeriesDataItem, add it to a TimeSeries. Now, modifying
* the original TimeSeriesDataItem should NOT affect the TimeSeries.
*/
public void testAdd_TimeSeriesDataItem() {
TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2009), 1.0);
TimeSeries series = new TimeSeries("S1");
series.add(item);
assertTrue(item.equals(series.getDataItem(0)));
item.setValue(new Double(99.9));
assertFalse(item.equals(series.getDataItem(0)));
}
}
|
package com.ea.orbit.web.diagnostics;
import com.ea.orbit.container.Container;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Date;
@Path("/orbit/diagnostics")
public class DiagnosticsHandler
{
@Inject
Container orbitContainer;
public static class HealthcheckResult
{
private Boolean alive = true;
private Date serverTime = new Date();
public Boolean getAlive()
{
return alive;
}
public void setAlive(Boolean alive)
{
this.alive = alive;
}
public Date getServerTime()
{
return serverTime;
}
public void setServerTime(Date serverTime)
{
this.serverTime = serverTime;
}
}
@GET
@Path("/healthcheck")
@Produces(MediaType.APPLICATION_JSON)
public HealthcheckResult getHealthCheck()
{
final HealthcheckResult healthcheckResult = new HealthcheckResult();
healthcheckResult.setAlive(orbitContainer.getContainerState() == Container.ContainerState.STARTED);
return healthcheckResult;
}
}
|
package com.netcracker.controllers;
import com.netcracker.dto.AttachmentDtoInfo;
import com.netcracker.entities.Attachment;
import com.netcracker.entities.User;
import com.netcracker.services.Converter;
import com.netcracker.services.impl.AttachmentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
/**
* The controller, whose methods provide ways of interacting with
* an authorized user comments. It is worth noting that in
* this controller is not the method getComment (), as the comments
* received getFullLabelInfo perform () method of the class
* {@link com.netcracker.controllers.LabelController}.
*
* This controller is responsible for:
* UC17 - Adding attachments; +
* UC18 - Deleting attachments; +
*
* @author Oveian Egor
* @author Kozhuchar Alexander
*/
@RestController
@RequestMapping("/labels/{labelId}/attachments")
public class AttachmentController {
@Autowired
private AttachmentServiceImpl attachmentService;
@Autowired
private Converter converter;
/**
* Method of attachments extraction, depending on which label id came from client.
*
* Described in:
* FR14 - The system should provide the ability to view attachments;
* FR15 - The system should provide display of attachments in accordance
* with the order they are added to the label
*
* @param labelId
* @return list of {@link AttachmentDtoInfo} - objects, that contain information about existing attachments.
*/
@GetMapping
public List<AttachmentDtoInfo> getAttachmentsByLabel(@PathVariable(name = "labelId") Long labelId) {
return attachmentService.getAttachmentsByLabel(labelId)
.stream().map(a -> converter.convertAttachmentToDtoInfo(a))
.collect(Collectors.toList());
}
/**
* Method of adding attachment to current label
*
* Described in:
* FR57 - The system should provide the authorized user the ability to attach files to their label.
* FR59 - The system should provide adding file attachments from the user file system.
*
* @param attach - object that contains bytes of attachment.
* @return {@link AttachmentDtoInfo} - object, that contains information about created attachment.
*/
@PostMapping("/add")
public AttachmentDtoInfo addAttachment(@PathVariable(name = "labelId") Long labelId, @RequestParam("attach")MultipartFile attach) throws IOException {
User user = (User) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
String uploadRootPath = "/var/www/resources/upload/"+labelId;
File uploadRootDir = new File(uploadRootPath);
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + attach.getOriginalFilename());
attach.transferTo(serverFile);
Attachment dbRecord = attachmentService.addAttachment(labelId,user.getUserId(),attach.getOriginalFilename());
return converter.convertAttachmentToDtoInfo(dbRecord);
}
/**
* Method of attachment extraction by its id
*
* Described in:
* nowhere
*
* @param labelId
* @param attachmentId
* @return {@link AttachmentDtoInfo} - object, that contains information about existing attachment.
*/
@GetMapping("/{attachmentId}")
public AttachmentDtoInfo getAttachment(@PathVariable(name = "labelId") Long labelId,
@PathVariable(name = "attachmentId") Long attachmentId) {
return null;
}
/**
* Method of deleting attachment from specified label.
*
* Described in:
* FR61 - The system should provide the authorized user to remove attached file from their label.
*
* @param attachmentId
* @return status of deleting attachment from database
*/
@DeleteMapping("/{attachmentId}")
public Integer deleteAttachment(@PathVariable(name = "labelId") Long labelId,
@PathVariable(name = "attachmentId") Long attachmentId) {
return 0;
}
}
|
package org.wikipedia.analytics;
import android.net.Uri;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.WikipediaApp;
import org.wikipedia.concurrency.SaneAsyncTask;
/**
* Base class for all various types of events that are logged to EventLogging.
*
* Each Schema has its own class, and has its own constructor that makes it easy
* to call from everywhere without having to duplicate param info at all places.
* Updating schemas / revisions is also easier this way.
*/
public class EventLoggingEvent {
private static final String EVENTLOG_URL = "https://bits.wikimedia.org/event.gif";
/* Use for testing: */
private final JSONObject data;
private final String userAgent;
/**
* Create an EventLoggingEvent that logs to a given revision of a given schema with
* the gven data payload.
*
* @param schema Schema name (as specified on meta.wikimedia.org)
* @param revID Revision of the schema to log to
* @param wiki DBName (enwiki, dewiki, etc) of the wiki in which we are operating
* @param userAgent User-Agent string to use for this request
* @param eventData Data for the actual event payload. Considered to be
*
*/
public EventLoggingEvent(String schema, int revID, String wiki, String userAgent, JSONObject eventData) {
data = new JSONObject();
try {
data.put("schema", schema);
data.put("revision", revID);
data.put("wiki", wiki);
data.put("event", eventData);
} catch (JSONException e) {
throw new RuntimeException(e);
}
this.userAgent = userAgent;
}
/**
* Log the current event.
*
* Returns immediately after queueing the network request in the background.
*/
public void log() {
new LogEventTask(data).execute();
}
private class LogEventTask extends SaneAsyncTask<Integer> {
private final JSONObject data;
public LogEventTask(JSONObject data) {
super(SINGLE_THREAD);
this.data = data;
}
@Override
public Integer performTask() throws Throwable {
String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http");
String dataURL = Uri.parse(elUrl)
.buildUpon().query(data.toString())
.build().toString();
return HttpRequest.get(dataURL).header("User-Agent", userAgent).code();
}
@Override
public void onCatch(Throwable caught) {
// Do nothing bad. EL data is ok to lose.
Log.d(Funnel.ANALYTICS_TAG, "Lost EL data: " + data.toString());
}
}
}
|
package com.intellij.updater;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.testFramework.rules.TempDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import java.io.File;
public abstract class UpdaterTestCase {
protected static class TestUpdaterUI extends ConsoleUpdaterUI {
public boolean cancelled = false;
@Override public void setDescription(String oldBuildDesc, String newBuildDesc) { }
@Override public void startProcess(String title) { }
@Override public void checkCancelled() throws OperationCancelledException { if (cancelled) throw new OperationCancelledException(); }
@Override public void showError(String message) { }
}
@Rule public TempDirectory tempDir = new TempDirectory();
protected File dataDir;
protected TestUpdaterUI TEST_UI;
protected CheckSums CHECKSUMS;
@Before
public void setUp() throws Exception {
dataDir = PathManagerEx.findFileUnderCommunityHome("updater/testData");
Runner.checkCaseSensitivity(dataDir.getPath());
Runner.initTestLogger();
TEST_UI = new TestUpdaterUI();
CHECKSUMS = new CheckSums(
new File(dataDir, "Readme.txt").length() == 7132,
File.separatorChar == '\\');
}
@After
public void tearDown() throws Exception {
Utils.cleanup();
}
public File getTempFile(String fileName) {
return new File(tempDir.getRoot(), fileName);
}
@SuppressWarnings("FieldMayBeStatic")
protected static class CheckSums {
public final long README_TXT;
public final long IDEA_BAT;
public final long ANNOTATIONS_JAR = 2119442657L;
public final long ANNOTATIONS_JAR_BIN = 2525796836L;
public final long ANNOTATIONS_CHANGED_JAR = 4088078858L;
public final long ANNOTATIONS_CHANGED_JAR_BIN = 2587736223L;
public final long BOOT_JAR = 3018038682L;
public final long BOOT_WITH_DIRECTORY_BECOMES_FILE_JAR = 1972168924;
public final long BOOT2_JAR = 2406818996L;
public final long BOOT2_CHANGED_WITH_UNCHANGED_CONTENT_JAR = 2406818996L;
public final long BOOTSTRAP_JAR = 2082851308L;
public final long BOOTSTRAP_JAR_BIN = 2745721972L;
public final long BOOTSTRAP_DELETED_JAR = 544883981L;
public final long LINK_TO_README_TXT = 2305843011042707672L;
public final long LINK_TO_DOT_README_TXT;
public CheckSums(boolean crLfs, boolean backwardSlashes) {
README_TXT = crLfs ? 1272723667L : 7256327L;
IDEA_BAT = crLfs ? 3088608749L : 1493936069L;
LINK_TO_DOT_README_TXT = backwardSlashes ? 2305843011210142148L : 2305843009503057206L;
}
}
}
|
package org.jfree.chart;
import java.awt.AWTEvent;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.datatransfer.Clipboard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.EventListenerList;
import org.jfree.chart.editor.ChartEditor;
import org.jfree.chart.editor.ChartEditorManager;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.panel.Overlay;
import org.jfree.chart.event.OverlayChangeEvent;
import org.jfree.chart.event.OverlayChangeListener;
import org.jfree.chart.plot.Pannable;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.Zoomable;
import org.jfree.chart.util.ResourceBundleWrapper;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.ExtensionFileFilter;
/**
* A Swing GUI component for displaying a {@link JFreeChart} object.
* <P>
* The panel registers with the chart to receive notification of changes to any
* component of the chart. The chart is redrawn automatically whenever this
* notification is received.
*/
public class ChartPanel extends JPanel implements ChartChangeListener,
ChartProgressListener, ActionListener, MouseListener,
MouseMotionListener, OverlayChangeListener, Printable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 6046366297214274674L;
/**
* Default setting for buffer usage. The default has been changed to
* <code>true</code> from version 1.0.13 onwards, because of a severe
* performance problem with drawing the zoom rectangle using XOR (which
* now happens only when the buffer is NOT used).
*/
public static final boolean DEFAULT_BUFFER_USED = true;
/** The default panel width. */
public static final int DEFAULT_WIDTH = 680;
/** The default panel height. */
public static final int DEFAULT_HEIGHT = 420;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768;
/** The minimum size required to perform a zoom on a rectangle */
public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;
/** Properties action command. */
public static final String PROPERTIES_COMMAND = "PROPERTIES";
/**
* Copy action command.
*
* @since 1.0.13
*/
public static final String COPY_COMMAND = "COPY";
/** Save action command. */
public static final String SAVE_COMMAND = "SAVE";
/** Print action command. */
public static final String PRINT_COMMAND = "PRINT";
/** Zoom in (both axes) action command. */
public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH";
/** Zoom in (domain axis only) action command. */
public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN";
/** Zoom in (range axis only) action command. */
public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE";
/** Zoom out (both axes) action command. */
public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH";
/** Zoom out (domain axis only) action command. */
public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH";
/** Zoom out (range axis only) action command. */
public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH";
/** Zoom reset (both axes) action command. */
public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH";
/** Zoom reset (domain axis only) action command. */
public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN";
/** Zoom reset (range axis only) action command. */
public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE";
/** The chart that is displayed in the panel. */
private JFreeChart chart;
/** Storage for registered (chart) mouse listeners. */
private transient EventListenerList chartMouseListeners;
/** A flag that controls whether or not the off-screen buffer is used. */
private boolean useBuffer;
/** A flag that indicates that the buffer should be refreshed. */
private boolean refreshBuffer;
/** A buffer for the rendered chart. */
private transient Image chartBuffer;
/** The height of the chart buffer. */
private int chartBufferHeight;
/** The width of the chart buffer. */
private int chartBufferWidth;
/**
* The minimum width for drawing a chart (uses scaling for smaller widths).
*/
private int minimumDrawWidth;
/**
* The minimum height for drawing a chart (uses scaling for smaller
* heights).
*/
private int minimumDrawHeight;
/**
* The maximum width for drawing a chart (uses scaling for bigger
* widths).
*/
private int maximumDrawWidth;
/**
* The maximum height for drawing a chart (uses scaling for bigger
* heights).
*/
private int maximumDrawHeight;
/** The popup menu for the frame. */
private JPopupMenu popup;
/** The drawing info collected the last time the chart was drawn. */
private ChartRenderingInfo info;
/** The chart anchor point. */
private Point2D anchor;
/** The scale factor used to draw the chart. */
private double scaleX;
/** The scale factor used to draw the chart. */
private double scaleY;
/** The plot orientation. */
private PlotOrientation orientation = PlotOrientation.VERTICAL;
/** A flag that controls whether or not domain zooming is enabled. */
private boolean domainZoomable = false;
/** A flag that controls whether or not range zooming is enabled. */
private boolean rangeZoomable = false;
/**
* The zoom rectangle starting point (selected by the user with a mouse
* click). This is a point on the screen, not the chart (which may have
* been scaled up or down to fit the panel).
*/
private Point2D zoomPoint = null;
/** The zoom rectangle (selected by the user with the mouse). */
private transient Rectangle2D zoomRectangle = null;
/** Controls if the zoom rectangle is drawn as an outline or filled. */
private boolean fillZoomRectangle = true;
/** The minimum distance required to drag the mouse to trigger a zoom. */
private int zoomTriggerDistance;
/** A flag that controls whether or not horizontal tracing is enabled. */
private boolean horizontalAxisTrace = false;
/** A flag that controls whether or not vertical tracing is enabled. */
private boolean verticalAxisTrace = false;
/** A vertical trace line. */
private transient Line2D verticalTraceLine;
/** A horizontal trace line. */
private transient Line2D horizontalTraceLine;
/** Menu item for zooming in on a chart (both axes). */
private JMenuItem zoomInBothMenuItem;
/** Menu item for zooming in on a chart (domain axis). */
private JMenuItem zoomInDomainMenuItem;
/** Menu item for zooming in on a chart (range axis). */
private JMenuItem zoomInRangeMenuItem;
/** Menu item for zooming out on a chart. */
private JMenuItem zoomOutBothMenuItem;
/** Menu item for zooming out on a chart (domain axis). */
private JMenuItem zoomOutDomainMenuItem;
/** Menu item for zooming out on a chart (range axis). */
private JMenuItem zoomOutRangeMenuItem;
/** Menu item for resetting the zoom (both axes). */
private JMenuItem zoomResetBothMenuItem;
/** Menu item for resetting the zoom (domain axis only). */
private JMenuItem zoomResetDomainMenuItem;
/** Menu item for resetting the zoom (range axis only). */
private JMenuItem zoomResetRangeMenuItem;
/**
* The default directory for saving charts to file.
*
* @since 1.0.7
*/
private File defaultDirectoryForSaveAs;
/** A flag that controls whether or not file extensions are enforced. */
private boolean enforceFileExtensions;
/** A flag that indicates if original tooltip delays are changed. */
private boolean ownToolTipDelaysActive;
/** Original initial tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipInitialDelay;
/** Original reshow tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipReshowDelay;
/** Original dismiss tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipDismissDelay;
/** Own initial tooltip delay to be used in this chart panel. */
private int ownToolTipInitialDelay;
/** Own reshow tooltip delay to be used in this chart panel. */
private int ownToolTipReshowDelay;
/** Own dismiss tooltip delay to be used in this chart panel. */
private int ownToolTipDismissDelay;
/** The factor used to zoom in on an axis range. */
private double zoomInFactor = 0.5;
/** The factor used to zoom out on an axis range. */
private double zoomOutFactor = 2.0;
/**
* A flag that controls whether zoom operations are centred on the
* current anchor point, or the centre point of the relevant axis.
*
* @since 1.0.7
*/
private boolean zoomAroundAnchor;
/**
* The paint used to draw the zoom rectangle outline.
*
* @since 1.0.13
*/
private transient Paint zoomOutlinePaint;
/**
* The zoom fill paint (should use transparency).
*
* @since 1.0.13
*/
private transient Paint zoomFillPaint;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundleWrapper.getBundle(
"org.jfree.chart.LocalizationBundle");
/**
* Temporary storage for the width and height of the chart
* drawing area during panning.
*/
private double panW, panH;
/** The last mouse position during panning. */
private Point panLast;
/**
* The mask for mouse events to trigger panning.
*
* @since 1.0.13
*/
private int panMask = InputEvent.CTRL_MASK;
/**
* A list of overlays for the panel.
*
* @since 1.0.13
*/
private List overlays;
/**
* Constructs a panel that displays the specified chart.
*
* @param chart the chart.
*/
public ChartPanel(JFreeChart chart) {
this(
chart,
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a panel containing a chart. The <code>useBuffer</code> flag
* controls whether or not an offscreen <code>BufferedImage</code> is
* maintained for the chart. If the buffer is used, more memory is
* consumed, but panel repaints will be a lot quicker in cases where the
* chart itself hasn't changed (for example, when another frame is moved
* to reveal the panel). WARNING: If you set the <code>useBuffer</code>
* flag to false, note that the mouse zooming rectangle will (in that case)
* be drawn using XOR, and there is a SEVERE performance problem with that
* on JRE6 on Windows.
*
* @param chart the chart.
* @param useBuffer a flag controlling whether or not an off-screen buffer
* is used (read the warning above before setting this
* to <code>false</code>).
*/
public ChartPanel(JFreeChart chart, boolean useBuffer) {
this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should
* be added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart,
boolean properties,
boolean save,
boolean print,
boolean zoom,
boolean tooltips) {
this(chart,
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED,
properties,
save,
print,
zoom,
tooltips
);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean save, boolean print, boolean zoom, boolean tooltips) {
this(chart, width, height, minimumDrawWidth, minimumDrawHeight,
maximumDrawWidth, maximumDrawHeight, useBuffer, properties,
true, save, print, zoom, tooltips);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param copy a flag indicating whether or not a copy option should be
* available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*
* @since 1.0.13
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean copy, boolean save, boolean print, boolean zoom,
boolean tooltips) {
setChart(chart);
this.chartMouseListeners = new EventListenerList();
this.info = new ChartRenderingInfo();
setPreferredSize(new Dimension(width, height));
this.useBuffer = useBuffer;
this.refreshBuffer = false;
this.minimumDrawWidth = minimumDrawWidth;
this.minimumDrawHeight = minimumDrawHeight;
this.maximumDrawWidth = maximumDrawWidth;
this.maximumDrawHeight = maximumDrawHeight;
this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE;
// set up popup menu...
this.popup = null;
if (properties || copy || save || print || zoom) {
this.popup = createPopupMenu(properties, copy, save, print, zoom);
}
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
setDisplayToolTips(tooltips);
addMouseListener(this);
addMouseMotionListener(this);
this.defaultDirectoryForSaveAs = null;
this.enforceFileExtensions = true;
// initialize ChartPanel-specific tool tip delays with
// values the from ToolTipManager.sharedInstance()
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.ownToolTipInitialDelay = ttm.getInitialDelay();
this.ownToolTipDismissDelay = ttm.getDismissDelay();
this.ownToolTipReshowDelay = ttm.getReshowDelay();
this.zoomAroundAnchor = false;
this.zoomOutlinePaint = Color.blue;
this.zoomFillPaint = new Color(0, 0, 255, 63);
this.panMask = InputEvent.CTRL_MASK;
// for MacOSX we can't use the CTRL key for mouse drags, see:
String osName = System.getProperty("os.name").toLowerCase();
if (osName.startsWith("mac os x")) {
this.panMask = InputEvent.ALT_MASK;
}
this.overlays = new java.util.ArrayList();
}
/**
* Returns the chart contained in the panel.
*
* @return The chart (possibly <code>null</code>).
*/
public JFreeChart getChart() {
return this.chart;
}
/**
* Sets the chart that is displayed in the panel.
*
* @param chart the chart (<code>null</code> permitted).
*/
public void setChart(JFreeChart chart) {
// stop listening for changes to the existing chart
if (this.chart != null) {
this.chart.removeChangeListener(this);
this.chart.removeProgressListener(this);
}
// add the new chart
this.chart = chart;
if (chart != null) {
this.chart.addChangeListener(this);
this.chart.addProgressListener(this);
Plot plot = chart.getPlot();
this.domainZoomable = false;
this.rangeZoomable = false;
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = z.isDomainZoomable();
this.rangeZoomable = z.isRangeZoomable();
this.orientation = z.getOrientation();
}
}
else {
this.domainZoomable = false;
this.rangeZoomable = false;
}
if (this.useBuffer) {
this.refreshBuffer = true;
}
repaint();
}
/**
* Returns the minimum drawing width for charts.
* <P>
* If the width available on the panel is less than this, then the chart is
* drawn at the minimum width then scaled down to fit.
*
* @return The minimum drawing width.
*/
public int getMinimumDrawWidth() {
return this.minimumDrawWidth;
}
/**
* Sets the minimum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* less than this amount, the chart will be drawn using the minimum width
* then scaled down to fit the available space.
*
* @param width The width.
*/
public void setMinimumDrawWidth(int width) {
this.minimumDrawWidth = width;
}
/**
* Returns the maximum drawing width for charts.
* <P>
* If the width available on the panel is greater than this, then the chart
* is drawn at the maximum width then scaled up to fit.
*
* @return The maximum drawing width.
*/
public int getMaximumDrawWidth() {
return this.maximumDrawWidth;
}
/**
* Sets the maximum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* greater than this amount, the chart will be drawn using the maximum
* width then scaled up to fit the available space.
*
* @param width The width.
*/
public void setMaximumDrawWidth(int width) {
this.maximumDrawWidth = width;
}
/**
* Returns the minimum drawing height for charts.
* <P>
* If the height available on the panel is less than this, then the chart
* is drawn at the minimum height then scaled down to fit.
*
* @return The minimum drawing height.
*/
public int getMinimumDrawHeight() {
return this.minimumDrawHeight;
}
/**
* Sets the minimum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* less than this amount, the chart will be drawn using the minimum height
* then scaled down to fit the available space.
*
* @param height The height.
*/
public void setMinimumDrawHeight(int height) {
this.minimumDrawHeight = height;
}
/**
* Returns the maximum drawing height for charts.
* <P>
* If the height available on the panel is greater than this, then the
* chart is drawn at the maximum height then scaled up to fit.
*
* @return The maximum drawing height.
*/
public int getMaximumDrawHeight() {
return this.maximumDrawHeight;
}
/**
* Sets the maximum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* greater than this amount, the chart will be drawn using the maximum
* height then scaled up to fit the available space.
*
* @param height The height.
*/
public void setMaximumDrawHeight(int height) {
this.maximumDrawHeight = height;
}
/**
* Returns the X scale factor for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleX() {
return this.scaleX;
}
/**
* Returns the Y scale factory for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleY() {
return this.scaleY;
}
/**
* Returns the anchor point.
*
* @return The anchor point (possibly <code>null</code>).
*/
public Point2D getAnchor() {
return this.anchor;
}
/**
* Sets the anchor point. This method is provided for the use of
* subclasses, not end users.
*
* @param anchor the anchor point (<code>null</code> permitted).
*/
protected void setAnchor(Point2D anchor) {
this.anchor = anchor;
}
/**
* Returns the popup menu.
*
* @return The popup menu.
*/
public JPopupMenu getPopupMenu() {
return this.popup;
}
/**
* Sets the popup menu for the panel.
*
* @param popup the popup menu (<code>null</code> permitted).
*/
public void setPopupMenu(JPopupMenu popup) {
this.popup = popup;
}
/**
* Returns the chart rendering info from the most recent chart redraw.
*
* @return The chart rendering info.
*/
public ChartRenderingInfo getChartRenderingInfo() {
return this.info;
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag <code>true</code> enables zooming and rectangle fill on
* zoom.
*/
public void setMouseZoomable(boolean flag) {
setMouseZoomable(flag, true);
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag <code>true</code> if zooming enabled
* @param fillRectangle <code>true</code> if zoom rectangle is filled,
* false if rectangle is shown as outline only.
*/
public void setMouseZoomable(boolean flag, boolean fillRectangle) {
setDomainZoomable(flag);
setRangeZoomable(flag);
setFillZoomRectangle(fillRectangle);
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the domain axis.
*
* @return A boolean.
*/
public boolean isDomainZoomable() {
return this.domainZoomable;
}
/**
* Sets the flag that controls whether or not zooming is enable for the
* domain axis. A check is made to ensure that the current plot supports
* zooming for the domain values.
*
* @param flag <code>true</code> enables zooming if possible.
*/
public void setDomainZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = flag && (z.isDomainZoomable());
}
}
else {
this.domainZoomable = false;
}
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the range axis.
*
* @return A boolean.
*/
public boolean isRangeZoomable() {
return this.rangeZoomable;
}
/**
* A flag that controls mouse-based zooming on the vertical axis.
*
* @param flag <code>true</code> enables zooming.
*/
public void setRangeZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.rangeZoomable = flag && (z.isRangeZoomable());
}
}
else {
this.rangeZoomable = false;
}
}
/**
* Returns the flag that controls whether or not the zoom rectangle is
* filled when drawn.
*
* @return A boolean.
*/
public boolean getFillZoomRectangle() {
return this.fillZoomRectangle;
}
/**
* A flag that controls how the zoom rectangle is drawn.
*
* @param flag <code>true</code> instructs to fill the rectangle on
* zoom, otherwise it will be outlined.
*/
public void setFillZoomRectangle(boolean flag) {
this.fillZoomRectangle = flag;
}
/**
* Returns the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @return The distance (in Java2D units).
*/
public int getZoomTriggerDistance() {
return this.zoomTriggerDistance;
}
/**
* Sets the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @param distance the distance (in Java2D units).
*/
public void setZoomTriggerDistance(int distance) {
this.zoomTriggerDistance = distance;
}
/**
* Returns the flag that controls whether or not a horizontal axis trace
* line is drawn over the plot area at the current mouse location.
*
* @return A boolean.
*/
public boolean getHorizontalAxisTrace() {
return this.horizontalAxisTrace;
}
/**
* A flag that controls trace lines on the horizontal axis.
*
* @param flag <code>true</code> enables trace lines for the mouse
* pointer on the horizontal axis.
*/
public void setHorizontalAxisTrace(boolean flag) {
this.horizontalAxisTrace = flag;
}
/**
* Returns the horizontal trace line.
*
* @return The horizontal trace line (possibly <code>null</code>).
*/
protected Line2D getHorizontalTraceLine() {
return this.horizontalTraceLine;
}
/**
* Sets the horizontal trace line.
*
* @param line the line (<code>null</code> permitted).
*/
protected void setHorizontalTraceLine(Line2D line) {
this.horizontalTraceLine = line;
}
/**
* Returns the flag that controls whether or not a vertical axis trace
* line is drawn over the plot area at the current mouse location.
*
* @return A boolean.
*/
public boolean getVerticalAxisTrace() {
return this.verticalAxisTrace;
}
/**
* A flag that controls trace lines on the vertical axis.
*
* @param flag <code>true</code> enables trace lines for the mouse
* pointer on the vertical axis.
*/
public void setVerticalAxisTrace(boolean flag) {
this.verticalAxisTrace = flag;
}
/**
* Returns the vertical trace line.
*
* @return The vertical trace line (possibly <code>null</code>).
*/
protected Line2D getVerticalTraceLine() {
return this.verticalTraceLine;
}
/**
* Sets the vertical trace line.
*
* @param line the line (<code>null</code> permitted).
*/
protected void setVerticalTraceLine(Line2D line) {
this.verticalTraceLine = line;
}
/**
* Returns the default directory for the "save as" option.
*
* @return The default directory (possibly <code>null</code>).
*
* @since 1.0.7
*/
public File getDefaultDirectoryForSaveAs() {
return this.defaultDirectoryForSaveAs;
}
/**
* Sets the default directory for the "save as" option. If you set this
* to <code>null</code>, the user's default directory will be used.
*
* @param directory the directory (<code>null</code> permitted).
*
* @since 1.0.7
*/
public void setDefaultDirectoryForSaveAs(File directory) {
if (directory != null) {
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"The 'directory' argument is not a directory.");
}
}
this.defaultDirectoryForSaveAs = directory;
}
/**
* Returns <code>true</code> if file extensions should be enforced, and
* <code>false</code> otherwise.
*
* @return The flag.
*
* @see #setEnforceFileExtensions(boolean)
*/
public boolean isEnforceFileExtensions() {
return this.enforceFileExtensions;
}
/**
* Sets a flag that controls whether or not file extensions are enforced.
*
* @param enforce the new flag value.
*
* @see #isEnforceFileExtensions()
*/
public void setEnforceFileExtensions(boolean enforce) {
this.enforceFileExtensions = enforce;
}
/**
* Returns the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @return A boolean.
*
* @since 1.0.7
*
* @see #setZoomAroundAnchor(boolean)
*/
public boolean getZoomAroundAnchor() {
return this.zoomAroundAnchor;
}
/**
* Sets the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @param zoomAroundAnchor the new flag value.
*
* @since 1.0.7
*
* @see #getZoomAroundAnchor()
*/
public void setZoomAroundAnchor(boolean zoomAroundAnchor) {
this.zoomAroundAnchor = zoomAroundAnchor;
}
/**
* Returns the zoom rectangle fill paint.
*
* @return The zoom rectangle fill paint (never <code>null</code>).
*
* @see #setZoomFillPaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomFillPaint() {
return this.zoomFillPaint;
}
/**
* Sets the zoom rectangle fill paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getZoomFillPaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomFillPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.zoomFillPaint = paint;
}
/**
* Returns the zoom rectangle outline paint.
*
* @return The zoom rectangle outline paint (never <code>null</code>).
*
* @see #setZoomOutlinePaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomOutlinePaint() {
return this.zoomOutlinePaint;
}
/**
* Sets the zoom rectangle outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getZoomOutlinePaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomOutlinePaint(Paint paint) {
this.zoomOutlinePaint = paint;
}
/**
* The mouse wheel handler.
*/
private MouseWheelHandler mouseWheelHandler;
/**
* Returns <code>true</code> if the mouse wheel handler is enabled, and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @since 1.0.13
*/
public boolean isMouseWheelEnabled() {
return this.mouseWheelHandler != null;
}
/**
* Enables or disables mouse wheel support for the panel.
*
* @param flag a boolean.
*
* @since 1.0.13
*/
public void setMouseWheelEnabled(boolean flag) {
if (flag && this.mouseWheelHandler == null) {
this.mouseWheelHandler = new MouseWheelHandler(this);
}
else if (!flag && this.mouseWheelHandler != null) {
this.removeMouseWheelListener(this.mouseWheelHandler);
this.mouseWheelHandler = null;
}
}
/**
* Add an overlay to the panel.
*
* @param overlay the overlay (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void addOverlay(Overlay overlay) {
if (overlay == null) {
throw new IllegalArgumentException("Null 'overlay' argument.");
}
this.overlays.add(overlay);
overlay.addChangeListener(this);
repaint();
}
/**
* Removes an overlay from the panel.
*
* @param overlay the overlay to remove (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void removeOverlay(Overlay overlay) {
if (overlay == null) {
throw new IllegalArgumentException("Null 'overlay' argument.");
}
boolean removed = this.overlays.remove(overlay);
if (removed) {
overlay.removeChangeListener(this);
repaint();
}
}
/**
* Handles a change to an overlay by repainting the panel.
*
* @param event the event.
*
* @since 1.0.13
*/
public void overlayChanged(OverlayChangeEvent event) {
repaint();
}
/**
* Switches the display of tooltips for the panel on or off. Note that
* tooltips can only be displayed if the chart has been configured to
* generate tooltip items.
*
* @param flag <code>true</code> to enable tooltips, <code>false</code> to
* disable tooltips.
*/
public void setDisplayToolTips(boolean flag) {
if (flag) {
ToolTipManager.sharedInstance().registerComponent(this);
}
else {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
/**
* Returns a string for the tooltip.
*
* @param e the mouse event.
*
* @return A tool tip or <code>null</code> if no tooltip is available.
*/
public String getToolTipText(MouseEvent e) {
String result = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
Insets insets = getInsets();
ChartEntity entity = entities.getEntity(
(int) ((e.getX() - insets.left) / this.scaleX),
(int) ((e.getY() - insets.top) / this.scaleY));
if (entity != null) {
result = entity.getToolTipText();
}
}
}
return result;
}
/**
* Translates a Java2D point on the chart to a screen location.
*
* @param java2DPoint the Java2D point.
*
* @return The screen location.
*/
public Point translateJava2DToScreen(Point2D java2DPoint) {
Insets insets = getInsets();
int x = (int) (java2DPoint.getX() * this.scaleX + insets.left);
int y = (int) (java2DPoint.getY() * this.scaleY + insets.top);
return new Point(x, y);
}
/**
* Translates a panel (component) location to a Java2D point.
*
* @param screenPoint the screen location (<code>null</code> not
* permitted).
*
* @return The Java2D coordinates.
*/
public Point2D translateScreenToJava2D(Point screenPoint) {
Insets insets = getInsets();
double x = (screenPoint.getX() - insets.left) / this.scaleX;
double y = (screenPoint.getY() - insets.top) / this.scaleY;
return new Point2D.Double(x, y);
}
/**
* Applies any scaling that is in effect for the chart drawing to the
* given rectangle.
*
* @param rect the rectangle (<code>null</code> not permitted).
*
* @return A new scaled rectangle.
*/
public Rectangle2D scale(Rectangle2D rect) {
Insets insets = getInsets();
double x = rect.getX() * getScaleX() + insets.left;
double y = rect.getY() * getScaleY() + insets.top;
double w = rect.getWidth() * getScaleX();
double h = rect.getHeight() * getScaleY();
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the chart entity at a given point.
* <P>
* This method will return null if there is (a) no entity at the given
* point, or (b) no entity collection has been generated.
*
* @param viewX the x-coordinate.
* @param viewY the y-coordinate.
*
* @return The chart entity (possibly <code>null</code>).
*/
public ChartEntity getEntityForPoint(int viewX, int viewY) {
ChartEntity result = null;
if (this.info != null) {
Insets insets = getInsets();
double x = (viewX - insets.left) / this.scaleX;
double y = (viewY - insets.top) / this.scaleY;
EntityCollection entities = this.info.getEntityCollection();
result = entities != null ? entities.getEntity(x, y) : null;
}
return result;
}
/**
* Returns the flag that controls whether or not the offscreen buffer
* needs to be refreshed.
*
* @return A boolean.
*/
public boolean getRefreshBuffer() {
return this.refreshBuffer;
}
/**
* Sets the refresh buffer flag. This flag is used to avoid unnecessary
* redrawing of the chart when the offscreen image buffer is used.
*
* @param flag <code>true</code> indicates that the buffer should be
* refreshed.
*/
public void setRefreshBuffer(boolean flag) {
this.refreshBuffer = flag;
}
/**
* Paints the component by drawing the chart to fill the entire component,
* but allowing for the insets (which will be non-zero if a border has been
* set for this component). To increase performance (at the expense of
* memory), an off-screen buffer image can be used.
*
* @param g the graphics device for drawing on.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.chart == null) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
// first determine the size of the chart rendering area...
Dimension size = getSize();
Insets insets = getInsets();
Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
size.getWidth() - insets.left - insets.right,
size.getHeight() - insets.top - insets.bottom);
// work out if scaling is required...
boolean scale = false;
double drawWidth = available.getWidth();
double drawHeight = available.getHeight();
this.scaleX = 1.0;
this.scaleY = 1.0;
if (drawWidth < this.minimumDrawWidth) {
this.scaleX = drawWidth / this.minimumDrawWidth;
drawWidth = this.minimumDrawWidth;
scale = true;
}
else if (drawWidth > this.maximumDrawWidth) {
this.scaleX = drawWidth / this.maximumDrawWidth;
drawWidth = this.maximumDrawWidth;
scale = true;
}
if (drawHeight < this.minimumDrawHeight) {
this.scaleY = drawHeight / this.minimumDrawHeight;
drawHeight = this.minimumDrawHeight;
scale = true;
}
else if (drawHeight > this.maximumDrawHeight) {
this.scaleY = drawHeight / this.maximumDrawHeight;
drawHeight = this.maximumDrawHeight;
scale = true;
}
Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,
drawHeight);
// are we using the chart buffer?
if (this.useBuffer) {
// do we need to resize the buffer?
if ((this.chartBuffer == null)
|| (this.chartBufferWidth != available.getWidth())
|| (this.chartBufferHeight != available.getHeight())) {
this.chartBufferWidth = (int) available.getWidth();
this.chartBufferHeight = (int) available.getHeight();
GraphicsConfiguration gc = g2.getDeviceConfiguration();
this.chartBuffer = gc.createCompatibleImage(
this.chartBufferWidth, this.chartBufferHeight,
Transparency.TRANSLUCENT);
this.refreshBuffer = true;
}
// do we need to redraw the buffer?
if (this.refreshBuffer) {
this.refreshBuffer = false; // clear the flag
Rectangle2D bufferArea = new Rectangle2D.Double(
0, 0, this.chartBufferWidth, this.chartBufferHeight);
// make the background of the buffer clear and transparent
Graphics2D bufferG2 = (Graphics2D)
this.chartBuffer.getGraphics();
Composite savedComposite = bufferG2.getComposite();
bufferG2.setComposite(AlphaComposite.getInstance(
AlphaComposite.CLEAR, 0.0f));
Rectangle r = new Rectangle(0, 0, this.chartBufferWidth,
this.chartBufferHeight);
bufferG2.fill(r);
bufferG2.setComposite(savedComposite);
if (scale) {
AffineTransform saved = bufferG2.getTransform();
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
bufferG2.transform(st);
this.chart.draw(bufferG2, chartArea, this.anchor,
this.info);
bufferG2.setTransform(saved);
}
else {
this.chart.draw(bufferG2, bufferArea, this.anchor,
this.info);
}
}
// zap the buffer onto the panel...
g2.drawImage(this.chartBuffer, insets.left, insets.top, this);
}
// or redrawing the chart every time...
else {
AffineTransform saved = g2.getTransform();
g2.translate(insets.left, insets.top);
if (scale) {
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
g2.transform(st);
}
this.chart.draw(g2, chartArea, this.anchor, this.info);
g2.setTransform(saved);
}
Iterator iterator = this.overlays.iterator();
while (iterator.hasNext()) {
Overlay overlay = (Overlay) iterator.next();
overlay.paintOverlay(g2, this);
}
// redraw the zoom rectangle (if present) - if useBuffer is false,
// we use XOR so we can XOR the rectangle away again without redrawing
// the chart
drawZoomRectangle(g2, !this.useBuffer);
g2.dispose();
this.anchor = null;
this.verticalTraceLine = null;
this.horizontalTraceLine = null;
}
/**
* Receives notification of changes to the chart, and redraws the chart.
*
* @param event details of the chart change event.
*/
public void chartChanged(ChartChangeEvent event) {
this.refreshBuffer = true;
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.orientation = z.getOrientation();
}
repaint();
}
/**
* Receives notification of a chart progress event.
*
* @param event the event.
*/
public void chartProgress(ChartProgressEvent event) {
// does nothing - override if necessary
}
/**
* Handles action events generated by the popup menu.
*
* @param event the event.
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
// many of the zoom methods need a screen location - all we have is
// the zoomPoint, but it might be null. Here we grab the x and y
// coordinates, or use defaults...
double screenX = -1.0;
double screenY = -1.0;
if (this.zoomPoint != null) {
screenX = this.zoomPoint.getX();
screenY = this.zoomPoint.getY();
}
if (command.equals(PROPERTIES_COMMAND)) {
doEditChartProperties();
}
else if (command.equals(COPY_COMMAND)) {
doCopy();
}
else if (command.equals(SAVE_COMMAND)) {
try {
doSaveAs();
}
catch (IOException e) {
e.printStackTrace();
}
}
else if (command.equals(PRINT_COMMAND)) {
createChartPrintJob();
}
else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {
zoomInBoth(screenX, screenY);
}
else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {
zoomInDomain(screenX, screenY);
}
else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {
zoomInRange(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {
zoomOutBoth(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {
zoomOutDomain(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {
zoomOutRange(screenX, screenY);
}
else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {
restoreAutoBounds();
}
else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {
restoreAutoDomainBounds();
}
else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {
restoreAutoRangeBounds();
}
}
/**
* Handles a 'mouse entered' event. This method changes the tooltip delays
* of ToolTipManager.sharedInstance() to the possibly different values set
* for this chart panel.
*
* @param e the mouse event.
*/
public void mouseEntered(MouseEvent e) {
if (!this.ownToolTipDelaysActive) {
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.originalToolTipInitialDelay = ttm.getInitialDelay();
ttm.setInitialDelay(this.ownToolTipInitialDelay);
this.originalToolTipReshowDelay = ttm.getReshowDelay();
ttm.setReshowDelay(this.ownToolTipReshowDelay);
this.originalToolTipDismissDelay = ttm.getDismissDelay();
ttm.setDismissDelay(this.ownToolTipDismissDelay);
this.ownToolTipDelaysActive = true;
}
}
/**
* Handles a 'mouse exited' event. This method resets the tooltip delays of
* ToolTipManager.sharedInstance() to their
* original values in effect before mouseEntered()
*
* @param e the mouse event.
*/
public void mouseExited(MouseEvent e) {
if (this.ownToolTipDelaysActive) {
// restore original tooltip dealys
ToolTipManager ttm = ToolTipManager.sharedInstance();
ttm.setInitialDelay(this.originalToolTipInitialDelay);
ttm.setReshowDelay(this.originalToolTipReshowDelay);
ttm.setDismissDelay(this.originalToolTipDismissDelay);
this.ownToolTipDelaysActive = false;
}
}
/**
* Handles a 'mouse pressed' event.
* <P>
* This event is the popup trigger on Unix/Linux. For Windows, the popup
* trigger is the 'mouse released' event.
*
* @param e The mouse event.
*/
public void mousePressed(MouseEvent e) {
if (this.chart == null) {
return;
}
Plot plot = this.chart.getPlot();
int mods = e.getModifiers();
if ((mods & this.panMask) == this.panMask) {
// can we pan this plot?
if (plot instanceof Pannable) {
Pannable pannable = (Pannable) plot;
if (pannable.isDomainPannable() || pannable.isRangePannable()) {
Rectangle2D screenDataArea = getScreenDataArea(e.getX(),
e.getY());
if (screenDataArea != null && screenDataArea.contains(
e.getPoint())) {
this.panW = screenDataArea.getWidth();
this.panH = screenDataArea.getHeight();
this.panLast = e.getPoint();
setCursor(Cursor.getPredefinedCursor(
Cursor.MOVE_CURSOR));
}
}
// the actual panning occurs later in the mouseDragged()
// method
}
}
else if (this.zoomRectangle == null) {
Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY());
if (screenDataArea != null) {
this.zoomPoint = getPointInRectangle(e.getX(), e.getY(),
screenDataArea);
}
else {
this.zoomPoint = null;
}
if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
}
}
}
/**
* Returns a point based on (x, y) but constrained to be within the bounds
* of the given rectangle. This method could be moved to JCommon.
*
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param area the rectangle (<code>null</code> not permitted).
*
* @return A point within the rectangle.
*/
private Point2D getPointInRectangle(int x, int y, Rectangle2D area) {
double xx = Math.max(area.getMinX(), Math.min(x, area.getMaxX()));
double yy = Math.max(area.getMinY(), Math.min(y, area.getMaxY()));
return new Point2D.Double(xx, yy);
}
/**
* Handles a 'mouse dragged' event.
*
* @param e the mouse event.
*/
public void mouseDragged(MouseEvent e) {
// if the popup menu has already been triggered, then ignore dragging...
if (this.popup != null && this.popup.isShowing()) {
return;
}
// handle panning if we have a start point
if (this.panLast != null) {
double dx = e.getX() - this.panLast.getX();
double dy = e.getY() - this.panLast.getY();
if (dx == 0.0 && dy == 0.0) {
return;
}
double wPercent = -dx / this.panW;
double hPercent = dy / this.panH;
boolean old = this.chart.getPlot().isNotify();
this.chart.getPlot().setNotify(false);
Pannable p = (Pannable) this.chart.getPlot();
if (p.getOrientation() == PlotOrientation.VERTICAL) {
p.panDomainAxes(wPercent, this.info.getPlotInfo(),
this.panLast);
p.panRangeAxes(hPercent, this.info.getPlotInfo(),
this.panLast);
}
else {
p.panDomainAxes(hPercent, this.info.getPlotInfo(),
this.panLast);
p.panRangeAxes(wPercent, this.info.getPlotInfo(),
this.panLast);
}
this.panLast = e.getPoint();
this.chart.getPlot().setNotify(old);
return;
}
// if no initial zoom point was set, ignore dragging...
if (this.zoomPoint == null) {
return;
}
Graphics2D g2 = (Graphics2D) getGraphics();
// erase the previous zoom rectangle (if any). We only need to do
// this is we are using XOR mode, which we do when we're not using
// the buffer (if there is a buffer, then at the end of this method we
// just trigger a repaint)
if (!this.useBuffer) {
drawZoomRectangle(g2, true);
}
boolean hZoom = false;
boolean vZoom = false;
if (this.orientation == PlotOrientation.HORIZONTAL) {
hZoom = this.rangeZoomable;
vZoom = this.domainZoomable;
}
else {
hZoom = this.domainZoomable;
vZoom = this.rangeZoomable;
}
Rectangle2D scaledDataArea = getScreenDataArea(
(int) this.zoomPoint.getX(), (int) this.zoomPoint.getY());
if (hZoom && vZoom) {
// selected rectangle shouldn't extend outside the data area...
double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
this.zoomRectangle = new Rectangle2D.Double(
this.zoomPoint.getX(), this.zoomPoint.getY(),
xmax - this.zoomPoint.getX(), ymax - this.zoomPoint.getY());
}
else if (hZoom) {
double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
this.zoomRectangle = new Rectangle2D.Double(
this.zoomPoint.getX(), scaledDataArea.getMinY(),
xmax - this.zoomPoint.getX(), scaledDataArea.getHeight());
}
else if (vZoom) {
double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
this.zoomRectangle = new Rectangle2D.Double(
scaledDataArea.getMinX(), this.zoomPoint.getY(),
scaledDataArea.getWidth(), ymax - this.zoomPoint.getY());
}
// Draw the new zoom rectangle...
if (this.useBuffer) {
repaint();
}
else {
// with no buffer, we use XOR to draw the rectangle "over" the
// chart...
drawZoomRectangle(g2, true);
}
g2.dispose();
}
/**
* Handles a 'mouse released' event. On Windows, we need to check if this
* is a popup trigger, but only if we haven't already been tracking a zoom
* rectangle.
*
* @param e information about the event.
*/
public void mouseReleased(MouseEvent e) {
// if we've been panning, we need to reset now that the mouse is
// released...
if (this.panLast != null) {
this.panLast = null;
setCursor(Cursor.getDefaultCursor());
}
else if (this.zoomRectangle != null) {
boolean hZoom = false;
boolean vZoom = false;
if (this.orientation == PlotOrientation.HORIZONTAL) {
hZoom = this.rangeZoomable;
vZoom = this.domainZoomable;
}
else {
hZoom = this.domainZoomable;
vZoom = this.rangeZoomable;
}
boolean zoomTrigger1 = hZoom && Math.abs(e.getX()
- this.zoomPoint.getX()) >= this.zoomTriggerDistance;
boolean zoomTrigger2 = vZoom && Math.abs(e.getY()
- this.zoomPoint.getY()) >= this.zoomTriggerDistance;
if (zoomTrigger1 || zoomTrigger2) {
if ((hZoom && (e.getX() < this.zoomPoint.getX()))
|| (vZoom && (e.getY() < this.zoomPoint.getY()))) {
restoreAutoBounds();
}
else {
double x, y, w, h;
Rectangle2D screenDataArea = getScreenDataArea(
(int) this.zoomPoint.getX(),
(int) this.zoomPoint.getY());
double maxX = screenDataArea.getMaxX();
double maxY = screenDataArea.getMaxY();
// for mouseReleased event, (horizontalZoom || verticalZoom)
// will be true, so we can just test for either being false;
// otherwise both are true
if (!vZoom) {
x = this.zoomPoint.getX();
y = screenDataArea.getMinY();
w = Math.min(this.zoomRectangle.getWidth(),
maxX - this.zoomPoint.getX());
h = screenDataArea.getHeight();
}
else if (!hZoom) {
x = screenDataArea.getMinX();
y = this.zoomPoint.getY();
w = screenDataArea.getWidth();
h = Math.min(this.zoomRectangle.getHeight(),
maxY - this.zoomPoint.getY());
}
else {
x = this.zoomPoint.getX();
y = this.zoomPoint.getY();
w = Math.min(this.zoomRectangle.getWidth(),
maxX - this.zoomPoint.getX());
h = Math.min(this.zoomRectangle.getHeight(),
maxY - this.zoomPoint.getY());
}
Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h);
zoom(zoomArea);
}
this.zoomPoint = null;
this.zoomRectangle = null;
}
else {
// erase the zoom rectangle
Graphics2D g2 = (Graphics2D) getGraphics();
if (this.useBuffer) {
repaint();
}
else {
drawZoomRectangle(g2, true);
}
g2.dispose();
this.zoomPoint = null;
this.zoomRectangle = null;
}
}
else if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
}
}
/**
* Receives notification of mouse clicks on the panel. These are
* translated and passed on to any registered {@link ChartMouseListener}s.
*
* @param event Information about the mouse event.
*/
public void mouseClicked(MouseEvent event) {
Insets insets = getInsets();
int x = (int) ((event.getX() - insets.left) / this.scaleX);
int y = (int) ((event.getY() - insets.top) / this.scaleY);
this.anchor = new Point2D.Double(x, y);
if (this.chart == null) {
return;
}
this.chart.setNotify(true); // force a redraw
// new entity code...
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length == 0) {
return;
}
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(), event,
entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent);
}
}
/**
* Implementation of the MouseMotionListener's method.
*
* @param e the event.
*/
public void mouseMoved(MouseEvent e) {
Graphics2D g2 = (Graphics2D) getGraphics();
if (this.horizontalAxisTrace) {
drawHorizontalAxisTrace(g2, e.getX());
}
if (this.verticalAxisTrace) {
drawVerticalAxisTrace(g2, e.getY());
}
g2.dispose();
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length == 0) {
return;
}
Insets insets = getInsets();
int x = (int) ((e.getX() - insets.left) / this.scaleX);
int y = (int) ((e.getY() - insets.top) / this.scaleY);
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
// we can only generate events if the panel's chart is not null
// (see bug report 1556951)
if (this.chart != null) {
ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseMoved(event);
}
}
}
/**
* Zooms in on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomInBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomInDomain(x, y);
zoomInRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Decreases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is reduced
* by the value of {@link #getZoomInFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomInDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Decreases the length of the range axis, centered about the given
* coordinate on the screen. The length of the range axis is reduced by
* the value of {@link #getZoomInFactor()}.
*
* @param x the x-coordinate (in screen coordinates).
* @param y the y coordinate (in screen coordinates).
*/
public void zoomInRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms out on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomOutBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomOutDomain(x, y);
zoomOutRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Increases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Increases the length the range axis, centered about the given
* coordinate on the screen. The length of the range axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms in on a selected region.
*
* @param selection the selected region.
*/
public void zoom(Rectangle2D selection) {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(
(int) Math.ceil(selection.getX()),
(int) Math.ceil(selection.getY())));
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D scaledDataArea = getScreenDataArea(
(int) selection.getCenterX(), (int) selection.getCenterY());
if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {
double hLower = (selection.getMinX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double hUpper = (selection.getMaxX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double vLower = (scaledDataArea.getMaxY() - selection.getMaxY())
/ scaledDataArea.getHeight();
double vUpper = (scaledDataArea.getMaxY() - selection.getMinY())
/ scaledDataArea.getHeight();
Plot p = this.chart.getPlot();
if (p instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = p.isNotify();
p.setNotify(false);
Zoomable z = (Zoomable) p;
if (z.getOrientation() == PlotOrientation.HORIZONTAL) {
z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);
}
else {
z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);
}
p.setNotify(savedNotify);
}
}
}
/**
* Restores the auto-range calculation on both axes.
*/
public void restoreAutoBounds() {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
restoreAutoDomainBounds();
restoreAutoRangeBounds();
plot.setNotify(savedNotify);
}
/**
* Restores the auto-range calculation on the domain axis.
*/
public void restoreAutoDomainBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomDomainAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Restores the auto-range calculation on the range axis.
*/
public void restoreAutoRangeBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomRangeAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Returns the data area for the chart (the area inside the axes) with the
* current scaling applied (that is, the area as it appears on screen).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea() {
Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();
Insets insets = getInsets();
double x = dataArea.getX() * this.scaleX + insets.left;
double y = dataArea.getY() * this.scaleY + insets.top;
double w = dataArea.getWidth() * this.scaleX;
double h = dataArea.getHeight() * this.scaleY;
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the data area (the area inside the axes) for the plot or subplot,
* with the current scaling applied.
*
* @param x the x-coordinate (for subplot selection).
* @param y the y-coordinate (for subplot selection).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea(int x, int y) {
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D result;
if (plotInfo.getSubplotCount() == 0) {
result = getScreenDataArea();
}
else {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(x, y));
int subplotIndex = plotInfo.getSubplotIndex(selectOrigin);
if (subplotIndex == -1) {
return null;
}
result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea());
}
return result;
}
/**
* Returns the initial tooltip delay value used inside this chart panel.
*
* @return An integer representing the initial delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getInitialDelay()
*/
public int getInitialDelay() {
return this.ownToolTipInitialDelay;
}
/**
* Returns the reshow tooltip delay value used inside this chart panel.
*
* @return An integer representing the reshow delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getReshowDelay()
*/
public int getReshowDelay() {
return this.ownToolTipReshowDelay;
}
/**
* Returns the dismissal tooltip delay value used inside this chart panel.
*
* @return An integer representing the dismissal delay value, in
* milliseconds.
*
* @see javax.swing.ToolTipManager#getDismissDelay()
*/
public int getDismissDelay() {
return this.ownToolTipDismissDelay;
}
/**
* Specifies the initial delay value for this chart panel.
*
* @param delay the number of milliseconds to delay (after the cursor has
* paused) before displaying.
*
* @see javax.swing.ToolTipManager#setInitialDelay(int)
*/
public void setInitialDelay(int delay) {
this.ownToolTipInitialDelay = delay;
}
/**
* Specifies the amount of time before the user has to wait initialDelay
* milliseconds before a tooltip will be shown.
*
* @param delay time in milliseconds
*
* @see javax.swing.ToolTipManager#setReshowDelay(int)
*/
public void setReshowDelay(int delay) {
this.ownToolTipReshowDelay = delay;
}
/**
* Specifies the dismissal delay value for this chart panel.
*
* @param delay the number of milliseconds to delay before taking away the
* tooltip
*
* @see javax.swing.ToolTipManager#setDismissDelay(int)
*/
public void setDismissDelay(int delay) {
this.ownToolTipDismissDelay = delay;
}
/**
* Returns the zoom in factor.
*
* @return The zoom in factor.
*
* @see #setZoomInFactor(double)
*/
public double getZoomInFactor() {
return this.zoomInFactor;
}
/**
* Sets the zoom in factor.
*
* @param factor the factor.
*
* @see #getZoomInFactor()
*/
public void setZoomInFactor(double factor) {
this.zoomInFactor = factor;
}
/**
* Returns the zoom out factor.
*
* @return The zoom out factor.
*
* @see #setZoomOutFactor(double)
*/
public double getZoomOutFactor() {
return this.zoomOutFactor;
}
/**
* Sets the zoom out factor.
*
* @param factor the factor.
*
* @see #getZoomOutFactor()
*/
public void setZoomOutFactor(double factor) {
this.zoomOutFactor = factor;
}
/**
* Draws zoom rectangle (if present).
* The drawing is performed in XOR mode, therefore
* when this method is called twice in a row,
* the second call will completely restore the state
* of the canvas.
*
* @param g2 the graphics device.
* @param xor use XOR for drawing?
*/
private void drawZoomRectangle(Graphics2D g2, boolean xor) {
if (this.zoomRectangle != null) {
if (xor) {
// Set XOR mode to draw the zoom rectangle
g2.setXORMode(Color.gray);
}
if (this.fillZoomRectangle) {
g2.setPaint(this.zoomFillPaint);
g2.fill(this.zoomRectangle);
}
else {
g2.setPaint(this.zoomOutlinePaint);
g2.draw(this.zoomRectangle);
}
if (xor) {
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
}
}
/**
* Draws a vertical line used to trace the mouse position to the horizontal
* axis.
*
* @param g2 the graphics device.
* @param x the x-coordinate of the trace line.
*/
private void drawHorizontalAxisTrace(Graphics2D g2, int x) {
Rectangle2D dataArea = getScreenDataArea();
g2.setXORMode(Color.orange);
if (((int) dataArea.getMinX() < x) && (x < (int) dataArea.getMaxX())) {
if (this.verticalTraceLine != null) {
g2.draw(this.verticalTraceLine);
this.verticalTraceLine.setLine(x, (int) dataArea.getMinY(), x,
(int) dataArea.getMaxY());
}
else {
this.verticalTraceLine = new Line2D.Float(x,
(int) dataArea.getMinY(), x, (int) dataArea.getMaxY());
}
g2.draw(this.verticalTraceLine);
}
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
/**
* Draws a horizontal line used to trace the mouse position to the vertical
* axis.
*
* @param g2 the graphics device.
* @param y the y-coordinate of the trace line.
*/
private void drawVerticalAxisTrace(Graphics2D g2, int y) {
Rectangle2D dataArea = getScreenDataArea();
g2.setXORMode(Color.orange);
if (((int) dataArea.getMinY() < y) && (y < (int) dataArea.getMaxY())) {
if (this.horizontalTraceLine != null) {
g2.draw(this.horizontalTraceLine);
this.horizontalTraceLine.setLine((int) dataArea.getMinX(), y,
(int) dataArea.getMaxX(), y);
}
else {
this.horizontalTraceLine = new Line2D.Float(
(int) dataArea.getMinX(), y, (int) dataArea.getMaxX(),
y);
}
g2.draw(this.horizontalTraceLine);
}
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
/**
* Displays a dialog that allows the user to edit the properties for the
* current chart.
*
* @since 1.0.3
*/
public void doEditChartProperties() {
ChartEditor editor = ChartEditorManager.getChartEditor(this.chart);
int result = JOptionPane.showConfirmDialog(this, editor,
localizationResources.getString("Chart_Properties"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
editor.updateChart(this.chart);
}
}
/**
* Copies the current chart to the system clipboard.
*
* @since 1.0.13
*/
public void doCopy() {
Clipboard systemClipboard
= Toolkit.getDefaultToolkit().getSystemClipboard();
Insets insets = getInsets();
int w = getWidth() - insets.left - insets.right;
int h = getHeight() - insets.top - insets.bottom;
ChartTransferable selection = new ChartTransferable(this.chart, w, h,
getMinimumDrawWidth(), getMinimumDrawHeight(),
getMaximumDrawWidth(), getMaximumDrawHeight(), true);
systemClipboard.setContents(selection, null);
}
/**
* Opens a file chooser and gives the user an opportunity to save the chart
* in PNG format.
*
* @throws IOException if there is an I/O error.
*/
public void doSaveAs() throws IOException {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
ExtensionFileFilter filter = new ExtensionFileFilter(
localizationResources.getString("PNG_Image_Files"), ".png");
fileChooser.addChoosableFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
getWidth(), getHeight());
}
}
/**
* Creates a print job for the chart.
*/
public void createChartPrintJob() {
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
PageFormat pf2 = job.pageDialog(pf);
if (pf2 != pf) {
job.setPrintable(this, pf2);
if (job.printDialog()) {
try {
job.print();
}
catch (PrinterException e) {
JOptionPane.showMessageDialog(this, e);
}
}
}
}
/**
* Prints the chart on a single page.
*
* @param g the graphics context.
* @param pf the page format to use.
* @param pageIndex the index of the page. If not <code>0</code>, nothing
* gets print.
*
* @return The result of printing.
*/
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
double x = pf.getImageableX();
double y = pf.getImageableY();
double w = pf.getImageableWidth();
double h = pf.getImageableHeight();
this.chart.draw(g2, new Rectangle2D.Double(x, y, w, h), this.anchor,
null);
return PAGE_EXISTS;
}
/**
* Adds a listener to the list of objects listening for chart mouse events.
*
* @param listener the listener (<code>null</code> not permitted).
*/
public void addChartMouseListener(ChartMouseListener listener) {
if (listener == null) {
throw new IllegalArgumentException("Null 'listener' argument.");
}
this.chartMouseListeners.add(ChartMouseListener.class, listener);
}
/**
* Removes a listener from the list of objects listening for chart mouse
* events.
*
* @param listener the listener.
*/
public void removeChartMouseListener(ChartMouseListener listener) {
this.chartMouseListeners.remove(ChartMouseListener.class, listener);
}
/**
* Returns an array of the listeners of the given type registered with the
* panel.
*
* @param listenerType the listener type.
*
* @return An array of listeners.
*/
public EventListener[] getListeners(Class listenerType) {
if (listenerType == ChartMouseListener.class) {
// fetch listeners from local storage
return this.chartMouseListeners.getListeners(listenerType);
}
else {
return super.getListeners(listenerType);
}
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*/
protected JPopupMenu createPopupMenu(boolean properties, boolean save,
boolean print, boolean zoom) {
return createPopupMenu(properties, false, save, print, zoom);
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param copy include a menu item for copying to the clipboard.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*
* @since 1.0.13
*/
protected JPopupMenu createPopupMenu(boolean properties,
boolean copy, boolean save, boolean print, boolean zoom) {
JPopupMenu result = new JPopupMenu(localizationResources.getString("Chart") + ":");
boolean separator = false;
if (properties) {
JMenuItem propertiesItem = new JMenuItem(
localizationResources.getString("Properties..."));
propertiesItem.setActionCommand(PROPERTIES_COMMAND);
propertiesItem.addActionListener(this);
result.add(propertiesItem);
separator = true;
}
if (copy) {
if (separator) {
result.addSeparator();
separator = false;
}
JMenuItem copyItem = new JMenuItem(
localizationResources.getString("Copy"));
copyItem.setActionCommand(COPY_COMMAND);
copyItem.addActionListener(this);
result.add(copyItem);
separator = !save;
}
if (save) {
if (separator) {
result.addSeparator();
separator = false;
}
JMenuItem saveItem = new JMenuItem(
localizationResources.getString("Save_as..."));
saveItem.setActionCommand(SAVE_COMMAND);
saveItem.addActionListener(this);
result.add(saveItem);
separator = true;
}
if (print) {
if (separator) {
result.addSeparator();
separator = false;
}
JMenuItem printItem = new JMenuItem(
localizationResources.getString("Print..."));
printItem.setActionCommand(PRINT_COMMAND);
printItem.addActionListener(this);
result.add(printItem);
separator = true;
}
if (zoom) {
if (separator) {
result.addSeparator();
separator = false;
}
JMenu zoomInMenu = new JMenu(
localizationResources.getString("Zoom_In"));
this.zoomInBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND);
this.zoomInBothMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInBothMenuItem);
zoomInMenu.addSeparator();
this.zoomInDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND);
this.zoomInDomainMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInDomainMenuItem);
this.zoomInRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND);
this.zoomInRangeMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInRangeMenuItem);
result.add(zoomInMenu);
JMenu zoomOutMenu = new JMenu(
localizationResources.getString("Zoom_Out"));
this.zoomOutBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND);
this.zoomOutBothMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutBothMenuItem);
zoomOutMenu.addSeparator();
this.zoomOutDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomOutDomainMenuItem.setActionCommand(
ZOOM_OUT_DOMAIN_COMMAND);
this.zoomOutDomainMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutDomainMenuItem);
this.zoomOutRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND);
this.zoomOutRangeMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutRangeMenuItem);
result.add(zoomOutMenu);
JMenu autoRangeMenu = new JMenu(
localizationResources.getString("Auto_Range"));
this.zoomResetBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomResetBothMenuItem.setActionCommand(
ZOOM_RESET_BOTH_COMMAND);
this.zoomResetBothMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetBothMenuItem);
autoRangeMenu.addSeparator();
this.zoomResetDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomResetDomainMenuItem.setActionCommand(
ZOOM_RESET_DOMAIN_COMMAND);
this.zoomResetDomainMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetDomainMenuItem);
this.zoomResetRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomResetRangeMenuItem.setActionCommand(
ZOOM_RESET_RANGE_COMMAND);
this.zoomResetRangeMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetRangeMenuItem);
result.addSeparator();
result.add(autoRangeMenu);
}
return result;
}
/**
* The idea is to modify the zooming options depending on the type of chart
* being displayed by the panel.
*
* @param x horizontal position of the popup.
* @param y vertical position of the popup.
*/
protected void displayPopupMenu(int x, int y) {
if (this.popup == null) {
return;
}
// go through each zoom menu item and decide whether or not to
// enable it...
boolean isDomainZoomable = false;
boolean isRangeZoomable = false;
Plot plot = (this.chart != null ? this.chart.getPlot() : null);
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
isDomainZoomable = z.isDomainZoomable();
isRangeZoomable = z.isRangeZoomable();
}
if (this.zoomInDomainMenuItem != null) {
this.zoomInDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomOutDomainMenuItem != null) {
this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomResetDomainMenuItem != null) {
this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomInRangeMenuItem != null) {
this.zoomInRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomOutRangeMenuItem != null) {
this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomResetRangeMenuItem != null) {
this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomInBothMenuItem != null) {
this.zoomInBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomOutBothMenuItem != null) {
this.zoomOutBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomResetBothMenuItem != null) {
this.zoomResetBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
this.popup.show(this, x, y);
}
/**
* Updates the UI for a LookAndFeel change.
*/
public void updateUI() {
// here we need to update the UI for the popup menu, if the panel
// has one...
if (this.popup != null) {
SwingUtilities.updateComponentTreeUI(this.popup);
}
super.updateUI();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.zoomFillPaint, stream);
SerialUtilities.writePaint(this.zoomOutlinePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.zoomFillPaint = SerialUtilities.readPaint(stream);
this.zoomOutlinePaint = SerialUtilities.readPaint(stream);
// we create a new but empty chartMouseListeners list
this.chartMouseListeners = new EventListenerList();
// register as a listener with sub-components...
if (this.chart != null) {
this.chart.addChangeListener(this);
}
}
}
|
package VASSAL.counters;
import VASSAL.build.GameModule;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.NamedKeyStrokeArrayConfigurer;
import VASSAL.configure.PlayerIdFormattedExpressionConfigurer;
import VASSAL.configure.StringArrayConfigurer;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatablePiece;
import VASSAL.script.expression.AuditTrail;
import VASSAL.search.HTMLImageFinder;
import VASSAL.tools.FormattedString;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.ProblemDialog;
import VASSAL.tools.SequenceEncoder;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.InputEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import org.apache.commons.lang3.ArrayUtils;
/**
* d/b/a "Report Action"
*
* A GamePiece with this trait will echo the piece's current name when any of a given key commands are pressed
* (and after they take effect)
*/
public class ReportState extends Decorator implements TranslatablePiece {
public static final String ID = "report;"; // NON-NLS
protected NamedKeyStroke[] keys;
protected FormattedString format = new FormattedString();
protected String reportFormat;
protected String[] cycleReportFormat;
protected NamedKeyStroke[] cycleDownKeys;
protected int cycleIndex = -1;
protected String description;
protected boolean noSuppress;
public ReportState() {
this(ID, null);
}
public ReportState(String type, GamePiece inner) {
mySetType(type);
setInner(inner);
}
@Override
public Rectangle boundingBox() {
return piece.boundingBox();
}
@Override
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
piece.draw(g, x, y, obs, zoom);
}
@Override
public String getName() {
return piece.getName();
}
@Override
protected KeyCommand[] myGetKeyCommands() {
return KeyCommand.NONE;
}
@Override
public String myGetState() {
return Integer.toString(cycleIndex);
}
@Override
public String myGetType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(NamedKeyStrokeArrayConfigurer.encode(keys))
.append(reportFormat)
.append(NamedKeyStrokeArrayConfigurer.encode(cycleDownKeys))
.append(StringArrayConfigurer.arrayToString(cycleReportFormat))
.append(description)
.append(noSuppress);
return ID + se.getValue();
}
// We perform the inner commands first so that their effects will be reported
@Override
public Command keyEvent(KeyStroke stroke) {
final Command c = piece.keyEvent(stroke);
return c == null ? myKeyEvent(stroke) : c.append(myKeyEvent(stroke));
}
@Override
public Command myKeyEvent(KeyStroke stroke) {
final GamePiece outer = getOutermost(this);
// Retrieve the name, location and visibility of the unit prior to the
// trait being executed if it is outside this one.
format.setProperty(MAP_NAME, getMap() == null ? null : getMap().getConfigureName());
format.setProperty(LOCATION_NAME, getMap() == null ? null : getMap().locationName(getPosition()));
format.setProperty(OLD_MAP_NAME, (String) getProperty(BasicPiece.OLD_MAP));
format.setProperty(OLD_LOCATION_NAME, (String) getProperty(BasicPiece.OLD_LOCATION_NAME));
Command c = null;
final java.util.Map<String, Object> oldPiece;
final Object o = getProperty(Properties.SNAPSHOT);
// If the SNAPSHOT is returned as a PropertyExporter instead of a Map, then it been set from custom code
// that is still calling using PieceCloner.clonePiece. Extract the Property Map from the supplied GamePiece and annoy the user.
if (o instanceof PropertyExporter) {
oldPiece = ((PropertyExporter) o).getProperties();
ProblemDialog.showOutdatedUsage(Resources.getString("Editor.ReportState.custom_trait_warning"));
}
else {
// If this cast fails, then custom code developer has done something terribly wrong, so just let it crash and burn
oldPiece = (java.util.Map<String, Object>) o;
}
final boolean wasVisible = oldPiece != null && !Boolean.TRUE.equals(oldPiece.get(Properties.INVISIBLE_TO_OTHERS));
final boolean isVisible = !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS));
PieceAccess.GlobalAccess.hideAll();
final String oldUnitName = oldPiece == null ? null : (String) oldPiece.get(PropertyExporter.LOCALIZED_NAME);
format.setProperty(OLD_UNIT_NAME, oldUnitName);
final String newUnitName = outer.getLocalizedName();
format.setProperty(NEW_UNIT_NAME, newUnitName);
PieceAccess.GlobalAccess.revertAll();
// Only make a report if:
// 1. It's not part of a global command with Single Reporting on
// 2. The piece is visible to all players either before or after the trait
// command was executed.
if (isVisible || wasVisible) {
final NamedKeyStroke[] allKeys = ArrayUtils.addAll(keys, cycleDownKeys);
for (int i = 0; i < allKeys.length; ++i) {
if (stroke != null && stroke.equals(allKeys[i].getKeyStroke())) {
// Find the Command Name
String commandName = "";
final KeyCommand[] k = ((Decorator) outer).getKeyCommands();
for (final KeyCommand keyCommand : k) {
final KeyStroke commandKey = keyCommand.getKeyStroke();
if (stroke.equals(commandKey)) {
commandName = keyCommand.getName();
}
}
final ChangeTracker tracker = new ChangeTracker(this);
format.setProperty(COMMAND_NAME, commandName);
String theFormat = reportFormat;
if (cycleIndex >= 0 && cycleReportFormat.length > 0) {
if (i < keys.length) {
theFormat = cycleReportFormat[cycleIndex];
cycleIndex = (cycleIndex + 1) % cycleReportFormat.length;
}
else {
cycleIndex = (cycleIndex + cycleReportFormat.length - 1) % cycleReportFormat.length;
theFormat = cycleReportFormat[(cycleIndex + cycleReportFormat.length - 1) % cycleReportFormat.length];
}
}
format.setFormat(getTranslation(theFormat));
final OldAndNewPieceProperties properties = new OldAndNewPieceProperties(oldPiece, outer);
// Create explicit Audit Trail as format is evaluated twice
final AuditTrail audit = AuditTrail.create(this, format.getFormat(), Resources.getString("Editor.ReportState.report_format_3"));
String reportText = format.getLocalizedText(properties, this, audit);
if (getMap() != null) {
format.setFormat(getMap().getChangeFormat(noSuppress));
}
else if (!Map.isChangeReportingEnabled() && !noSuppress) {
format.setFormat("");
}
else {
format.setFormat("$" + Map.MESSAGE + "$");
}
format.setProperty(Map.MESSAGE, reportText);
reportText = format.getLocalizedText(properties, this, audit);
if (reportText.length() > 0) {
final Command display = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), "* " + reportText);
display.execute();
c = display;
}
c = tracker.getChangeCommand().append(c);
break;
}
}
}
return c;
}
protected String getPieceName() {
final String name;
PieceAccess.GlobalAccess.hideAll();
name = getOutermost(this).getName();
PieceAccess.GlobalAccess.revertAll();
return name;
}
@Override
public void mySetState(String newState) {
if (newState.length() > 0) {
try {
cycleIndex = Integer.parseInt(newState);
}
catch (NumberFormatException e) {
cycleIndex = -1;
reportDataError(this, Resources.getString("Error.non_number_error"), "Trying to init Message Index to " + newState); // NON-NLS
}
}
else {
cycleIndex = -1;
}
}
@Override
public Shape getShape() {
return piece.getShape();
}
@Override
public String getDescription() {
String s = buildDescription("Editor.ReportState.trait_description", description);
for (final NamedKeyStroke n : keys) {
s += getCommandDesc("", n);
}
return s;
}
@Override
public String getBaseDescription() {
return Resources.getString("Editor.ReportState.trait_description");
}
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("ReportChanges.html"); // NON-NLS
}
@Override
public void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
final String encodedKeys = st.nextToken("");
if (encodedKeys.indexOf(',') > 0) {
keys = NamedKeyStrokeArrayConfigurer.decode(encodedKeys);
}
else {
keys = new NamedKeyStroke[encodedKeys.length()];
for (int i = 0; i < keys.length; i++) {
keys[i] = NamedKeyStroke.of(encodedKeys.charAt(i), InputEvent.CTRL_DOWN_MASK);
}
}
reportFormat = st.nextToken("$" + LOCATION_NAME + "$: $" + NEW_UNIT_NAME + "$ *");
final String encodedCycleDownKeys = st.nextToken("");
if (encodedCycleDownKeys.indexOf(',') > 0) {
cycleDownKeys = NamedKeyStrokeArrayConfigurer.decode(encodedCycleDownKeys);
}
else {
cycleDownKeys = new NamedKeyStroke[encodedCycleDownKeys.length()];
for (int i = 0; i < cycleDownKeys.length; i++) {
cycleDownKeys[i] = NamedKeyStroke.of(encodedCycleDownKeys.charAt(i), InputEvent.CTRL_DOWN_MASK);
}
}
cycleReportFormat = StringArrayConfigurer.stringToArray(st.nextToken(""));
description = st.nextToken("");
noSuppress = st.nextBoolean(false);
}
@Override
public PieceEditor getEditor() {
return new Ed(this);
}
@Override
public PieceI18nData getI18nData() {
final int c = cycleReportFormat == null ? 0 : cycleReportFormat.length;
final String[] formats = new String[c + 1];
final String[] descriptions = new String[c + 1];
formats[0] = reportFormat;
descriptions[0] = getCommandDescription(description, Resources.getString("Editor.ReportState.report_format"));
int j = 1;
for (int i = 0; i < c; i++) {
formats[j] = cycleReportFormat[i];
descriptions[j] = getCommandDescription(description, Resources.getString("Editor.ReportState.report_format_2"));
j++;
}
return getI18nData(formats, descriptions);
}
@Override
public boolean testEquals(Object o) {
if (! (o instanceof ReportState)) return false;
final ReportState c = (ReportState) o;
if (!Arrays.equals(keys, c.keys)) return false;
if (! Objects.equals(reportFormat, c.reportFormat)) return false;
if (!Arrays.equals(cycleDownKeys, c.cycleDownKeys)) return false;
if (!Arrays.equals(cycleReportFormat, c.cycleReportFormat)) return false;
if (!Objects.equals(noSuppress, c.noSuppress)) return false;
return Objects.equals(description, c.description);
}
public static final String OLD_UNIT_NAME = "oldPieceName"; // NON-NLS
public static final String NEW_UNIT_NAME = "newPieceName"; // NON-NLS
public static final String MAP_NAME = "mapName"; // NON-NLS
public static final String OLD_MAP_NAME = "oldMapName"; // NON-NLS
public static final String LOCATION_NAME = "location"; // NON-NLS
public static final String OLD_LOCATION_NAME = "oldLocation"; // NON-NLS
public static final String COMMAND_NAME = "menuCommand"; // NON-NLS
public static class Ed implements PieceEditor {
private final NamedKeyStrokeArrayConfigurer keys;
private final StringConfigurer format;
private final JLabel formatLabel;
private final BooleanConfigurer cycle;
private final JLabel cycleLabel;
private final StringArrayConfigurer cycleFormat;
private final JLabel cycleDownLabel;
private final NamedKeyStrokeArrayConfigurer cycleDownKeys;
protected StringConfigurer descInput;
private final TraitConfigPanel box;
private final BooleanConfigurer noSuppressConfig;
public Ed(ReportState piece) {
box = new TraitConfigPanel();
descInput = new StringConfigurer(piece.description);
descInput.setHintKey("Editor.description_hint");
box.add("Editor.description_label", descInput);
keys = new NamedKeyStrokeArrayConfigurer(piece.keys);
box.add("Editor.ReportState.report_on_these_keystrokes", keys);
cycle = new BooleanConfigurer(piece.cycleReportFormat.length > 0);
cycle.addPropertyChangeListener(e -> adjustVisibilty());
box.add("Editor.ReportState.cycle_through_different_messages", cycle);
formatLabel = new JLabel(Resources.getString("Editor.ReportState.report_format_3"));
format = new PlayerIdFormattedExpressionConfigurer(
new String[]{
COMMAND_NAME,
OLD_UNIT_NAME,
NEW_UNIT_NAME,
MAP_NAME,
OLD_MAP_NAME,
LOCATION_NAME,
OLD_LOCATION_NAME},
piece.reportFormat);
box.add(formatLabel, format);
cycleLabel = new JLabel(Resources.getString("Editor.ReportState.message_formats"));
cycleFormat = new StringArrayConfigurer(piece.cycleReportFormat);
box.add(cycleLabel, cycleFormat);
cycleDownLabel = new JLabel(Resources.getString("Editor.ReportState.report_previous"));
cycleDownKeys = new NamedKeyStrokeArrayConfigurer(piece.cycleDownKeys);
box.add(cycleDownLabel, cycleDownKeys);
noSuppressConfig = new BooleanConfigurer(piece.noSuppress);
box.add("Editor.ReportState.no_suppress", noSuppressConfig);
adjustVisibilty();
}
private void adjustVisibilty() {
format.getControls().setVisible(!cycle.getValueBoolean());
formatLabel.setVisible(!cycle.getValueBoolean());
cycleFormat.getControls().setVisible(cycle.getValueBoolean());
cycleLabel.setVisible(cycle.getValueBoolean());
cycleDownKeys.getControls().setVisible(cycle.getValueBoolean());
cycleDownLabel.setVisible(cycle.getValueBoolean());
repack(box);
}
@Override
public Component getControls() {
return box;
}
@Override
public String getState() {
return cycle.getValueBoolean() ? "0" : "-1";
}
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(keys.getValueString())
.append(format.getValueString())
.append(cycleDownKeys.getValueString())
.append(cycle.getValueBoolean() ? cycleFormat.getValueString() : "")
.append(descInput.getValueString())
.append(noSuppressConfig.getValueString());
return ID + se.getValue();
}
}
/**
* Looks in both the new and old piece for property values.
* Any properties with names of the format "oldXyz" are changed
* to "xyz" and applied to the old piece.
* @author rkinney
*
*/
public static class OldAndNewPieceProperties implements PropertySource {
private final java.util.Map<String, Object> oldPiece;
private final GamePiece newPiece;
public OldAndNewPieceProperties(java.util.Map<String, Object> oldPiece, GamePiece newPiece) {
super();
this.oldPiece = oldPiece;
this.newPiece = newPiece;
}
public GamePiece getNewPiece() {
return newPiece;
}
@Override
public Object getProperty(Object key) {
Object value = null;
if (key != null) {
String name = key.toString();
if (name.startsWith("old") && name.length() >= 4) { // NON-NLS
name = name.substring(3);
value = oldPiece.get(name);
}
else {
value = newPiece.getProperty(key);
}
}
return value;
}
@Override
public Object getLocalizedProperty(Object key) {
return getProperty(key);
}
}
/**
* @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search)
*/
@Override
public List<NamedKeyStroke> getNamedKeyStrokeList() {
return Arrays.asList(keys);
}
/**
* @return a list of any Message Format strings referenced in the Decorator, if any (for search)
*/
@Override
public List<String> getFormattedStringList() {
final List<String> l = new ArrayList<>();
if (cycleIndex >= 0 && cycleReportFormat.length > 0) {
Collections.addAll(l, cycleReportFormat);
}
else {
l.add(reportFormat);
}
return l;
}
/**
* In case reports use HTML and refer to any image files
* @param s Collection to add image names to
*/
@Override
public void addLocalImageNames(Collection<String> s) {
HTMLImageFinder h;
if (cycleIndex >= 0 && cycleReportFormat.length > 0) {
for (final String r : cycleReportFormat) {
h = new HTMLImageFinder(r);
h.addImageNames(s);
}
}
else {
h = new HTMLImageFinder(reportFormat);
h.addImageNames(s);
}
}
}
|
package com.psddev.dari.util;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LocalImageEditor extends AbstractImageEditor {
private static final String DEFAULT_IMAGE_FORMAT = "png";
private static final String DEFAULT_IMAGE_CONTENT_TYPE = "image/" + DEFAULT_IMAGE_FORMAT;
private static final String DEFAULT_SECRET = "secret!";
private static final String ORIGINAL_WIDTH_METADATA_PATH = "image/originalWidth";
private static final String ORIGINAL_HEIGHT_METADATA_PATH = "image/originalHeight";
/** Setting key for quality to use for the output images. */
private static final String QUALITY_SETTING = "quality";
protected static final String TIFF_READER_CLASS = "com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi";
protected static final String THUMBNAIL_COMMAND = "thumbnail";
private static final Logger LOGGER = LoggerFactory.getLogger(LocalImageEditor.class);
private Scalr.Method quality = Scalr.Method.AUTOMATIC;
private String baseUrl;
private String basePath;
private String sharedSecret;
public Scalr.Method getQuality() {
return quality;
}
public void setQuality(Scalr.Method quality) {
this.quality = quality;
}
public String getBaseUrl() {
return baseUrl;
}
public String getBasePath() {
if (StringUtils.isBlank(basePath) && !(StringUtils.isBlank(baseUrl))) {
basePath = baseUrl.substring(baseUrl.indexOf("
basePath = basePath.substring(basePath.indexOf("/") + 1);
if (!basePath.endsWith("/")) {
basePath += "/";
}
}
return basePath;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getSharedSecret() {
return sharedSecret;
}
public void setSharedSecret(String sharedSecret) {
this.sharedSecret = sharedSecret;
}
@Override
public StorageItem edit(StorageItem storageItem, String command, Map<String, Object> options, Object... arguments) {
if (StringUtils.isBlank(this.getBasePath()) && PageContextFilter.Static.getRequest() != null) {
setBaseUrlFromRequest(PageContextFilter.Static.getRequest());
setSharedSecret(DEFAULT_SECRET);
}
if (ImageEditor.CROP_COMMAND.equals(command) &&
options != null &&
options.containsKey(ImageEditor.CROP_OPTION) &&
options.get(ImageEditor.CROP_OPTION).equals(ImageEditor.CROP_OPTION_NONE)) {
return storageItem;
}
String imageUrl = storageItem.getPublicUrl();
List<String> commands = new ArrayList<String>();
if (imageUrl.startsWith(this.getBaseUrl()) && imageUrl.contains("?url=")) {
String[] imageComponents = imageUrl.split("\\?url=");
imageUrl = imageComponents[1];
String path = imageComponents[0].substring(this.getBaseUrl().length() + 1);
for (String parameter : path.split("/")) {
commands.add(parameter);
}
if (!StringUtils.isBlank(this.getSharedSecret())) {
commands = commands.subList(2, commands.size());
}
}
Object cropOption = options != null ? options.get(ImageEditor.CROP_OPTION) : null;
Dimension originalDimension = null;
Dimension outputDimension = null;
Map<String, Object> oldMetadata = storageItem.getMetadata();
if (oldMetadata != null) {
Integer originalWidth = null;
Integer originalHeight = null;
// grab the original width and height of the image
originalWidth = ObjectUtils.to(Integer.class,
CollectionUtils.getByPath(oldMetadata, ORIGINAL_WIDTH_METADATA_PATH));
if (originalWidth == null) {
originalWidth = ObjectUtils.to(Integer.class, oldMetadata.get("width"));
}
originalHeight = ObjectUtils.to(Integer.class,
CollectionUtils.getByPath(oldMetadata, ORIGINAL_HEIGHT_METADATA_PATH));
if (originalHeight == null) {
originalHeight = ObjectUtils.to(Integer.class, oldMetadata.get("height"));
}
originalDimension = new Dimension(originalWidth, originalHeight);
}
if (ImageEditor.CROP_COMMAND.equals(command) &&
ObjectUtils.to(Integer.class, arguments[0]) == null &&
ObjectUtils.to(Integer.class, arguments[1]) == null) {
commands.add(THUMBNAIL_COMMAND);
command = RESIZE_COMMAND;
arguments[0] = arguments[2];
arguments[1] = arguments[3];
} else {
commands.add(command);
}
if (ImageEditor.CROP_COMMAND.equals(command)) {
Integer width = ObjectUtils.to(Integer.class, arguments[2]);
Integer height = ObjectUtils.to(Integer.class, arguments[3]);
commands.add(arguments[0] + "x" + arguments[1] + "x" + width + "x" + height);
if (originalDimension != null) {
outputDimension = new Dimension(Math.min(originalDimension.width, width),
Math.min(originalDimension.height, height));
}
} else if (ImageEditor.RESIZE_COMMAND.equals(command)) {
Integer width = ObjectUtils.to(Integer.class, arguments[0]);
Integer height = ObjectUtils.to(Integer.class, arguments[1]);
StringBuilder resizeBuilder = new StringBuilder();
if (width != null) {
resizeBuilder.append(width);
}
resizeBuilder.append("x");
if (height != null) {
resizeBuilder.append(height);
}
Object resizeOption = options != null ? options.get(ImageEditor.RESIZE_OPTION) : null;
if (resizeOption != null &&
(cropOption == null || !cropOption.equals(ImageEditor.CROP_OPTION_AUTOMATIC))) {
if (resizeOption.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO)) {
resizeBuilder.append("!");
} else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER)) {
resizeBuilder.append(">");
if (originalDimension != null && width != null && height != null) {
outputDimension = new Dimension(Math.min(originalDimension.width, width),
Math.min(originalDimension.height, height));
}
} else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {
resizeBuilder.append("<");
if (originalDimension != null && width != null && height != null) {
outputDimension = new Dimension(Math.max(originalDimension.width, width),
Math.max(originalDimension.height, height));
}
} else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_FILL_AREA)) {
resizeBuilder.append("^");
}
}
if (originalDimension != null && width != null && height != null && (resizeOption == null ||
resizeOption.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO) ||
resizeOption.equals(ImageEditor.RESIZE_OPTION_FILL_AREA))) {
outputDimension = new Dimension(Math.min(originalDimension.width, width),
Math.min(originalDimension.height, height));
}
commands.add(resizeBuilder.toString());
}
StringBuilder storageItemUrlBuilder = new StringBuilder();
storageItemUrlBuilder.append(this.getBaseUrl());
if (!StringUtils.isBlank(this.getSharedSecret())) {
StringBuilder commandsBuilder = new StringBuilder();
for (String parameter : commands) {
commandsBuilder.append(StringUtils.encodeUri(parameter))
.append('/');
}
Long expireTs = (long) Integer.MAX_VALUE;
String signature = expireTs + this.getSharedSecret() + StringUtils.decodeUri("/" + commandsBuilder.toString()) + imageUrl;
String md5Hex = StringUtils.hex(StringUtils.md5(signature));
String requestSig = md5Hex.substring(0, 7);
storageItemUrlBuilder.append(requestSig)
.append("/")
.append(expireTs.toString())
.append("/");
}
for (String parameter : commands) {
storageItemUrlBuilder.append(parameter)
.append("/");
}
storageItemUrlBuilder.append("?url=")
.append(imageUrl);
UrlStorageItem newStorageItem = StorageItem.Static.createUrl(storageItemUrlBuilder.toString());
String format = DEFAULT_IMAGE_FORMAT;
String contentType = DEFAULT_IMAGE_CONTENT_TYPE;
if (storageItem.getContentType() != null && storageItem.getContentType().contains("/")) {
contentType = storageItem.getContentType();
format = storageItem.getContentType().split("/")[1];
}
newStorageItem.setContentType(contentType);
Map<String, Object> metadata = storageItem.getMetadata();
if (metadata == null) {
metadata = new HashMap<String, Object>();
}
// store the new width and height in the metadata map
if (outputDimension != null && outputDimension.width != null) {
metadata.put("width", outputDimension.width);
}
if (outputDimension != null && outputDimension.height != null) {
metadata.put("height", outputDimension.height);
}
// store the original width and height in the map for use with future image edits.
if (originalDimension != null && originalDimension.width != null) {
CollectionUtils.putByPath(metadata, ORIGINAL_WIDTH_METADATA_PATH, originalDimension.width);
}
if (originalDimension != null && originalDimension.height != null) {
CollectionUtils.putByPath(metadata, ORIGINAL_HEIGHT_METADATA_PATH, originalDimension.height);
}
newStorageItem.setMetadata(metadata);
return newStorageItem;
}
@Override
public void initialize(String settingsKey, Map<String, Object> settings) {
Object qualitySetting = settings.get(QUALITY_SETTING);
if (qualitySetting == null) {
qualitySetting = Settings.get(QUALITY_SETTING);
}
if (qualitySetting != null) {
if (qualitySetting instanceof Integer) {
Integer qualityInteger = ObjectUtils.to(Integer.class, qualitySetting);
quality = findQualityByInteger(qualityInteger);
} else if (qualitySetting instanceof String) {
quality = Scalr.Method.valueOf(ObjectUtils.to(String.class, qualitySetting));
}
}
if (!ObjectUtils.isBlank(settings.get("servletPath"))) {
LocalImageServlet.setServletPath(ObjectUtils.to(String.class, settings.get("servletPath")));
}
if (!ObjectUtils.isBlank(settings.get("baseUrl"))) {
setBaseUrl(ObjectUtils.to(String.class, settings.get("baseUrl")));
}
if (!ObjectUtils.isBlank(settings.get("sharedSecret"))) {
setSharedSecret(ObjectUtils.to(String.class, settings.get("sharedSecret")));
} else {
setSharedSecret(DEFAULT_SECRET);
}
}
protected void setBaseUrlFromRequest(HttpServletRequest request) {
StringBuilder baseUrlBuilder = new StringBuilder();
baseUrlBuilder.append("http");
if (request.isSecure()) {
baseUrlBuilder.append("s");
}
baseUrlBuilder.append(":
.append(request.getServerName());
if (request.getServerPort() != 80 && request.getServerPort() != 443) {
baseUrlBuilder.append(":")
.append(request.getServerPort());
}
baseUrlBuilder.append(LocalImageServlet.getServletPath());
setBaseUrl(baseUrlBuilder.toString());
}
protected static Scalr.Method findQualityByInteger(Integer quality) {
if (quality >= 80) {
return Scalr.Method.ULTRA_QUALITY;
} else if (quality >= 60) {
return Scalr.Method.QUALITY;
} else if (quality >= 40) {
return Scalr.Method.AUTOMATIC;
} else if (quality >= 20) {
return Scalr.Method.BALANCED;
} else {
return Scalr.Method.SPEED;
}
}
/** Helper class so that width and height can be returned in a single object */
protected static class Dimension {
public final Integer width;
public final Integer height;
public Dimension(Integer width, Integer height) {
this.width = width;
this.height = height;
}
}
public BufferedImage reSize(BufferedImage bufferedImage, Integer width, Integer height, String option, Scalr.Method quality) {
if (quality == null) {
quality = this.quality;
}
if (width != null || height != null) {
if (!StringUtils.isBlank(option) &&
option.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER)) {
if ((height == null && width >= bufferedImage.getWidth()) ||
(width == null && height >= bufferedImage.getHeight()) ||
(width != null && height != null && width >= bufferedImage.getWidth() && height >= bufferedImage.getHeight())) {
return bufferedImage;
}
} else if (!StringUtils.isBlank(option) &&
option.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {
if ((height == null && width <= bufferedImage.getWidth()) ||
(width == null && height <= bufferedImage.getHeight()) ||
(width != null && height != null && (width <= bufferedImage.getWidth() || height <= bufferedImage.getHeight()))) {
return bufferedImage;
}
}
if (StringUtils.isBlank(option) ||
option.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER) ||
option.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {
if (height == null) {
return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_TO_WIDTH, width);
} else if (width == null) {
return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_TO_HEIGHT, height);
} else {
return Scalr.resize(bufferedImage, quality, width, height);
}
} else if (height != null && width != null) {
if (option.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO)) {
return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_EXACT, width, height);
} else if (option.equals(ImageEditor.RESIZE_OPTION_FILL_AREA)) {
Dimension dimension = getFillAreaDimension(bufferedImage.getWidth(), bufferedImage.getHeight(), width, height);
return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_EXACT, dimension.width, dimension.height);
}
}
}
return null;
}
public static BufferedImage crop(BufferedImage bufferedImage, Integer x, Integer y, Integer width, Integer height) {
if (width != null || height != null) {
if (height == null) {
height = (int) ((double) bufferedImage.getHeight() / (double) bufferedImage.getWidth() * (double) width);
} else if (width == null) {
width = (int) ((double) bufferedImage.getWidth() / (double) bufferedImage.getHeight() * (double) height);
}
if (x == null) {
x = bufferedImage.getWidth() / 2;
}
if (y == null) {
y = bufferedImage.getHeight() / 2;
}
if (x + width > bufferedImage.getWidth()) {
width = bufferedImage.getWidth() - x;
}
if (y + height > bufferedImage.getHeight()) {
height = bufferedImage.getHeight() - y;
}
return Scalr.crop(bufferedImage, x, y, width, height);
}
return null;
}
public static BufferedImage grayscale(BufferedImage sourceImage) {
BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = resultImage.getGraphics();
g.drawImage(sourceImage, 0, 0, null);
g.dispose();
return resultImage;
}
public static BufferedImage brightness(BufferedImage sourceImage, int brightness, int contrast) {
BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
int multiply = 100;
int add;
if (contrast == 0) {
add = Math.round(brightness / 100.0f * 255);
} else {
if (contrast > 0) {
contrast = contrast * 4;
}
contrast = 100 - (contrast * -1);
multiply = contrast;
brightness = Math.round(brightness / 100.0f * 255);
add = ((Double) (((brightness - 128) * (multiply / 100.0d) + 128))).intValue();
}
for (int x = 0; x < sourceImage.getWidth(); x++) {
for (int y = 0; y < sourceImage.getHeight(); y++) {
int rgb = sourceImage.getRGB(x, y);
int alpha = (rgb >> 24) & 0xFF;
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
red = adjustColor(red, multiply, add);
green = adjustColor(green, multiply, add);
blue = adjustColor(blue, multiply, add);
int newRgb = (alpha << 24) | (red << 16) | (green << 8) | blue;
resultImage.setRGB(x, y, newRgb);
}
}
return resultImage;
}
public static BufferedImage flipHorizontal(BufferedImage sourceImage) {
return Scalr.rotate(sourceImage, Scalr.Rotation.FLIP_HORZ);
}
public static BufferedImage flipVertical(BufferedImage sourceImage) {
return Scalr.rotate(sourceImage, Scalr.Rotation.FLIP_VERT);
}
public static BufferedImage invert(BufferedImage sourceImage) {
BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
for (int x = 0; x < sourceImage.getWidth(); x++) {
for (int y = 0; y < sourceImage.getHeight(); y++) {
int rgb = sourceImage.getRGB(x, y);
int alpha = (rgb >> 24) & 0xFF;
int red = 255 - (rgb >> 16) & 0xFF;
int green = 255 - (rgb >> 8) & 0xFF;
int blue = 255 - rgb & 0xFF;
int newRgb = (alpha << 24) | (red << 16) | (green << 8) | blue;
resultImage.setRGB(x, y, newRgb);
}
}
return resultImage;
}
public static BufferedImage rotate(BufferedImage sourceImage, int degrees) {
Scalr.Rotation rotation;
if (degrees == 90) {
rotation = Scalr.Rotation.CW_90;
} else if (degrees == 180) {
rotation = Scalr.Rotation.CW_180;
} else if (degrees == 270 || degrees == -90) {
rotation = Scalr.Rotation.CW_270;
} else {
double radians = Math.toRadians(degrees);
int w = (new Double(Math.abs(sourceImage.getWidth() * Math.cos(radians)) + Math.abs(sourceImage.getHeight() * Math.sin(radians)))).intValue();
int h = (new Double(Math.abs(sourceImage.getWidth() * Math.sin(radians)) + Math.abs(sourceImage.getHeight() * Math.cos(radians)))).intValue();
BufferedImage resultImage = new BufferedImage(w, h, sourceImage.getType());
Graphics2D graphics = resultImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, w, h);
int x = -1 * (sourceImage.getWidth() - w) / 2;
int y = -1 * (sourceImage.getHeight() - h) / 2;
graphics.rotate(Math.toRadians(degrees), (w / 2), (h / 2));
graphics.drawImage(sourceImage, null, x, y);
return resultImage;
}
return Scalr.rotate(sourceImage, rotation);
}
public static BufferedImage sepia(BufferedImage sourceImage) {
BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
for (int x = 0; x < sourceImage.getWidth(); x++) {
for (int y = 0; y < sourceImage.getHeight(); y++) {
int rgb = sourceImage.getRGB(x, y);
int alpha = (rgb >> 24) & 0xFF;
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
int newRed = (new Double((red * .393) + (green * .769) + (blue * .189))).intValue();
int newGreen = (new Double((red * .349) + (green * .686) + (blue * .168))).intValue();
int newBlue = (new Double((red * .272) + (green * .534) + (blue * .131))).intValue();
newRed = colorMinMax(newRed);
newGreen = colorMinMax(newGreen);
newBlue = colorMinMax(newBlue);
int newRgb = (alpha << 24) | (newRed << 16) | (newGreen << 8) | newBlue;
resultImage.setRGB(x, y, newRgb);
}
}
return resultImage;
}
private static int adjustColor(int color, int multiply, int add) {
color = Math.round(color * (multiply / 100.0f)) + add;
return colorMinMax(color);
}
private static int colorMinMax(int color) {
if (color < 0) {
return 0;
} else if (color > 255) {
return 255;
}
return color;
}
private static Dimension getFillAreaDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) {
Integer actualWidth = null;
Integer actualHeight = null;
if (originalWidth != null && originalHeight != null &&
(requestedWidth != null || requestedHeight != null)) {
float originalRatio = (float) originalWidth / (float) originalHeight;
if (requestedWidth != null && requestedHeight != null) {
Integer potentialWidth = Math.round((float) requestedHeight * originalRatio);
Integer potentialHeight = Math.round((float) requestedWidth / originalRatio);
if (potentialWidth > requestedWidth) {
actualWidth = potentialWidth;
actualHeight = requestedHeight;
} else { // potentialHeight > requestedHeight
actualWidth = requestedWidth;
actualHeight = potentialHeight;
}
} else if (originalWidth > originalHeight) {
actualHeight = requestedHeight != null ? requestedHeight : requestedWidth;
actualWidth = Math.round((float) actualHeight * originalRatio);
} else { // originalWidth <= originalHeight
actualWidth = requestedWidth != null ? requestedWidth : requestedHeight;
actualHeight = Math.round((float) actualWidth / originalRatio);
}
}
return new Dimension(actualWidth, actualHeight);
}
}
|
package appathon.com.billythesilly;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
// import android.widget.TextView;
// Commented Page Number feature
public class ScenariosScreen extends Activity {
String [] arrayButtons = new String[18];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scenarios_screen);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scenarios_screen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goButton1(View view){
Intent intent = new Intent(this,BaseGameActivity.class);
startActivity(intent);
}
public void goButton2(View view){
Intent intent = new Intent(this,StartScreen.class);
startActivity(intent);
}
public void goButton3(View view){
Intent intent = new Intent(this,StartScreen.class);
startActivity(intent);
}
public void goNextPage(View view){
generateButtonStrings();
Button current1 = (Button) findViewById(R.id.button1);
Button current2 = (Button) findViewById(R.id.button2);
Button current3 = (Button) findViewById(R.id.button3);
int position = findPosition(current1.getText().toString());
current1.setText(arrayButtons[(position+3)%18]);
current2.setText(arrayButtons[(position+4)%18]);
current3.setText(arrayButtons[(position+5)%18]);
//Line that changes color of text: current1.setTextColor(Color.BLUE);
//setPage(position);
}
public void goPreviousPage(View view) {
generateButtonStrings();
Button current1 = (Button) findViewById(R.id.button1);
Button current2 = (Button) findViewById(R.id.button2);
Button current3 = (Button) findViewById(R.id.button3);
int position = findPosition(current1.getText().toString());
current1.setText(arrayButtons[(position+15)%18]);
current2.setText(arrayButtons[(position+16)%18]);
current3.setText(arrayButtons[(position+17)%18]);
//setPage(position);
}
/*public void setPage(int n){
TextView page = (TextView) findViewById(R.id.textPage);
String s = "Page "+ Integer.toString((n/3)+1);
CharSequence num = s;
page.setText(num);
}*/
public void generateButtonStrings(){
for(int i=0; i<18; i++){
arrayButtons[i] = ("Testing Changes " + i);
}
}
public int findPosition(String n){
int position=0;
for(int i=0; i<18; i++){
if(arrayButtons[i].equals(n))
position = i;
}
return position;
}
}
|
package com.networknt.utility;
import org.junit.Assert;
import org.junit.Test;
public class HashUtilTest {
@Test
public void testMd5Hex() {
String md5 = HashUtil.md5Hex("[email protected]");
Assert.assertEquals(md5, "417bed6d9644f12d8bc709059c225c27");
}
@Test
public void testPasswordHash() throws Exception {
String password = "123456";
String hashedPass = HashUtil.generateStorngPasswordHash(password);
System.out.println("hashedPass = " + hashedPass);
Assert.assertTrue(HashUtil.validatePassword(password, hashedPass));
}
@Test
public void testClientSecretHash() throws Exception {
String secret = "f6h1FTI8Q3-7UScPZDzfXA";
String hashedPass = HashUtil.generateStorngPasswordHash(secret);
System.out.println("hashedSecret = " + hashedPass);
Assert.assertTrue(HashUtil.validatePassword(secret, hashedPass));
}
}
|
package com.chickenkiller.upods2.utils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
public class GlobalUtils {
private static final String[] bestStreamPatterns = {".+\\.mp3", ".+[^.]{4}$"};
public static String getBestStreamUrl(JSONArray allUrls) {
String url = "";
try {
url = allUrls.getString(0);
for (String pattern : bestStreamPatterns) {
for (int i = 0; i < allUrls.length(); i++) {
if (allUrls.getString(i).matches(pattern)) {
Log.i("MATCHES", allUrls.getString(i) + "pattern " + pattern);
url = allUrls.getString(i);
return url;
}
Log.i("NOT", allUrls.getString(i) + "pattern" + pattern);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return url;
}
}
|
package com.darkkeeper.minecraft.mods;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.appodeal.ads.Appodeal;
/*import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;*/
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
//import com.google.firebase.analytics.FirebaseAnalytics;
import com.appodeal.ads.BannerCallbacks;
import com.appodeal.ads.BannerView;
import com.appodeal.ads.InterstitialCallbacks;
import com.backendless.Backendless;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class BaseActivity extends AppCompatActivity {
/* private Tracker globalTracker;*/
public final static String BACKENDLESS_ID = "CB0EF57E-5CF2-1505-FF6A-C070AF81DA00";
public final static String BACKENDLESS_SECRET_KEY = "091E1EA1-2543-89FC-FF96-A3EFF6815500";
public final static String APP_VERSION = "v1";
public final static String DEFAULT_LANGUAGE = "en";
public static String CURRENT_LANGUAGE = "en";
private Tracker globalTracker;
public final static String INTENT_UPDATE = "UPDATE_APP";
protected boolean canShowCommercial = false;
private boolean isBannerShowing = false;
// private static FirebaseAnalytics mFirebaseAnalytics;
private static int backPressedCount = 1;
private Toast toast = null;
private static boolean isActivityVisible;
@Override
protected void onResume() {
super.onResume();
isActivityVisible = true;
isBannerShowing = false;
try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.GONE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.GONE);
} catch (Exception e){
}
showBanner(this);
}
@Override
protected void onPause() {
super.onPause();
isActivityVisible = false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch ( item.getItemId() ){
case android.R.id.home:
logFirebaseEvent("back");
onBackPressed();
return true;
case R.id.action_share:
logFirebaseEvent( "share" );
canShowCommercial = true;
showInterestial( this );
share( this );
return true;
case R.id.action_rate:
logFirebaseEvent( "rate" );
canShowCommercial = true;
showInterestial( this );
rate( this );
return true;
case R.id.action_help:
logFirebaseEvent( "help" );
/* canShowCommercial = true;
showInterestial( this );*/
help( this );
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed(){
canShowCommercial = true;
showInterestial( this );
super.onBackPressed();
/* backPressedCount++;
if ( (3 + backPressedCount)%3 == 0 ){
canShowCommercial = true;
showInterestial( this );
}
super.onBackPressed();*/
}
protected boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void getSystemLanguage (){
CURRENT_LANGUAGE = Locale.getDefault().getLanguage();
}
protected void initDatabase () {
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
}
protected void initAds () {
String appKey = getResources().getString(R.string.appodeal_id);
Appodeal.confirm(Appodeal.SKIPPABLE_VIDEO);
Appodeal.disableNetwork(this, "cheetah");
// Appodeal.disableNetwork(this, "yandex");
Appodeal.disableNetwork(this, "unity_ads");
Appodeal.initialize(this, appKey, Appodeal.BANNER_BOTTOM | Appodeal.INTERSTITIAL | Appodeal.SKIPPABLE_VIDEO);
}
protected void initGoogleAnalytics ( Context context ) {
// mFirebaseAnalytics = FirebaseAnalytics.getInstance( context );
GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);
globalTracker = analytics.newTracker( R.xml.global_tracker );
globalTracker.setScreenName(getPackageName());
globalTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
private void logFirebaseEvent ( String event ){
/* Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, event);
// bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, event);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
}
protected void showInterestial ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
if (canShowCommercial) {
Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);
}
}
protected void showBanner ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
// isBannerShowing = false;
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}
protected void setAppodealCallbacks ( final Context context ) {
Appodeal.setInterstitialCallbacks(new InterstitialCallbacks() {
private Toast mToast;
@Override
public void onInterstitialLoaded(boolean isPrecache) {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialFailedToLoad() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialShown() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClicked() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClosed() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
});
Appodeal.setBannerCallbacks(new BannerCallbacks() {
private Toast mToast;
@Override
public void onBannerLoaded(int height, boolean isPrecache) {
// showToast(String.format("onBannerLoaded, %ddp" + isBannerShowing, height));
/* if ( !isBannerShowing && Appodeal.isLoaded(Appodeal.BANNER_BOTTOM)){
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
isBannerShowing = true;
}*/
}
@Override
public void onBannerFailedToLoad() {
// showToast("onBannerFailedToLoad");
}
@Override
public void onBannerShown() {
/* try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.VISIBLE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.VISIBLE);
NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView2);
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.getLayoutParams().height += 50;
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.invalidate();
} catch (Exception e){
Log.d("MY_LOGS", "ERROR = " + e.toString());
e.printStackTrace();
}*/
// showToast("onBannerShown");
}
@Override
public void onBannerClicked() {
// showToast("onBannerClicked");
}
void showToast(final String text) {
if (mToast == null) {
mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
});
}
/* protected void showAdsOnStart ( Context context ) {
Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}*/
protected void showPermissionDialog ( final Context context ) {
AlertDialog.Builder permissions = new AlertDialog.Builder( context );
permissions.setMessage(R.string.showPermissionMessage)
.setTitle(R.string.notificationMessage)
.setCancelable(false)
.setPositiveButton(R.string.answerOk,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions((MainActivity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return;
}
}
);
AlertDialog alert = permissions.create();
alert.show();
}
protected void showOffer ( final Context mContext, String spinnerChoice ){
if ( spinnerChoice != null ) {
AlertDialog.Builder rate = new AlertDialog.Builder(mContext);
String helpMessage = getString(R.string.offerMessage1) + mContext.getResources().getString(R.string.app_name) + "!" + "\n" + "\n" +
getString(R.string.offerMessage2) + "\n" + "\n" +
getString(R.string.offerMessage3);
rate.setMessage(helpMessage)
.setTitle(R.string.offerTitle)
.setCancelable(false)
.setNegativeButton(R.string.answerCancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
)
.setPositiveButton(getString(R.string.answerOk),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=net.zhuoweizhang.mcpelauncher"));
mContext.startActivity(i);
}
}
);
AlertDialog alert = rate.create();
alert.show();
} else {
Toast toast = Toast.makeText( mContext, R.string.noVersionSelectedMessage, Toast.LENGTH_LONG );
toast.show();
}
}
protected void showInetRequirementMessage ( final Context context ) {
if (isActivityVisible) {
try {
toast.getView().isShown();
toast.setText(R.string.networkReq);
} catch (Exception e) {
toast = Toast.makeText(context, R.string.networkReq, Toast.LENGTH_SHORT);
}
toast.show();
}
/* if ( toast==null || toast.getView().getWindowVisibility() != View.GONE ) {
toast = Toast.makeText(context, "Network is Unnavailable", Toast.LENGTH_SHORT);
toast.show();
Log.d("LOGS", "" + toast + " VISIBILITY = " + toast.getView().getWindowVisibility() + " isShown = " + toast.getView().isShown() + " getWindowToken = " + toast.getView().getWindowToken());
}*/
}
protected void showExitDialog ( Context context ) {
Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO | Appodeal.INTERSTITIAL);
AlertDialog.Builder exit = new AlertDialog.Builder( context );
exit.setMessage(R.string.exitText)
.setTitle(R.string.exitQuestion)
.setCancelable(false)
.setPositiveButton(R.string.answerYes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
}
)
.setNegativeButton(R.string.answerNo,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = exit.create();
alert.show();
}
protected void showUpdateDialog ( final Context context ) {
AlertDialog.Builder alert = new AlertDialog.Builder( context );
alert.setMessage(R.string.updateMessage)
.setTitle(R.string.updateTitle)
.setCancelable(false)
.setPositiveButton(R.string.answerInstallNow,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
}
)
.setNegativeButton(R.string.answerLater,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
return;
}
}
);
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
protected void rate ( Context context ) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
protected void share ( Context context ) {
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List<Intent> targetedShareIntents = new ArrayList<Intent>();
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("text/plain");
if (info.activityInfo.packageName.toLowerCase().contains("facebook") || info.activityInfo.name.toLowerCase().contains("facebook") || info.activityInfo.packageName.toLowerCase().contains("twitter") || info.activityInfo.name.toLowerCase().contains("twitter") || info.activityInfo.packageName.toLowerCase().contains("vk") || info.activityInfo.name.toLowerCase().contains("vk")) {
targetedShare.putExtra(Intent.EXTRA_TEXT, context.getString( context.getApplicationInfo().labelRes) + getString(R.string.shareMessage) + "https://play.google.com/store/apps/details?id=" + context.getPackageName());
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
context.startActivity(chooserIntent);
}
}
protected void help ( final Context context ) {
Intent i = new Intent( context, HelpActivity.class );
context.startActivity(i);
}
protected void sendEmail( Context context ){
Intent myIntent1 = new Intent(android.content.Intent.ACTION_SEND);
myIntent1.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
final String my1 = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID);
final String my2 = android.os.Build.DEVICE;
final String my3 = android.os.Build.MANUFACTURER;
final String my4 = android.os.Build.MODEL;
final String my5 = android.os.Build.VERSION.RELEASE;
final int my6 = android.os.Build.VERSION.SDK_INT;
final String my7 = android.os.Build.BRAND;
final String my8 = android.os.Build.VERSION.INCREMENTAL;
final String my9 = android.os.Build.PRODUCT;
myIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Support Request: " + my1 + " Application: " + context.getPackageName() + " Device: " + my2 + " Manufacturer: " + my3 + " Model: " + my4 + " Version: " + my5 + " SDK: " + my6 + " Brand: " + my7 + " Incremental: " + my8 + " Product: " + my9);
myIntent1.setType("text/plain");
//IN CASE EMAIL APP FAILS, THEN DEFINE THE OPTION TO LAUNCH SUPPORT WEBSITE
String url2 = "";
Intent myIntent2 = new Intent(Intent.ACTION_VIEW);
myIntent2.setData(Uri.parse(url2));
//IF USER CLICKS THE OK BUTTON, THEN DO THIS
try {
// TRY TO LAUNCH TO EMAIL APP
context.startActivity(Intent.createChooser(myIntent1, "Send email to Developer"));
// startActivity(myIntent1);
} catch (ActivityNotFoundException ex) {
// ELSE LAUNCH TO WEB BROWSER
// activity.startActivity(myIntent2);
}
}
protected boolean isPermissionGranted (){
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ;
}
}
|
package com.jasonette.seed.Action;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.jasonette.seed.Helper.JasonHelper;
import org.json.JSONException;
import org.json.JSONObject;
public class JasonOauthAction {
public void auth(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if(options.getString("version").equals("1")) {
//OAuth 1
JSONObject request_options = options.getJSONObject("request");
JSONObject authorize_options = options.getJSONObject("authorize");
String client_id = request_options.getString("client_id");
String client_secret = request_options.getString("client_secret");
if(!request_options.has("scheme") || request_options.getString("scheme").length() == 0
|| !request_options.has("host") || request_options.getString("host").length() == 0
|| !request_options.has("path") || request_options.getString("path").length() == 0
|| !authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
JSONObject request_options_data = request_options.getJSONObject("data");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(request_options.getString("scheme"))
.encodedAuthority(request_options.getString("host"))
.encodedPath(request_options.getString("path"));
final String requestUri = uriBuilder.build().toString();
final Uri.Builder authorizeUriBuilder = new Uri.Builder();
authorizeUriBuilder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
String callback_uri = request_options_data.getString("oauth_callback");
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() {
return requestUri;
}
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return authorizeUriBuilder
.appendQueryParameter("oauth_token", requestToken.getToken())
.build().toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(callback_uri)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String client_id = params[0];
OAuth1RequestToken request_token = oauthService.getRequestToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id + "_request_token_secret", request_token.getTokenSecret()).apply();
String auth_url = oauthService.getAuthorizationUrl(request_token);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(auth_url));
context.startActivity(intent);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(client_id);
}
} else {
//OAuth 2
JSONObject authorize_options = options.getJSONObject("authorize");
JSONObject authorize_options_data = new JSONObject();
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
}
if(authorize_options_data.has("grant_type") && authorize_options_data.getString("grant_type").equals("password")) {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
|| !authorize_options_data.has("username") || authorize_options_data.getString("username").length() == 0
|| !authorize_options_data.has("password") || authorize_options_data.getString("password").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
String username = authorize_options_data.getString("username");
String password = authorize_options_data.getString("password");
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return uri.toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String username = params[0];
String password = params[1];
String client_id = params[2];
String access_token = oauthService.getAccessTokenPasswordGrant(username, password).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} catch(JSONException e) {
handleError(e, action, event, context);
}
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(username, password, client_id);
}
} else {
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
} else {
JSONObject error = new JSONObject();
error.put("data", "Authorize data missing");
JasonHelper.next("error", action, error, event, context);
}
//Assuming code auth
if(authorize_options == null || authorize_options.length() == 0) {
JasonHelper.next("error", action, data, event, context);
} else {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
String redirect_uri = "";
String scope = "";
//Secret can be missing in implicit authentication
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(authorize_options_data.has("redirect_uri")) {
redirect_uri = authorize_options_data.getString("redirect_uri");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return uri.toString();
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
serviceBuilder.callback(redirect_uri);
OAuth20Service oauthService = serviceBuilder.build(oauthApi);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(oauthService.getAuthorizationUrl()));
context.startActivity(intent);
}
}
}
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void access_token(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getJSONObject("access").getString("client_id");
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
if(access_token != null) {
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject error = new JSONObject();
error.put("data", "access token not found");
JasonHelper.next("error", action, error, event, context);
}
} catch(JSONException e) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
public void oauth_callback(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if (options.has("version") && options.getString("version").equals("1")) {
//OAuth 1
if(action.has("uri")) {
Uri uri = Uri.parse(action.getString("uri"));
String oauth_token = uri.getQueryParameter("oauth_token");
String oauth_verifier = uri.getQueryParameter("oauth_verifier");
JSONObject access_options = options.getJSONObject("access");
if(
oauth_token.length() > 0 && oauth_verifier.length() > 0
&& access_options.has("scheme") && access_options.getString("scheme").length() > 0
&& access_options.has("host") && access_options.getString("host").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("client_id") && access_options.getString("client_id").length() > 0
&& access_options.has("client_secret") && access_options.getString("client_secret").length() > 0
) {
String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(access_options.getString("scheme"))
.encodedAuthority(access_options.getString("host"))
.encodedPath(access_options.getString("path"));
final String accessUri = uriBuilder.build().toString();
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() {
return accessUri.toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String string_oauth_token = params[0];
String oauth_verifier = params[1];
String client_id = params[2];
String oauth_token_secret = preferences.getString(client_id + "_request_token_secret", null);
OAuth1RequestToken oauthToken = new OAuth1RequestToken(string_oauth_token, oauth_token_secret);
OAuth1AccessToken access_token = oauthService.getAccessToken(oauthToken, oauth_verifier);
preferences.edit().putString(client_id, access_token.getToken()).apply();
preferences.edit().putString(client_id + "_access_token_secret", access_token.getTokenSecret()).apply();
JSONObject result = new JSONObject();
result.put("token", access_token.getToken());
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(oauth_token, oauth_verifier, client_id);
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
// OAuth 2
Uri uri = Uri.parse(action.getString("uri"));
String access_token = uri.getQueryParameter("access_token"); // get access token from url here
JSONObject authorize_options = options.getJSONObject("authorize");
if (access_token != null && access_token.length() > 0) {
String client_id = authorize_options.getString("client_id");
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject access_options = options.getJSONObject("access");
final String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
String redirect_uri = "";
if(access_options.has("redirect_uri")) {
redirect_uri = access_options.getString("redirect_uri");
}
final String code = uri.getQueryParameter("code");
if (access_options.length() == 0
|| !access_options.has("scheme") || access_options.getString("scheme").length() == 0
|| !access_options.has("host") || access_options.getString("host").length() == 0
|| !access_options.has("path") || access_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
final Uri.Builder builder = new Uri.Builder();
builder.scheme(access_options.getString("scheme"))
.authority(access_options.getString("host"))
.appendEncodedPath(access_options.getString("path"));
if(redirect_uri != "") {
builder.appendQueryParameter("redirect_uri", redirect_uri);
}
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return builder.build().toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
serviceBuilder.apiSecret(client_secret);
if(redirect_uri != "") {
serviceBuilder.callback(redirect_uri);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
String access_token = oauthService.getAccessToken(code).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
} catch(JSONException e) {
handleError(e, action, event, context);
}
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
}
}
}
catch(JSONException e) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
public void reset(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
if(options.has("version") && options.getString("version").equals("1")) {
//TODO
} else {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().remove(client_id).apply();
JasonHelper.next("success", action, data, event, context);
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void request(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
String client_secret = "";
if(options.has("client_secret") && options.getString("client_secret").length() > 0) {
client_secret = options.getString("client_secret");
}
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
String path = options.getString("path");
String scheme = options.getString("scheme");
String host = options.getString("host");
String method;
if(options.has("method")) {
method = options.getString("method");
} else {
method = "GET";
}
if(access_token != null && access_token.length() > 0) {
if(options.has("version") && options.getString("version").equals("1")) {
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() { return null; }
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth10aService oauthService = serviceBuilder.build(oauthApi);
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.encodedAuthority(host);
uriBuilder.path(path);
Uri uri = uriBuilder.build();
String url = uri.toString();
final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);
String access_token_secret = sharedPreferences.getString(client_id + "_access_token_secret", null);
oauthService.signRequest(new OAuth1AccessToken(access_token, access_token_secret), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
com.github.scribejava.core.model.Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
} else {
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.encodedAuthority(host);
uriBuilder.encodedPath(path);
Uri uri = uriBuilder.build();
String url = uri.toString();
final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);
oauthService.signRequest(new OAuth2AccessToken(access_token), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
com.github.scribejava.core.model.Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
} else {
JasonHelper.next("error", action, data, event, context);
}
//change exception
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
private void handleError(Exception e, JSONObject action, JSONObject event, Context context) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
|
package com.t28.rxweather.fragment;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.t28.rxweather.R;
import com.t28.rxweather.data.model.Coordinate;
import com.t28.rxweather.data.model.MainAttribute;
import com.t28.rxweather.data.model.Weather;
import com.t28.rxweather.data.service.WeatherService;
import com.t28.rxweather.rx.CoordinateEventBus;
import com.t28.rxweather.volley.RequestQueueRetriever;
import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Observer;
import rx.android.observables.AndroidObservable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class WeatherFragment extends Fragment {
@InjectView(R.id.weather_temperature)
TextView mTemperatureView;
@InjectView(R.id.weather_min_temperature)
TextView mMinTemperatureView;
@InjectView(R.id.weather_max_temperature)
TextView mMaxTemperatureView;
private WeatherService mWeatherService;
public WeatherFragment() {
setRetainInstance(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWeatherService = new WeatherService("", RequestQueueRetriever.retrieve());
AndroidObservable.bindFragment(this, createWeatherObservable())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Weather>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable cause) {
onFailure(cause);
}
@Override
public void onNext(Weather result) {
onSuccess(result);
}
});
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_weather, container, false);
ButterKnife.inject(this, view);
return view;
}
@Override
public void onDestroyView() {
ButterKnife.reset(this);
super.onDestroyView();
}
private void onSuccess(Weather result) {
if (isDetached()) {
return;
}
final Activity activity = getActivity();
Toast.makeText(activity, result.toString(), Toast.LENGTH_SHORT).show();
final MainAttribute attribute = result.getAttribute();
mTemperatureView.setText(String.valueOf(attribute.getTemperature()));
mMinTemperatureView.setText(String.valueOf(attribute.getMinTemperature()));
mMaxTemperatureView.setText(String.valueOf(attribute.getMaxTemperature()));
}
private void onFailure(Throwable cause) {
if (isDetached()) {
return;
}
final Activity activity = getActivity();
Toast.makeText(activity, cause.toString(), Toast.LENGTH_SHORT).show();
}
private Observable<Weather> createWeatherObservable() {
return CoordinateEventBus.Retriever.retrieve()
.getEventStream()
.flatMap(new Func1<Coordinate, Observable<Weather>>() {
@Override
public Observable<Weather> call(Coordinate coordinate) {
return mWeatherService.findWeather(coordinate);
}
});
}
}
|
package com.walkap.x_android.fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.walkap.x_android.R;
import com.walkap.x_android.adapter.SectionsPagerAdapter;
import java.util.Calendar;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link HomeFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends BaseFragment{
private OnFragmentInteractionListener mListener;
private final String TAG = "HomeFragment";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private Calendar calendar = Calendar.getInstance();
private int day = calendar.get(Calendar.DAY_OF_WEEK) - 2;
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(6);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(day);
return rootView;
}
@Override
public void onStart(){
super.onStart();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
|
package com.zulip.android.activities;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.ArrayList;
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.j256.ormlite.android.AndroidDatabaseResults;
import com.zulip.android.BuildConfig;
import com.zulip.android.database.DatabaseHelper;
import com.zulip.android.models.Emoji;
import com.zulip.android.filters.NarrowFilterToday;
import com.zulip.android.models.Message;
import com.zulip.android.models.MessageType;
import com.zulip.android.filters.NarrowFilter;
import com.zulip.android.filters.NarrowFilterAllPMs;
import com.zulip.android.filters.NarrowFilterPM;
import com.zulip.android.filters.NarrowFilterSearch;
import com.zulip.android.filters.NarrowFilterStream;
import com.zulip.android.filters.NarrowListener;
import com.zulip.android.gcm.Notifications;
import com.zulip.android.models.Person;
import com.zulip.android.models.Presence;
import com.zulip.android.models.PresenceType;
import com.zulip.android.R;
import com.zulip.android.models.Stream;
import com.zulip.android.networking.AsyncSend;
import com.zulip.android.util.AnimationHelper;
import com.zulip.android.util.SwipeRemoveLinearLayout;
import com.zulip.android.util.ZLog;
import com.zulip.android.ZulipApp;
import com.zulip.android.gcm.GcmBroadcastReceiver;
import com.zulip.android.networking.AsyncGetEvents;
import com.zulip.android.networking.AsyncStatusUpdate;
import com.zulip.android.networking.ZulipAsyncPushTask;
import org.json.JSONObject;
/**
* The main Activity responsible for holding the {@link MessageListFragment} which has the list to the
* messages
* */
public class ZulipActivity extends AppCompatActivity implements
MessageListFragment.Listener, NarrowListener, SwipeRemoveLinearLayout.leftToRightSwipeListener {
private static final String NARROW = "narrow";
private static final String PARAMS = "params";
//At these many letters the emoji/person hint will not show now on
private static final int MAX_THRESOLD_EMOJI_HINT = 5;
//At these many letters the emoji/person hint starts to show up
private static final int MIN_THRESOLD_EMOJI_HINT = 1;
private ZulipApp app;
private List<Message> mutedTopics;
private boolean suspended = false;
private boolean logged_in = false;
private ZulipActivity that = this; // self-ref
private SharedPreferences settings;
String client_id;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ExpandableListView streamsDrawer;
private static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();
private SwipeRemoveLinearLayout chatBox;
private FloatingActionButton fab;
private CountDownTimer fabHidder;
private boolean isTextFieldFocused = false;
private static final int HIDE_FAB_AFTER_SEC = 5;
private HashMap<String, Bitmap> gravatars = new HashMap<>();
private AsyncGetEvents event_poll;
private Handler statusUpdateHandler;
private Toolbar toolbar;
public MessageListFragment currentList;
private MessageListFragment narrowedList;
private MessageListFragment homeList;
private AutoCompleteTextView streamActv;
private AutoCompleteTextView topicActv;
private AutoCompleteTextView messageEt;
private TextView textView;
private ImageView sendBtn;
private ImageView togglePrivateStreamBtn;
private Notifications notifications;
private SimpleCursorAdapter streamActvAdapter;
private SimpleCursorAdapter subjectActvAdapter;
private SimpleCursorAdapter emailActvAdapter;
private BroadcastReceiver onGcmMessage = new BroadcastReceiver() {
public void onReceive(Context contenxt, Intent intent) {
// Block the event before it propagates to show a notification.
// TODO: could be smarter and only block the event if the message is
// in the narrow.
Log.i("GCM", "Dropping a push because the activity is active");
abortBroadcast();
}
};
@Override
public void removeChatBox(boolean animToRight) {
AnimationHelper.hideViewX(chatBox, animToRight);
}
// Intent Extra constants
public enum Flag {
RESET_DATABASE,
}
public HashMap<String, Bitmap> getGravatars() {
return gravatars;
}
private SimpleCursorAdapter.ViewBinder peopleBinder = new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int i) {
switch (view.getId()) {
case R.id.name:
TextView name = (TextView) view;
name.setText(cursor.getString(i));
return true;
case R.id.stream_dot:
String email = cursor.getString(i);
if (app == null || email == null) {
view.setVisibility(View.INVISIBLE);
} else {
Presence presence = app.presences.get(email);
if (presence == null) {
view.setVisibility(View.INVISIBLE);
} else {
PresenceType status = presence.getStatus();
long age = presence.getAge();
if (age > 2 * 60) {
view.setVisibility(View.VISIBLE);
view.setBackgroundResource(R.drawable.presence_inactive);
} else if (PresenceType.ACTIVE == status) {
view.setVisibility(View.VISIBLE);
view.setBackgroundResource(R.drawable.presence_active);
} else if (PresenceType.IDLE == status) {
view.setVisibility(View.VISIBLE);
view.setBackgroundResource(R.drawable.presence_away);
} else {
view.setVisibility(View.INVISIBLE);
}
}
}
return true;
default:
break;
}
return false;
}
};
private RefreshableCursorAdapter peopleAdapter;
@Override
public void addToList(Message message) {
mutedTopics.add(message);
}
@Override
public void muteTopic(Message message) {
app.muteTopic(message);
for (int i = homeList.adapter.getItemCount() - 1; i >= 0; i
Object object = homeList.adapter.getItem(i);
if (object instanceof Message) {
Message msg = (Message) object;
if (msg.getStream() != null
&& msg.getStream().getId() == message.getStream().getId()
&& msg.getSubject().equals(message.getSubject())) {
mutedTopics.add(msg);
homeList.adapter.remove(msg);
}
}
}
homeList.adapter.notifyDataSetChanged();
}
@Override
public void recyclerViewScrolled() {
if (chatBox.getVisibility() == View.VISIBLE && !isTextFieldFocused) {
displayChatBox(false);
displayFAB(true);
}
}
public RefreshableCursorAdapter getPeopleAdapter() {
return peopleAdapter;
}
/**
* Called when the activity is first created.
*/
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (ZulipApp) getApplicationContext();
settings = app.getSettings();
processParams();
if (!app.isLoggedIn()) {
openLogin();
return;
}
this.logged_in = true;
notifications = new Notifications(this);
notifications.register();
setContentView(R.layout.main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_24dp);
streamActv = (AutoCompleteTextView) findViewById(R.id.stream_actv);
topicActv = (AutoCompleteTextView) findViewById(R.id.topic_actv);
messageEt = (AutoCompleteTextView) findViewById(R.id.message_et);
textView = (TextView) findViewById(R.id.textView);
sendBtn = (ImageView) findViewById(R.id.send_btn);
togglePrivateStreamBtn = (ImageView) findViewById(R.id.togglePrivateStream_btn);
mutedTopics = new ArrayList<>();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, R.string.streams_open,
R.string.streams_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
// pass
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// pass
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(drawerToggle);
ListView peopleDrawer = (ListView) findViewById(R.id.people_drawer);
// row number which is used to differentiate the 'All private messages'
// row from the people
final int allPeopleId = -1;
Callable<Cursor> peopleGenerator = new Callable<Cursor>() {
@Override
public Cursor call() throws Exception {
// TODO Auto-generated method stub
List<Person> people = app.getDao(Person.class).queryBuilder()
.where().eq(Person.ISBOT_FIELD, false).and()
.eq(Person.ISACTIVE_FIELD, true).query();
Person.sortByPresence(app, people);
String[] columnsWithPresence = new String[]{"_id",
Person.EMAIL_FIELD, Person.NAME_FIELD};
MatrixCursor sortedPeopleCursor = new MatrixCursor(
columnsWithPresence);
for (Person person : people) {
Object[] row = new Object[]{person.getId(), person.getEmail(),
person.getName()};
sortedPeopleCursor.addRow(row);
}
// add private messages row
MatrixCursor allPrivateMessages = new MatrixCursor(
sortedPeopleCursor.getColumnNames());
Object[] row = new Object[]{allPeopleId, "",
"All private messages"};
allPrivateMessages.addRow(row);
return new MergeCursor(new Cursor[]{
allPrivateMessages, sortedPeopleCursor});
}
};
try {
this.peopleAdapter = new RefreshableCursorAdapter(
this.getApplicationContext(), R.layout.stream_tile,
peopleGenerator.call(), peopleGenerator, new String[]{
Person.NAME_FIELD, Person.EMAIL_FIELD}, new int[]{
R.id.name, R.id.stream_dot}, 0);
peopleAdapter.setViewBinder(peopleBinder);
peopleDrawer.setAdapter(peopleAdapter);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (Exception e) {
ZLog.logException(e);
}
peopleDrawer.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (id == allPeopleId) {
doNarrow(new NarrowFilterAllPMs(app.getYou()));
} else {
narrow_pm_with(Person.getById(app, (int) id));
}
}
});
// send status update and check again every couple minutes
statusUpdateHandler = new Handler();
Runnable statusUpdateRunnable = new Runnable() {
@Override
public void run() {
AsyncStatusUpdate task = new AsyncStatusUpdate(
ZulipActivity.this);
task.setCallback(new ZulipAsyncPushTask.AsyncTaskCompleteListener() {
@Override
public void onTaskComplete(String result, JSONObject object) {
peopleAdapter.refresh();
}
@Override
public void onTaskFailure(String result) {
}
});
task.execute();
statusUpdateHandler.postDelayed(this, 2 * 60 * 1000);
}
};
statusUpdateHandler.post(statusUpdateRunnable);
homeList = MessageListFragment.newInstance(null);
pushListFragment(homeList, null);
togglePrivateStreamBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchView();
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
composeStatus = (LinearLayout) findViewById(R.id.composeStatus);
setUpAdapter();
streamActv.setAdapter(streamActvAdapter);
topicActv.setAdapter(subjectActvAdapter);
checkAndSetupStreamsDrawer();
setupFab();
View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean focus) {
isTextFieldFocused = focus;
}
};
messageEt.setOnFocusChangeListener(focusChangeListener);
topicActv.setOnFocusChangeListener(focusChangeListener);
streamActv.setOnFocusChangeListener(focusChangeListener);
SimpleCursorAdapter combinedAdapter = new SimpleCursorAdapter(
that, R.layout.emoji_tile, null,
new String[]{Emoji.NAME_FIELD, Emoji.NAME_FIELD},
new int[]{R.id.emojiImageView, R.id.nameTV}, 0);
combinedAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
//TODO - columnIndex is 6 for Person table and columnIndex is 1 for Emoji table, Confirm this will be perfect to distinguish between these two tables! It seems alphabetical ordering of columns!
boolean personTable = !(columnIndex == 1);
String name = cursor.getString(cursor.getColumnIndex(Emoji.NAME_FIELD));
switch (view.getId()) {
case R.id.emojiImageView:
if (personTable) {
view.setVisibility(View.GONE);
} else {
try {
Drawable drawable = Drawable.createFromStream(getApplicationContext().getAssets().open("emoji/" + name),
"emoji/" + name);
((ImageView) view).setImageDrawable(drawable);
} catch (Exception e) {
ZLog.logException(e);
}
}
return true;
case R.id.nameTV:
((TextView) view).setText(name);
return true;
}
if (BuildConfig.DEBUG)
ZLog.logException(new RuntimeException(getResources().getResourceName(view.getId()) + " - this view not binded!"));
return false;
}
});
combinedAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
if (cursor == null) return messageEt.getText();
int index = cursor.getColumnIndex(Emoji.NAME_FIELD);
String name = cursor.getString(index);
String currText = messageEt.getText().toString();
int last = (cursor.getColumnIndex(Emoji.NAME_FIELD) == 6) ? currText.lastIndexOf("@") : currText.lastIndexOf(":");
return TextUtils.substring(currText, 0, last) + ((cursor.getColumnIndex(Emoji.NAME_FIELD) == 6) ? "@**" + name + "**" : ":" + name.replace(".png", "") + ":");
}
});
combinedAdapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence charSequence) {
if (charSequence == null) return null;
int length = charSequence.length();
int personLength = charSequence.toString().lastIndexOf("@");
int smileyLength = charSequence.toString().lastIndexOf(":");
if (length - 1 > Math.max(personLength, smileyLength) + MAX_THRESOLD_EMOJI_HINT
|| length - Math.max(personLength, smileyLength) - 1 < MIN_THRESOLD_EMOJI_HINT
|| (personLength + smileyLength == -2))
return null;
try {
if (personLength > smileyLength) {
return makePeopleNameCursor(charSequence.subSequence(personLength + 1, length));
} else {
return makeEmojiCursor(charSequence.subSequence(smileyLength + 1, length));
}
} catch (SQLException e) {
Log.e("SQLException", "SQL not correct", e);
return null;
}
}
});
messageEt.setAdapter(combinedAdapter);
}
/**
* Returns a cursor for the combinedAdapter used to suggest Emoji when ':' is typed in the {@link #messageEt}
* @param emoji A string to search in the existing database
*/
private Cursor makeEmojiCursor(CharSequence emoji)
throws SQLException {
if (emoji == null) {
emoji = "";
}
return ((AndroidDatabaseResults) app
.getDao(Emoji.class)
.queryRaw("SELECT rowid _id,name FROM emoji WHERE name LIKE '%" + emoji + "%'")
.closeableIterator().getRawResults()).getRawCursor();
}
private Cursor makePeopleNameCursor(CharSequence name) throws SQLException {
if (name == null) {
name = "";
}
return ((AndroidDatabaseResults) app
.getDao(Person.class)
.queryRaw(
"SELECT rowid _id, * FROM people WHERE "
+ Person.ISBOT_FIELD + " = 0 AND "
+ Person.ISACTIVE_FIELD + " = 1 AND "
+ Person.NAME_FIELD
+ " LIKE ? ESCAPE '\\' ORDER BY "
+ Person.NAME_FIELD + " COLLATE NOCASE",
DatabaseHelper.likeEscape(name.toString()) + "%")
.closeableIterator().getRawResults()).getRawCursor();
}
private void setupFab() {
fab = (FloatingActionButton) findViewById(R.id.fab);
chatBox = (SwipeRemoveLinearLayout) findViewById(R.id.messageBoxContainer);
chatBox.registerToSwipeEvents(this);
fabHidder = new CountDownTimer(HIDE_FAB_AFTER_SEC * 1000, HIDE_FAB_AFTER_SEC * 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (!isTextFieldFocused) {
displayFAB(true);
displayChatBox(false);
} else {
start();
}
}
};
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentList.stopRecyclerViewScroll();
displayChatBox(true);
displayFAB(false);
fabHidder.start();
}
});
}
private void displayChatBox(boolean show) {
if (show) {
showView(chatBox);
} else {
hideView(chatBox);
}
}
private void displayFAB(boolean show) {
if (show) {
showView(fab);
} else {
hideView(fab);
}
}
public void hideView(final View view) {
ViewPropertyAnimator animator = view.animate()
.translationY((view instanceof AppBarLayout) ? -1 * view.getHeight() : view.getHeight())
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setDuration(200);
animator.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
view.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
animator.start();
}
public void showView(final View view) {
ViewPropertyAnimator animator = view.animate()
.translationY(0)
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setDuration(200);
animator.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
view.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animator) {
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
animator.start();
}
Callable<Cursor> streamsGenerator = new Callable<Cursor>() {
@Override
public Cursor call() throws Exception {
int pointer = app.getPointer();
return ((AndroidDatabaseResults) app.getDao(Stream.class).queryRaw("SELECT s.id as _id, s.name, s.color," +
" count(case when m.id > " + pointer + " then 1 end) as " + ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME
+ " FROM streams as s LEFT JOIN messages as m ON s.id=m.stream group by s.name order by s.name COLLATE NOCASE").closeableIterator().getRawResults()).getRawCursor();
}
};
/**
* Setup the streams Drawer which has a {@link ExpandableListView} categorizes the stream and subject
*/
private void setupListViewAdapter() {
ExpandableStreamDrawerAdapter streamsDrawerAdapter = null;
String[] groupFrom = {Stream.NAME_FIELD, Stream.COLOR_FIELD, ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME};
int[] groupTo = {R.id.name, R.id.stream_dot, R.id.unread_group};
// Comparison of data elements and View
String[] childFrom = {Message.SUBJECT_FIELD, ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME};
int[] childTo = {R.id.name_child, R.id.unread_child};
final ExpandableListView streamsDrawer = (ExpandableListView) findViewById(R.id.streams_drawer);
streamsDrawer.setGroupIndicator(null);
try {
streamsDrawerAdapter = new ExpandableStreamDrawerAdapter(this, streamsGenerator.call(),
R.layout.stream_tile_new, groupFrom,
groupTo, R.layout.stream_tile_child, childFrom,
childTo);
} catch (Exception e) {
ZLog.logException(e);
}
streamsDrawer.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
switch (v.getId()) {
case R.id.name_child:
String streamName = ((Cursor) streamsDrawer.getExpandableListAdapter().getGroup(groupPosition)).getString(1);
String subjectName = ((TextView) v).getText().toString();
onNarrow(new NarrowFilterStream(streamName, subjectName));
onNarrowFillSendBoxStream(streamName, subjectName, false);
break;
default:
return false;
}
return false;
}
});
streamsDrawer.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
int previousClick = -1;
@Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int position, long l) {
String streamName = ((TextView) view.findViewById(R.id.name)).getText().toString();
doNarrow(new NarrowFilterStream(streamName, null));
drawerLayout.openDrawer(GravityCompat.START);
if (previousClick != -1 && expandableListView.getCount() > previousClick) {
expandableListView.collapseGroup(previousClick);
}
expandableListView.expandGroup(position);
previousClick = position;
return true;
}
});
streamsDrawerAdapter.setViewBinder(new SimpleCursorTreeAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
switch (view.getId()) {
case R.id.name:
TextView name = (TextView) view;
final String streamName = cursor.getString(columnIndex);
name.setText(streamName);
//Change color in the drawer if this stream is inHomeView only.
if (!Stream.getByName(app, streamName).getInHomeView()) {
name.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextTertiary));
} else {
name.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextPrimary));
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onNarrow(new NarrowFilterStream(streamName, null));
onNarrowFillSendBoxStream(streamName, "", false);
}
});
return true;
case R.id.stream_dot:
// Set the color of the (currently white) dot
view.setVisibility(View.VISIBLE);
view.getBackground().setColorFilter(cursor.getInt(columnIndex),
PorterDuff.Mode.MULTIPLY);
return true;
case R.id.unread_group:
TextView unreadGroupTextView = (TextView) view;
final String unreadGroupCount = cursor.getString(columnIndex);
if (unreadGroupCount.equals("0")) {
unreadGroupTextView.setVisibility(View.GONE);
} else {
unreadGroupTextView.setText(unreadGroupCount);
unreadGroupTextView.setVisibility(View.VISIBLE);
}
return true;
case R.id.unread_child:
TextView unreadChildTextView = (TextView) view;
final String unreadChildNumber = cursor.getString(columnIndex);
if (unreadChildNumber.equals("0")) {
unreadChildTextView.setVisibility(View.GONE);
} else {
unreadChildTextView.setText(unreadChildNumber);
unreadChildTextView.setVisibility(View.VISIBLE);
}
return true;
case R.id.name_child:
TextView name_child = (TextView) view;
name_child.setText(cursor.getString(columnIndex));
if (app.isTopicMute(cursor.getInt(1), cursor.getString(columnIndex))) {
name_child.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextSecondary));
}
return true;
}
return false;
}
});
streamsDrawer.setAdapter(streamsDrawerAdapter);
}
/**
* Initiates the streams Drawer if the streams in the drawer is 0.
*/
public void checkAndSetupStreamsDrawer() {
try {
if (streamsDrawer.getAdapter().getCount() != 0) {
return;
}
setupListViewAdapter();
} catch (NullPointerException npe) {
setupListViewAdapter();
}
}
private void sendMessage() {
if (isCurrentModeStream()) {
if (TextUtils.isEmpty(streamActv.getText().toString())) {
streamActv.setError(getString(R.string.stream_error));
streamActv.requestFocus();
return;
} else {
try {
Cursor streamCursor = makeStreamCursor(streamActv.getText().toString());
if (streamCursor.getCount() == 0) {
streamActv.setError(getString(R.string.stream_not_exists));
streamActv.requestFocus();
return;
}
} catch (SQLException e) {
Log.e("SQLException", "SQL not correct", e);
}
}
if (TextUtils.isEmpty(topicActv.getText().toString())) {
topicActv.setError(getString(R.string.subject_error));
topicActv.requestFocus();
return;
}
} else {
if (TextUtils.isEmpty(topicActv.getText().toString())) {
topicActv.setError(getString(R.string.person_error));
topicActv.requestFocus();
return;
}
}
if (TextUtils.isEmpty(messageEt.getText().toString())) {
messageEt.setError(getString(R.string.no_message_error));
messageEt.requestFocus();
return;
}
sendingMessage(true);
MessageType messageType = isCurrentModeStream() ? MessageType.STREAM_MESSAGE : MessageType.PRIVATE_MESSAGE;
Message msg = new Message(app);
msg.setSender(app.getYou());
if (messageType == MessageType.STREAM_MESSAGE) {
msg.setType(messageType);
msg.setStream(new Stream(streamActv.getText().toString()));
msg.setSubject(topicActv.getText().toString());
} else if (messageType == MessageType.PRIVATE_MESSAGE) {
msg.setType(messageType);
msg.setRecipient(topicActv.getText().toString().split(","));
}
msg.setContent(messageEt.getText().toString());
AsyncSend sender = new AsyncSend(that, msg);
sender.setCallback(new ZulipAsyncPushTask.AsyncTaskCompleteListener() {
public void onTaskComplete(String result, JSONObject jsonObject) {
Toast.makeText(ZulipActivity.this, R.string.message_sent, Toast.LENGTH_SHORT).show();
messageEt.setText("");
sendingMessage(false);
}
public void onTaskFailure(String result) {
Log.d("onTaskFailure", "Result: " + result);
Toast.makeText(ZulipActivity.this, R.string.message_error, Toast.LENGTH_SHORT).show();
sendingMessage(false);
}
});
sender.execute();
}
/**
* Disable chatBox and show a loading footer while sending the message.
*/
private void sendingMessage(boolean isSending) {
streamActv.setEnabled(!isSending);
textView.setEnabled(!isSending);
messageEt.setEnabled(!isSending);
topicActv.setEnabled(!isSending);
sendBtn.setEnabled(!isSending);
togglePrivateStreamBtn.setEnabled(!isSending);
if (isSending)
composeStatus.setVisibility(View.VISIBLE);
else
composeStatus.setVisibility(View.GONE);
}
private LinearLayout composeStatus;
/**
* Setup adapter's for the {@link AutoCompleteTextView}
*
* These adapters are being intialized -
*
* {@link #streamActvAdapter} Adapter for suggesting all the stream names in this AutoCompleteTextView
* {@link #emailActvAdapter} Adapter for suggesting all the person email's in this AutoCompleteTextView
* {@link #subjectActvAdapter} Adapter for suggesting all the topic for the stream specified in the {@link #streamActv} in this AutoCompleteTextView
*/
private void setUpAdapter() {
streamActvAdapter = new SimpleCursorAdapter(
that, R.layout.stream_tile, null,
new String[]{Stream.NAME_FIELD},
new int[]{R.id.name}, 0);
streamActvAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
int index = cursor.getColumnIndex(Stream.NAME_FIELD);
return cursor.getString(index);
}
});
streamActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence charSequence) {
try {
return makeStreamCursor(charSequence);
} catch (SQLException e) {
Log.e("SQLException", "SQL not correct", e);
return null;
}
}
});
subjectActvAdapter = new SimpleCursorAdapter(
that, R.layout.stream_tile, null,
new String[]{Message.SUBJECT_FIELD},
new int[]{R.id.name}, 0);
subjectActvAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
int index = cursor.getColumnIndex(Message.SUBJECT_FIELD);
return cursor.getString(index);
}
});
subjectActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence charSequence) {
try {
return makeSubjectCursor(streamActv.getText().toString(), charSequence);
} catch (SQLException e) {
Log.e("SQLException", "SQL not correct", e);
return null;
}
}
});
emailActvAdapter = new SimpleCursorAdapter(
that, R.layout.stream_tile, null,
new String[]{Person.EMAIL_FIELD},
new int[]{R.id.name}, 0);
emailActvAdapter
.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
String text = topicActv.getText().toString();
String prefix;
int lastIndex = text.lastIndexOf(',');
if (lastIndex != -1) {
prefix = text.substring(0, lastIndex + 1);
} else {
prefix = "";
}
int index = cursor.getColumnIndex(Person.EMAIL_FIELD);
return prefix + cursor.getString(index);
}
});
emailActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence charSequence) {
try {
return makePeopleCursor(charSequence);
} catch (SQLException e) {
Log.e("SQLException", "SQL not correct", e);
return null;
}
}
});
sendingMessage(false);
}
/**
* Creates a cursor to get the streams saved in the database
* @param streamName Filter out streams name containing this string
*/
private Cursor makeStreamCursor(CharSequence streamName)
throws SQLException {
if (streamName == null) {
streamName = "";
}
return ((AndroidDatabaseResults) app
.getDao(Stream.class)
.queryRaw(
"SELECT rowid _id, * FROM streams WHERE "
+ Stream.SUBSCRIBED_FIELD + " = 1 AND "
+ Stream.NAME_FIELD
+ " LIKE ? ESCAPE '\\' ORDER BY "
+ Stream.NAME_FIELD + " COLLATE NOCASE",
DatabaseHelper.likeEscape(streamName.toString()) + "%")
.closeableIterator().getRawResults()).getRawCursor();
}
/**
* Creates a cursor to get the topics in the stream in
* @param stream
* @param subject Filter out subject containing this string
*/
private Cursor makeSubjectCursor(CharSequence stream, CharSequence subject)
throws SQLException {
if (subject == null) {
subject = "";
}
if (stream == null) {
stream = "";
}
AndroidDatabaseResults results = (AndroidDatabaseResults) app
.getDao(Message.class)
.queryRaw(
"SELECT DISTINCT "
+ Message.SUBJECT_FIELD
+ ", 1 AS _id FROM messages JOIN streams ON streams."
+ Stream.ID_FIELD + " = messages."
+ Message.STREAM_FIELD + " WHERE "
+ Message.SUBJECT_FIELD
+ " LIKE ? ESCAPE '\\' AND "
+ Stream.NAME_FIELD + " = ? ORDER BY "
+ Message.SUBJECT_FIELD + " COLLATE NOCASE",
DatabaseHelper.likeEscape(subject.toString()) + "%",
stream.toString()).closeableIterator().getRawResults();
return results.getRawCursor();
}
/**
* Creates a cursor to get the E-Mails stored in the database
* @param email Filter out emails containing this string
*/
private Cursor makePeopleCursor(CharSequence email) throws SQLException {
if (email == null) {
email = "";
}
String[] pieces = TextUtils.split(email.toString(), ",");
String piece;
if (pieces.length == 0) {
piece = "";
} else {
piece = pieces[pieces.length - 1].trim();
}
return ((AndroidDatabaseResults) app
.getDao(Person.class)
.queryRaw(
"SELECT rowid _id, * FROM people WHERE "
+ Person.ISBOT_FIELD + " = 0 AND "
+ Person.ISACTIVE_FIELD + " = 1 AND "
+ Person.EMAIL_FIELD
+ " LIKE ? ESCAPE '\\' ORDER BY "
+ Person.NAME_FIELD + " COLLATE NOCASE",
DatabaseHelper.likeEscape(piece) + "%")
.closeableIterator().getRawResults()).getRawCursor();
}
private void switchToStream() {
removeEditTextErrors();
if (!isCurrentModeStream()) {
switchView();
}
}
private void switchToPrivate() {
removeEditTextErrors();
if (isCurrentModeStream()) {
switchView();
}
}
private boolean isCurrentModeStream() {
//The TextView is VISIBLE which means currently send to stream is on.
return textView.getVisibility() == View.VISIBLE;
}
private void removeEditTextErrors() {
streamActv.setError(null);
topicActv.setError(null);
messageEt.setError(null);
}
/**
* Switch from Private to Stream or vice versa in chatBox
*/
private void switchView() {
if (isCurrentModeStream()) { //Person
togglePrivateStreamBtn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_action_bullhorn));
tempStreamSave = topicActv.getText().toString();
topicActv.setText(null);
topicActv.setHint(R.string.hint_person);
topicActv.setAdapter(emailActvAdapter);
streamActv.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
} else { //Stream
topicActv.setText(tempStreamSave);
togglePrivateStreamBtn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_action_person));
streamActv.setEnabled(true);
topicActv.setHint(R.string.hint_subject);
streamActv.setHint(R.string.hint_stream);
streamActv.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
topicActv.setVisibility(View.VISIBLE);
streamActv.setAdapter(streamActvAdapter);
topicActv.setAdapter(subjectActvAdapter);
}
}
private String tempStreamSave = null;
@Override
public void clearChatBox() {
if (messageEt != null) {
if (TextUtils.isEmpty(messageEt.getText())) {
topicActv.setText("");
streamActv.setText("");
}
}
}
public void onBackPressed() {
if (narrowedList != null) {
narrowedList = null;
getSupportFragmentManager().popBackStack(NARROW,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
private void pushListFragment(MessageListFragment list, String back) {
currentList = list;
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.list_fragment_container, list);
if (back != null) {
transaction.addToBackStack(back);
}
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
private void processParams() {
Bundle params = getIntent().getExtras();
if (params == null)
return;
for (String unprocessedParam : params.keySet()) {
Flag param;
if (unprocessedParam.contains(getBaseContext().getPackageName())) {
try {
param = Flag.valueOf(unprocessedParam
.substring(getBaseContext().getPackageName()
.length() + 1));
} catch (IllegalArgumentException e) {
Log.e(PARAMS, "Invalid app-specific intent specified.", e);
continue;
}
} else {
continue;
}
switch (param) {
case RESET_DATABASE:
Log.i(PARAMS, "Resetting the database...");
app.resetDatabase();
Log.i(PARAMS, "Database deleted successfully.");
this.finish();
break;
default:
break;
}
}
}
protected void narrow(final Stream stream) {
doNarrow(new NarrowFilterStream(stream, null));
}
private void narrow_pm_with(final Person person) {
doNarrow(new NarrowFilterPM(Arrays.asList(app.getYou(), person)));
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onListResume(MessageListFragment list) {
currentList = list;
NarrowFilter filter = list.filter;
if (filter == null) {
setupTitleBar(getString(R.string.app_name), null);
this.drawerToggle.setDrawerIndicatorEnabled(true);
} else {
setupTitleBar(filter.getTitle(), filter.getSubtitle());
this.drawerToggle.setDrawerIndicatorEnabled(false);
}
this.drawerLayout.closeDrawers();
}
private void setupTitleBar(String title, String subtitle) {
if (android.os.Build.VERSION.SDK_INT >= 11 && getSupportActionBar() != null) {
if (title != null) getSupportActionBar().setTitle(title);
getSupportActionBar().setSubtitle(subtitle);
}
}
/**
* This method creates a new Instance of the MessageListFragment and displays it with the filter.
*/
public void doNarrow(NarrowFilter filter) {
narrowedList = MessageListFragment.newInstance(filter);
// Push to the back stack if we are not already narrowed
pushListFragment(narrowedList, NARROW);
narrowedList.onReadyToDisplay(true);
}
@Override
public void onNarrowFillSendBoxPrivate(Person peopleList[], boolean openSoftKeyboard) {
displayChatBox(true);
displayFAB(false);
switchToPrivate();
ArrayList<String> names = new ArrayList<String>();
for (Person person : peopleList) {
if (person.getId() != app.getYou().getId()) {
names.add(person.getEmail());
}
}
topicActv.setText(TextUtils.join(", ", names));
messageEt.requestFocus();
if (openSoftKeyboard) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
}
/**
* Fills the chatBox according to the {@link MessageType}
* @param openSoftKeyboard If true open's up the SoftKeyboard else not.
*/
@Override
public void onNarrowFillSendBox(Message message, boolean openSoftKeyboard) {
displayChatBox(true);
displayFAB(false);
if (message.getType() == MessageType.PRIVATE_MESSAGE) {
switchToPrivate();
topicActv.setText(message.getReplyTo(app));
messageEt.requestFocus();
} else {
switchToStream();
streamActv.setText(message.getStream().getName());
topicActv.setText(message.getSubject());
if ("".equals(message.getSubject())) {
topicActv.requestFocus();
} else messageEt.requestFocus();
}
if (openSoftKeyboard) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
}
/**
* Fills the chatBox with the stream name and the topic
* @param stream Stream name to be filled
* @param subject Subject to be filled
* @param openSoftKeyboard If true open's the softKeyboard else not
*/
public void onNarrowFillSendBoxStream(String stream, String subject, boolean openSoftKeyboard) {
displayChatBox(true);
displayFAB(false);
switchToStream();
streamActv.setText(stream);
topicActv.setText(subject);
if ("".equals(subject)) {
topicActv.requestFocus();
} else messageEt.requestFocus();
if (openSoftKeyboard) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
}
public void onNarrow(NarrowFilter narrowFilter) {
// TODO: check if already narrowed to this particular stream/subject
doNarrow(narrowFilter);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Log.d("ASD", "onCreateOptionsMenu: ");
if (this.logged_in) {
getMenuInflater().inflate(R.menu.options, menu);
prepareSearchView(menu);
return true;
}
return false;
}
private boolean prepareSearchView(Menu menu) {
if (this.logged_in && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Get the SearchView and set the searchable configuration
final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// Assumes current activity is the searchable activity
final MenuItem mSearchMenuItem = menu.findItem(R.id.search);
final android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(mSearchMenuItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(getApplicationContext(), ZulipActivity.class)));
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(ContextCompat.getColor(this, R.color.colorTextPrimary));
searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
doNarrow(new NarrowFilterSearch(s));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mSearchMenuItem.collapseActionView();
}
return true;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (drawerToggle.onOptionsItemSelected(item)) {
// Close the right drawer if we opened the left one
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
getSupportFragmentManager().popBackStack(NARROW,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
break;
case R.id.search:
// show a pop up dialog only if gingerbread or under
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search Zulip");
final EditText editText = new EditText(this);
builder.setView(editText);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialogInterface, int i) {
String query = editText.getText().toString();
doNarrow(new NarrowFilterSearch(query));
}
});
builder.show();
}
break;
case R.id.daynight:
switch (AppCompatDelegate.getDefaultNightMode()) {
case -1:
case AppCompatDelegate.MODE_NIGHT_NO:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
default:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
}
break;
case R.id.refresh:
Log.w("menu", "Refreshed manually by user. We shouldn't need this.");
onRefresh();
break;
case R.id.today:
doNarrow(new NarrowFilterToday());
break;
case R.id.logout:
logout();
break;
case R.id.legal:
openLegal();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
/**
* Switches the current Day/Night mode to Night/Day mode
* @param nightMode which Mode {@link android.support.v7.app.AppCompatDelegate.NightMode}
*/
private void setNightMode(@AppCompatDelegate.NightMode int nightMode) {
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11) {
recreate();
}
}
/**
* Log the user out of the app, clearing our cache of their credentials.
*/
private void logout() {
this.logged_in = false;
notifications.logOut(new Runnable() {
public void run() {
app.logOut();
openLogin();
}
});
}
/**
* Switch to the login view.
*/
private void openLogin() {
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
}
private void openLegal() {
Intent i = new Intent(this, LegalActivity.class);
startActivityForResult(i, 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// our display has changed, lets recalculate the spacer
// this.size_bottom_spacer();
drawerToggle.onConfigurationChanged(newConfig);
}
protected void onPause() {
super.onPause();
Log.i("status", "suspend");
this.suspended = true;
unregisterReceiver(onGcmMessage);
if (event_poll != null) {
event_poll.abort();
event_poll = null;
}
if (statusUpdateHandler != null) {
statusUpdateHandler.removeMessages(0);
}
}
protected void onResume() {
super.onResume();
Log.i("status", "resume");
this.suspended = false;
// Set up the BroadcastReceiver to trap GCM messages so notifications
// don't show while in the app
IntentFilter filter = new IntentFilter(GcmBroadcastReceiver.getGCMReceiverAction(getApplicationContext()));
filter.setPriority(2);
registerReceiver(onGcmMessage, filter);
homeList.onActivityResume();
if (narrowedList != null) {
narrowedList.onActivityResume();
}
startRequests();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (statusUpdateHandler != null) {
statusUpdateHandler.removeMessages(0);
}
}
/**
* Refresh the current user profile, removes all the tables from the database and reloads them from the server, reset the queue.
*/
private void onRefresh() {
super.onResume();
if (event_poll != null) {
event_poll.abort();
event_poll = null;
}
app.clearConnectionState();
app.resetDatabase();
app.setEmail(app.getYou().getEmail());
startRequests();
}
private void startRequests() {
Log.i("zulip", "Starting requests");
if (event_poll != null) {
event_poll.abort();
event_poll = null;
}
event_poll = new AsyncGetEvents(this);
event_poll.start();
}
public void onReadyToDisplay(boolean registered) {
homeList.onReadyToDisplay(registered);
if (narrowedList != null) {
narrowedList.onReadyToDisplay(registered);
}
}
public void onNewMessages(Message[] messages) {
homeList.onNewMessages(messages);
if (narrowedList != null) {
narrowedList.onNewMessages(messages);
}
}
}
|
package com.xlythe.textmanager.text;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;
import com.xlythe.textmanager.Message;
import com.xlythe.textmanager.MessageCallback;
import com.xlythe.textmanager.MessageThread;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* An SMS conversation
*/
public class Thread implements MessageThread<Text>, Serializable {
long mThreadId;
int mCount;
int mUnreadCount;
Text mText;
protected Thread(Context context, Cursor cursor) {
mThreadId = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.Conversations.THREAD_ID));
mCount = 0;//cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Sms.Conversations.MESSAGE_COUNT));
mUnreadCount = 0;
buildLastMessage(context, mThreadId);
}
public void buildLastMessage(Context context, long threadId) {
ContentResolver contentResolver = context.getContentResolver();
final String[] projection = TextManager.PROJECTION;
final Uri uri = Uri.parse(Mock.Telephony.MmsSms.CONTENT_CONVERSATIONS_URI +"/"+ threadId);
final String order = "normalized_date ASC";
Cursor c = contentResolver.query(uri, projection, null, null, order);
if (c!=null && c.moveToFirst()) {
mText = new Text(context, c);
c.close();
}
}
@Override
public String getId(){
return Long.toString(mThreadId);
}
@Override
public int getCount() {
return 0;
}
@Override
public int getUnreadCount() {
return 0;
}
@Override
public Text getLatestMessage() {
return mText;
}
}
|
package de.eightbitboy.hijacr.data.comic;
//TODO use getters and stuff
/**
* Contains data for a comic whose page URLs can be counted easily.
*/
public class ComicData {
/**
* The comic's title.
*/
private String title;
/**
* The comic's website URL.
*/
private String url;
/**
* The URL to the first page of the comic.
*/
private String firstUrl;
private String baseUrl;
/**
* The number of the first comic. It is only used when baseUrl is given.
*/
private int firstNumber;
/**
* The jsoup query for getting the comic img element.
*/
private String imageQuery;
/**
* The jsoup query for getting the anchor with the href to the previous page.
*/
private String previousQuery;
/**
* The jsoup query for getting the anchor with the href to the next page.
*/
private String nextQuery;
private boolean simple = false;
/**
* Define "simple" a comic which uses an URL which ends with a
* number that can be counted and incremented for accessing comic pages.
*
* @param title
* @param url
* @param baseUrl
* @param firstNumber
* @param imageQuery
*/
public ComicData(String title, String url, String baseUrl, int firstNumber, String
imageQuery) {
this.title = title;
this.url = url;
this.baseUrl = baseUrl;
this.firstNumber = firstNumber;
this.imageQuery = imageQuery;
this.simple = true;
}
/**
* Define a comic. The URLs for accessing comic pages must be parsed from a page.
*
* @param title
* @param url
* @param firstUrl
* @param imageQuery
* @param previousQuery
* @param nextQuery
*/
public ComicData(String title, String url, String firstUrl, String imageQuery, String
previousQuery, String nextQuery) {
this.title = title;
this.url = url;
this.firstUrl = firstUrl;
this.imageQuery = imageQuery;
this.previousQuery = previousQuery;
this.nextQuery = nextQuery;
this.simple = false;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public String getFirstUrl() {
return firstUrl;
}
public String getBaseUrl() {
return baseUrl;
}
public int getFirstNumber() {
return firstNumber;
}
public String getImageQuery() {
return imageQuery;
}
public String getPreviousQuery() {
return previousQuery;
}
public String getNextQuery() {
return nextQuery;
}
public boolean isSimple() {
return simple;
}
//TODO improve cleanup
public String getCleanUrl() {
String cleanUrl;
cleanUrl = url.replaceAll("/", "");
cleanUrl = cleanUrl.replaceAll("http", "");
cleanUrl = cleanUrl.replaceAll(":", "");
cleanUrl = cleanUrl.replaceAll("www.", "");
return cleanUrl;
}
@Override
public boolean equals(Object o) {
return o instanceof ComicData && title.equals(((ComicData) o).getTitle());
}
}
|
package jp.gr.java_conf.nippy.kikisen;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import jp.gr.java_conf.nippy.kikisen.dialog.DirectionDialogFragment;
import jp.gr.java_conf.nippy.kikisen.dialog.DistanceDialogFragment;
import jp.gr.java_conf.nippy.kikisen.dialog.NumberDialogFragment;
import jp.gr.java_conf.nippy.kikisen.dialog.YesDialogFragment;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
TextView tvIP;
EditText etSendString;
Button btSend;
Button btNo;
Button btYes;
Button btEnemy;
Button btDirection;
Button btDistance;
Button btNumber;
Button btTimerStart;
Button btTimerEnd;
TextView tvTimer;
BouyomiChan4J bouyomi;
SharedPreferences pref;
final long circle_update[] = {2 * 60, 12 * 60, 17 * 60 + 40, 21 * 60 + 40, 24 * 60 + 40, 27 * 60 + 20, 29 * 60 + 20, 31 * 60 + 20};
final long circle_shrink_start[] = {0, 7 * 60, 15 * 60 + 20, 20 * 60 + 10, 23 * 60 + 40, 26 * 60 + 40, 28 * 60 + 50, 30 * 60 + 50};
final long total_time = circle_update[circle_update.length - 1];
final long err_time = 10;//(sec)
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
// Keep screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
tvIP = (TextView) findViewById(R.id.tvIP);
etSendString = (EditText) findViewById(R.id.etSendString);
btSend = (Button) findViewById(R.id.btSend);
btNo = (Button) findViewById(R.id.btNo);
btYes = (Button) findViewById(R.id.btYes);
btEnemy = (Button) findViewById(R.id.btEnemy);
btDirection = (Button) findViewById(R.id.btDirection);
btDistance = (Button) findViewById(R.id.btDistance);
btNumber = (Button) findViewById(R.id.btNumber);
btTimerStart = (Button) findViewById(R.id.btTimerStart);
btTimerEnd = (Button) findViewById(R.id.btTimerEnd);
tvTimer = (TextView) findViewById(R.id.tvTimer);
//preference
pref = PreferenceManager.getDefaultSharedPreferences(this);
tvTimer.setText("press start");
Log.v(TAG, "total time " + total_time);
// CountDownTimer(long millisInFuture, long countDownInterval)
// 3= 3x60x1000 = 180000 msec
final CountDown countDown = new CountDown(total_time * 1000, 100);
//SEND button
btSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
talk(etSendString.getText().toString());
etSendString.getEditableText().clear();
}
});
//enter pressed
etSendString.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && !(etSendString.getText().toString().equals(""))) {
talk(etSendString.getText().toString());
etSendString.getEditableText().clear();
return true;
}
return false;
}
});
//No button
btNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
talk("");
}
});
//Yes button
btYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
talk("");
}
});
//Yes button Long click
btYes.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
YesDialogFragment yesDialogFragment = new YesDialogFragment();
yesDialogFragment.show(getFragmentManager(), "yes");
return true;
}
});
//Enemy button
btEnemy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
talk("");
}
});
//Direction button
btDirection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//talk("");
//TODO enter direction
DirectionDialogFragment directionDialogFragment = new DirectionDialogFragment();
directionDialogFragment.show(getFragmentManager(), "yes");
}
});
//Distance button
btDistance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//talk("");
//TODO enter distance
DistanceDialogFragment distanceDialogFragment = new DistanceDialogFragment();
distanceDialogFragment.show(getFragmentManager(), "yes");
}
});
//Number button
btNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//talk("");
//TODO enter number
NumberDialogFragment numberDialogFragment = new NumberDialogFragment();
numberDialogFragment.show(getFragmentManager(), "yes");
}
});
// SKIP button
Button btSkip = (Button) findViewById(R.id.btSkip);
btSkip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
bouyomi.clear();
bouyomi.skip();
}
}).start();
}
});
btTimerStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
countDown.start();
talk_auto("");
}
});
btTimerEnd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
countDown.cancel();
tvTimer.setText("press start");
}
});
}
//send string to bouyomi-chan
private void talk(final String str) {
if (!(str.equals(""))) {
new Thread(new Runnable() {
public void run() {
bouyomi.talk(Integer.parseInt(pref.getString("list_preference_volume", "50")),
Integer.parseInt(pref.getString("list_preference_speed", "100")),
Integer.parseInt(pref.getString("list_preference_interval", "100")),
Integer.parseInt(pref.getString("list_preference_type", "0")),
pref.getString("edit_text_preference_command", " ") + str);
}
}).start();
}
}
//talk for timer
private void talk_auto(final String str) {
if (!(str.equals(""))) {
new Thread(new Runnable() {
public void run() {
bouyomi.talk(Integer.parseInt(pref.getString("list_preference_volume", "50")),
Integer.parseInt(pref.getString("list_preference_speed", "100")),
Integer.parseInt(pref.getString("list_preference_interval", "100")),
Integer.parseInt(pref.getString("list_preference_type_auto", "0")),
pref.getString("edit_text_preference_command_auto", "") + str);
}
}).start();
}
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tvTimer.setText("0:00.000");
}
long old_time = 0;
@Override
public void onTick(long millisUntilFinished) {
final long time_now = total_time * 1000 - millisUntilFinished - err_time * 1000;
if (pref.getBoolean("switch_preference_auto_start", false)) {
for (int i = 0; i < circle_shrink_start.length; i++) {
if (old_time < circle_shrink_start[i] * 1000 && circle_shrink_start[i] * 1000 < time_now) {
if (i != 0) talk_auto("" + (i) + " ");
}
}
}
if (pref.getBoolean("switch_preference_auto_5sec", false)) {
for (int i = 0; i < circle_shrink_start.length; i++) {
if (old_time < (circle_shrink_start[i] - 5) * 1000 && (circle_shrink_start[i] - 5) * 1000 < time_now) {
if (i != 0) talk_auto("5");
}
}
}
if (pref.getBoolean("switch_preference_auto_30sec", false)) {
for (int i = 0; i < circle_shrink_start.length; i++) {
if (old_time < (circle_shrink_start[i] - 30) * 1000 && (circle_shrink_start[i] - 30) * 1000 < time_now) {
if (i != 0) talk_auto("30");
}
}
}
if (pref.getBoolean("switch_preference_auto_60sec", false)) {
for (int i = 0; i < circle_shrink_start.length; i++) {
if (old_time < (circle_shrink_start[i] - 60) * 1000 && (circle_shrink_start[i] - 60) * 1000 < time_now) {
if (i != 0) talk_auto("" + (i) + " 1");
}
}
}
if (pref.getBoolean("switch_preference_auto_120sec", false)) {
for (int i = 0; i < circle_shrink_start.length; i++) {
if (old_time < (circle_shrink_start[i] - 120) * 1000 && (circle_shrink_start[i] - 120) * 1000 < time_now) {
if (i != 0) talk_auto("" + (i) + " 2");
}
}
}
if (pref.getBoolean("switch_preference_auto_circle_update", false)) {
for (int i = 0; i < circle_update.length; i++) {
if (old_time < circle_update[i] * 1000 && circle_update[i] * 1000 < time_now) {
if (i == 0) talk_auto("");
if (i != 0) talk_auto("");
}
}
}
old_time = time_now;
long mm = millisUntilFinished / 1000 / 60;
long ss = millisUntilFinished / 1000 % 60;
long ms = millisUntilFinished - ss * 1000 - mm * 1000 * 60;
//tvTimer.setText(String.format("%1$02d:%2$02d.%3$03d", mm, ss, ms));
tvTimer.setText(String.format(" " + (int) (time_now / 1000) + "sec"));
}
}
//menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.optionsMenu_01:
Intent intent1 = new android.content.Intent(this, MainPreferenceActivity.class);
startActivity(intent1);
return true;
case R.id.optionsMenu_02:
Intent intent2 = new android.content.Intent(this, HowToUseActivity.class);
startActivity(intent2);
return true;
case R.id.optionsMenu_03:
Intent intent3 = new android.content.Intent(this, AboutThisAppActivity.class);
startActivity(intent3);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onStart() {
Log.v(TAG, "onStart");
super.onStart();
}
@Override
public void onStop() {
Log.v(TAG, "onStop");
super.onStop();
bouyomi = null;
}
@Override
public void onResume() {
Log.v(TAG, "onResume");
super.onResume();
new Thread(new Runnable() {
public void run() {
bouyomi = new BouyomiChan4J(pref.getString("edit_text_preference_ip", "127.0.0.1"), Integer.parseInt(pref.getString("edit_text_preference_port", "50001")));
}
}).start();
/*tvIP.setText(" \nip:" + pref.getString("edit_text_preference_ip", "127.0.0.1") + "\nport:" + pref.getString("edit_text_preference_port", "50001")
+ "\nvolume:" + pref.getString("list_preference_volume", "50") + "\nspeed:" + pref.getString("list_preference_speed", "100")
+ "\ninterval:" + pref.getString("list_preference_interval", "100") + "\nvoice type:" + pref.getString("list_preference_type:", "0"));*/
tvIP.setText("ip:" + pref.getString("edit_text_preference_ip", "127.0.0.1") + " port:" + pref.getString("edit_text_preference_port", "50001"));
}
@Override
public void onPause() {
Log.v(TAG, "onPause");
super.onPause();
}
}
|
package com.worizon.junit.jsonrequest;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import com.worizon.jsonrpc.IDGenerator;
import com.worizon.jsonrpc.JsonRpcRequest;
import com.worizon.jsonrpc.gson.NonExpose;
public class JsonRpcRequestTest {
@Test
public void testId(){
IDGenerator.getInstance().reset();
for( long i=1; i < 10000; i++){
JsonRpcRequest req = new JsonRpcRequest("test");
assertTrue( req.getId().longValue() == i );
}
}
@Test
public void testConstructor1() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
JsonRpcRequest request = new JsonRpcRequest("test", params);
assertNotNull( request.getId() );
assertEquals( request.getVersion(), "2.0");
assertEquals( request.getMethod(), "test");
}
@Test
public void testConstructor2() {
JsonRpcRequest request = new JsonRpcRequest("test");
assertNotNull( request.getId() );
assertEquals( request.getVersion(), "2.0");
assertEquals( request.getMethod(), "test");
assertTrue(request.toString().startsWith("{\"method\":\"test\",\"jsonrpc\":\"2.0\","));
}
@Test
public void testConstructor3() {
JsonRpcRequest request1 = new JsonRpcRequest("test");
JsonRpcRequest request2 = new JsonRpcRequest( request1 );
assertTrue( request1.equals(request2) );
}
@Test
public void testEquals(){
JsonRpcRequest req1 = new JsonRpcRequest("test");
JsonRpcRequest req2 = new JsonRpcRequest("test");
assertFalse( req1.equals(req2) );
}
@Test
public void testParamsOrderToString(){
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("y", new int[]{3,4,5});
params.put("x", 1);
params.put("z", true);
JsonRpcRequest request = new JsonRpcRequest("test", params);
request.setId(1000L);
assertEquals(request.toString(), "{\"method\":\"test\",\"params\":{\"y\":[3,4,5],\"x\":1,\"z\":true},\"jsonrpc\":\"2.0\",\"id\":1000}");
}
class A{
int x;
String y;
public A( int x, String y){
this.x = x;
this.y = y;
}
}
@Test
public void testObjectToString(){
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", new A(5,"test"));
JsonRpcRequest request = new JsonRpcRequest("test",params);
request.setId(1000L);
assertEquals("{\"method\":\"test\",\"params\":{\"a\":{\"x\":5,\"y\":\"test\"}},\"jsonrpc\":\"2.0\",\"id\":1000}", request.toString());
}
class B{
int x;
@NonExpose String y;
public B( int x, String y){
this.x = x;
this.y = y;
}
@Override
public boolean equals( Object obj ){
return ((B)obj).x == x && ((B)obj).y.equals(y);
}
}
@Test
public void testObjectNonExposeFieldToString(){
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("b", new B(5,"test"));
JsonRpcRequest request = new JsonRpcRequest("test", params);
request.setId(1000L);
assertEquals("{\"method\":\"test\",\"params\":{\"b\":{\"x\":5}},\"jsonrpc\":\"2.0\",\"id\":1000}", request.toString());
}
@Test
public void testParseNumbers(){
JsonRpcRequest req = JsonRpcRequest.parse("{\"method\":\"test_numbers\",\"params\":{\"x\":5,\"y\":10.0},\"jsonrpc\":\"2.0\",\"id\":1000}");
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("x", 5.0);
params.put("y", 10.0);
JsonRpcRequest expected = new JsonRpcRequest("test_numbers", params);
expected.setId(1000L);
assertEquals(expected, req);
}
@Test
public void testParseStrings(){
JsonRpcRequest req = JsonRpcRequest.parse("{\"method\":\"test_strings\",\"params\":{\"x\":\"foo\",\"y\":\"bar\"},\"jsonrpc\":\"2.0\",\"id\":1000}");
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("x", "foo");
params.put("y", "bar");
JsonRpcRequest expected = new JsonRpcRequest("test_strings", params);
expected.setId(1000L);
assertEquals(expected, req);
}
@Test
public void testParseArray(){
JsonRpcRequest req = JsonRpcRequest.parse("{\"method\":\"test_array\",\"params\":{\"x\":[1,2,3]},\"jsonrpc\":\"2.0\",\"id\":1000}");
Map<String, Object> params = new LinkedHashMap<String, Object>();
ArrayList<Double> values = new ArrayList<Double>();
values.add(1.0d);
values.add(2.0d);
values.add(3.0d);
params.put("x", values);
JsonRpcRequest expected = new JsonRpcRequest("test_array", params);
expected.setId(1000L);
assertEquals(expected, req);
}
}
|
package mn.devfest.speakers;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.transition.Transition;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import butterknife.Bind;
import butterknife.ButterKnife;
import mn.devfest.R;
import mn.devfest.api.model.Speaker;
import mn.devfest.view.SpeakerView;
import timber.log.Timber;
import static mn.devfest.sessions.SessionsFragment.DEVFEST_2017_KEY;
import static mn.devfest.sessions.SessionsFragment.SPEAKERS_CHILD_KEY;
/**
* Fragment that displays details for a particular session
*
* @author bherbst
*/
public class SpeakerDetailsFragment extends Fragment {
private static final String ARG_SPEAKER_ID = "speakerId";
@Bind(R.id.speaker)
SpeakerView mSpeakerView;
private Speaker mSpeaker;
private DatabaseReference mFirebaseDatabaseReference;
public static SpeakerDetailsFragment newInstance(String speakerId) {
Bundle args = new Bundle();
args.putString(ARG_SPEAKER_ID, speakerId);
SpeakerDetailsFragment frag = new SpeakerDetailsFragment();
frag.setArguments(args);
return frag;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_speaker_details, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
Bundle args = getArguments();
if (args != null && args.containsKey(ARG_SPEAKER_ID)) {
String speakerId = args.getString(ARG_SPEAKER_ID);
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(SPEAKERS_CHILD_KEY)
.child(speakerId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Timber.d(dataSnapshot.toString());
mSpeaker = dataSnapshot.getValue(Speaker.class);
transitionSpeaker();
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.w(this.getClass().getSimpleName(), "Failed to read speaker value.", databaseError.toException());
}
});
} else {
throw new IllegalStateException("SpeakerDetailsFragment requires a speaker ID passed via newInstance()");
}
}
private void transitionSpeaker() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && addTransitionListener()) {
// If we are transitioning in, use the already loaded thumbnail
mSpeakerView.setSpeaker(mSpeaker, true);
} else {
// Otherwise do the normal Picasso loading of the full size image
mSpeakerView.setSpeaker(mSpeaker, false);
}
getActivity().setTitle(getResources().getString(R.string.speaker_title));
// Now the content exists, so we can start the transition
getActivity().supportStartPostponedEnterTransition();
}
private boolean addTransitionListener() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// Can't transition below lollipop
return false;
}
final Transition transition = getActivity().getWindow().getSharedElementEnterTransition();
if (transition != null) {
// There is an entering shared element transition so add a listener to it
transition.addListener(new Transition.TransitionListener() {
@Override
public void onTransitionEnd(Transition transition) {
// As the transition has ended, we can now load the full-size image
mSpeakerView.loadFullSizeImage(false);
// Make sure we remove ourselves as a listener
transition.removeListener(this);
}
@Override
public void onTransitionStart(Transition transition) {
// No-op
}
@Override
public void onTransitionCancel(Transition transition) {
// Make sure we remove ourselves as a listener
transition.removeListener(this);
}
@Override
public void onTransitionPause(Transition transition) {
// No-op
}
@Override
public void onTransitionResume(Transition transition) {
// No-op
}
});
return true;
}
// If we reach here then we have not added a listener
return false;
}
}
|
package com.lmy.lycommon.http;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import com.lmy.lycommon.utils.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
public class HttpUtil implements IHttpUtil {
public final static int EXECUTE_TYPE_GET = 0x00;
public final static int EXECUTE_TYPE_POST = 0x01;
public final static int TIME_OUT_DEFAULT = 10000;
public final static String CHARSET_DEFAULT = "utf-8";
public final static String BOUNDARY = UUID.randomUUID().toString();
public final static String PREFIX = "--", LINE_END = "\r\n";
public final static String CONTENT_TYPE = "multipart/form-data";
private int timeOut;
private String charset;
public static HttpUtil create() {
return new HttpUtil();
}
public static HttpUtil create(int timeOut, String charset) {
return new HttpUtil(timeOut, charset);
}
private HttpUtil() {
this(TIME_OUT_DEFAULT, CHARSET_DEFAULT);
}
private HttpUtil(int timeOut, String charset) {
this.timeOut = timeOut;
this.charset = charset;
}
@Override
public void execute(@NonNull HttpTask task) {
new AsyncHttpTask(task).execute();
}
private class AsyncHttpTask extends AsyncTask<HttpTask, Integer, String[]> {
private HttpTask task;
public AsyncHttpTask(HttpTask task) {
this.task = task;
}
public void progress(int progress) {
publishProgress(progress);
}
@Override
protected String[] doInBackground(HttpTask... params) {
checkType(task.getType());
try {
switch (task.getType()) {
case EXECUTE_TYPE_GET:
return doGet(this, task);
case EXECUTE_TYPE_POST:
return doPost(this, task);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
if (result == null) task.getHttpExecuteLinstener().onError(-1, "unknown error!");
else if (result.length >= 2)
task.getHttpExecuteLinstener().onError(Integer.parseInt(result[0]), result[1]);
else task.getHttpExecuteLinstener().onSuccess(result[0]);
}
@Override
protected void onProgressUpdate(Integer... values) {
task.getHttpExecuteLinstener().onProgress(values[0]);
}
}
private void checkType(int type) {
if (type > EXECUTE_TYPE_POST || type < EXECUTE_TYPE_GET)
throw new RuntimeException("This type(" + type + ") of request is not supported!");
}
private String[] doGet(AsyncHttpTask asyncTask, HttpTask task) throws IOException {
asyncTask.progress(0);
HttpURLConnection connection = initConnection(task.getURL(), EXECUTE_TYPE_POST);
setCookies(connection);
/**
* 200=
*/
int code = connection.getResponseCode();
String[] result = new String[]{""};
if (code == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
result[0] += lines;
}
} else {
result = new String[]{"", ""};
result[0] = String.valueOf(code);
result[1] = "Error!";
}
connection.disconnect();
asyncTask.progress(100);
return result;
}
private String[] doPost(AsyncHttpTask asyncTask, HttpTask task) throws IOException {
asyncTask.progress(0);
HttpURLConnection connection = initConnection(task.getURL(), EXECUTE_TYPE_POST);
setCookies(connection);
OutputStream os = connection.getOutputStream();
StringBuffer sb = parseParams(task.getParams());
byte[] paramsByteArray = sb.toString().getBytes();
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
os.write(paramsByteArray);
os.write(end_data);
os.write(LINE_END.getBytes());
os.flush();
os.close();
/**
* 200=
*/
int code = connection.getResponseCode();
String[] result = new String[]{""};
if (code == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines = "";
while ((lines = reader.readLine()) != null) {
result[0] += lines;
}
} else {
result = new String[]{"", ""};
result[0] = String.valueOf(code);
result[1] = "Error!";
}
connection.disconnect();
asyncTask.progress(100);
return result;
}
private StringBuffer parseParams(Map<String, String> map) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINE_END);
sb.append("Content-Type: text/plain; charset=" + charset + LINE_END);
sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
sb.append(LINE_END);
sb.append(entry.getValue());
sb.append(LINE_END);
}
return sb;
}
private void setCookies(HttpURLConnection connection) {
}
@Override
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
@Override
public int setTimeOut() {
return timeOut;
}
@Override
public void setCharset(String charset) {
this.charset = charset;
}
@Override
public String getCharset() {
return charset;
}
private HttpURLConnection initConnection(String url, int type) throws IOException {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(timeOut);
conn.setConnectTimeout(timeOut);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
if (type == EXECUTE_TYPE_GET)
conn.setRequestMethod("GET");
else if (type == EXECUTE_TYPE_POST)
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", charset);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
return conn;
}
}
|
package org.openlmis.core.exceptions;
import com.crashlytics.android.Crashlytics;
public class LMISException extends Exception {
public LMISException(String msg) {
super(msg);
}
public LMISException(Exception e) {
super(e);
}
public void reportToFabric() {
//this will save exception messages locally
//it only uploads to fabric server when network is available
//so this actually behaves analogously with our sync logic
Crashlytics.logException(this);
}
}
|
package com.malhartech.lib.math;
import com.malhartech.annotation.InputPortFieldAnnotation;
import com.malhartech.annotation.OutputPortFieldAnnotation;
import com.malhartech.api.BaseOperator;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.*;
/**
*
* @author David Yan <[email protected]>
*/
public class Script extends BaseOperator
{
protected transient ScriptEngineManager sem = new ScriptEngineManager();
protected transient ScriptEngine engine = sem.getEngineByName("JavaScript");
protected String script;
protected boolean keepContext = true;
protected boolean isPassThru = true;
protected transient SimpleScriptContext scriptContext = new SimpleScriptContext();
protected SimpleBindings scriptBindings = new SimpleBindings();
protected ArrayList<String> prerunScripts = new ArrayList<String>();
protected Object evalResult;
@InputPortFieldAnnotation(name = "inBindings", optional = true)
public final transient DefaultInputPort<Map<String, Object>> inBindings = new DefaultInputPort<Map<String, Object>>(this)
{
@Override
public void process(Map<String, Object> tuple)
{
for (Map.Entry<String, Object> entry: tuple.entrySet()) {
engine.put(entry.getKey(), entry.getValue());
}
Object res;
try {
evalResult = engine.eval(script, scriptContext);
if (isPassThru) {
result.emit(evalResult);
}
}
catch (ScriptException ex) {
Logger.getLogger(Script.class.getName()).log(Level.SEVERE, null, ex);
}
if (isPassThru) {
outBindings.emit(new HashMap<String, Object>(engine.getBindings(ScriptContext.ENGINE_SCOPE)));
}
}
};
@OutputPortFieldAnnotation(name = "outBindings", optional = true)
public final transient DefaultOutputPort<Map<String, Object>> outBindings = new DefaultOutputPort<Map<String, Object>>(this);
@OutputPortFieldAnnotation(name = "result", optional = true)
public final transient DefaultOutputPort<Object> result = new DefaultOutputPort<Object>(this);
public void setEngineByName(String name)
{
engine = sem.getEngineByName(name);
}
public void setKeepContext(boolean keepContext)
{
this.keepContext = keepContext;
}
public void setScript(String script)
{
this.script = script;
}
public void addPrerunScript(String script) throws ScriptException
{
prerunScripts.add(script);
}
public void setPassThru(boolean isPassThru)
{
this.isPassThru = isPassThru;
}
@Override
public void endWindow()
{
if (!isPassThru) {
result.emit(evalResult);
outBindings.emit(new HashMap<String, Object>(this.scriptContext.getBindings(ScriptContext.ENGINE_SCOPE)));
}
if (!keepContext) {
this.scriptContext = new SimpleScriptContext();
engine.setContext(this.scriptContext);
}
}
@Override
public void setup(OperatorContext context)
{
this.scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
engine.setContext(this.scriptContext);
try {
for (String s: prerunScripts) {
engine.eval(s, this.scriptContext);
}
}
catch (ScriptException ex) {
Logger.getLogger(Script.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void put(String key, Object val)
{
scriptBindings.put(key, val);
}
}
|
package org.y20k.transistor.helpers;
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import org.y20k.transistor.MainActivity;
import org.y20k.transistor.R;
import org.y20k.transistor.core.Station;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
/**
* StationFetcher class
*/
public final class StationFetcher extends AsyncTask<Void, Void, Bundle> implements TransistorKeys {
/* Define log tag */
private static final String LOG_TAG = StationFetcher.class.getSimpleName();
/* Main class variables */
private final Activity mActivity;
private final File mFolder;
private final Uri mStationUri;
private final String mStationName;
private final String mStationUriScheme;
private URL mStationURL;
private final boolean mFolderExists;
/* Constructor */
public StationFetcher(Activity activity, File folder, Uri stationUri, String stationName) {
mActivity = activity;
mFolder = folder;
mStationUri = stationUri;
mStationName =stationName; // optional station name // todo set station name, if given in postexecute
mFolderExists = mFolder.exists();
mStationUriScheme = stationUri.getScheme();
if (stationUri != null && mStationUriScheme != null && mStationUriScheme.startsWith("http")) {
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_add_download_started), Toast.LENGTH_LONG).show();
} else if (stationUri != null && mStationUriScheme != null && mStationUriScheme.startsWith("file")) {
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_add_open_file_started), Toast.LENGTH_LONG).show();
}
}
/* Background thread: download station */
@Override
public Bundle doInBackground(Void... params) {
Bundle stationDownloadBundle = new Bundle();
Station station = null;
Bitmap stationImage = null;
if (mFolderExists && mStationUriScheme != null && mStationUriScheme.startsWith("http") && urlCleanup()) {
// download new station,
station = new Station(mFolder, mStationURL);
// check if multiple streams
if (station.getStationFetchResults().getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM) {
// check if name parameter was given
if (mStationName != null) {
station.setStationName(mStationName);
}
// download new station image
stationImage = station.fetchImageFile(mStationURL);
// pack bundle
stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION, station);
stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION_IMAGE, stationImage);
}
return stationDownloadBundle;
} else if (mFolderExists && mStationUriScheme != null && mStationUriScheme.startsWith("file")) {
// read file and return new station
station = new Station(mFolder, mStationUri);
// check if multiple streams
if (station.getStationFetchResults().getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM) {
// pack bundle
stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION, station);
}
return stationDownloadBundle;
} else {
return stationDownloadBundle;
}
}
/* Main thread: set station and activate listener */
@Override
protected void onPostExecute(Bundle stationDownloadBundle) {
// get station from download bundle
Station station = null;
if (stationDownloadBundle.containsKey(KEY_DOWNLOAD_STATION)) {
station = stationDownloadBundle.getParcelable(KEY_DOWNLOAD_STATION);
}
// get fetch results from station
Bundle fetchResults = null;
if (station != null) {
fetchResults = station.getStationFetchResults();
}
// CASE 1: station was successfully fetched
if (station != null && fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM && mFolderExists) {
// hand over result to MainActivity
((MainActivity)mActivity).handleStationAdd(stationDownloadBundle);
LogHelper.v(LOG_TAG, "Station was successfully fetched: " + station.getStreamUri().toString());
}
// CASE 2: multiple streams found
if (station != null && fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_MULTIPLE_STREAMS && mFolderExists) {
// let user choose
DialogAddChooseStream.show(mActivity, fetchResults.getStringArrayList(RESULT_LIST_OF_URIS), fetchResults.getStringArrayList(RESULT_LIST_OF_NAMES));
}
// CASE 3: an error occurred
if (station == null || (fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_NO_STREAM) || !mFolderExists) {
String errorTitle;
String errorMessage;
String errorDetails;
if (mStationUriScheme != null && mStationUriScheme.startsWith("http")) {
// construct error message for "http"
errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_download);
errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_download);
errorDetails = buildDownloadErrorDetails(fetchResults);
} else if (mStationUriScheme != null && mStationUriScheme.startsWith("file")) {
// construct error message for "file"
errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_read);
errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_read);
errorDetails = buildReadErrorDetails(fetchResults);
} else if (!mFolderExists) {
// construct error message for write error
errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_write);
errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_write);
errorDetails = mActivity.getResources().getString(R.string.dialog_error_details_write);
} else {
// default values
errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_default);
errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_default);
errorDetails = mActivity.getResources().getString(R.string.dialog_error_details_default);
}
// show error dialog
DialogError.show(mActivity, errorTitle, errorMessage, errorDetails);
}
}
/* checks and cleans url string and sets mStationURL */
private boolean urlCleanup() {
// remove whitespaces and create url
try {
mStationURL = new URL(mStationUri.toString().trim());
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
}
}
/* Builds more detailed download error string */
private String buildDownloadErrorDetails(Bundle fetchResults) {
String fileContent = fetchResults.getString(RESULT_FILE_CONTENT);
String playListType;
String streamType;
if (fetchResults.containsKey(RESULT_PLAYLIST_TYPE) && fetchResults.getParcelable(RESULT_PLAYLIST_TYPE) != null) {
playListType = fetchResults.getParcelable(RESULT_PLAYLIST_TYPE).toString();
} else {
playListType = "unknown";
}
if (fetchResults.containsKey(RESULT_STREAM_TYPE) && fetchResults.getParcelable(RESULT_STREAM_TYPE) != null) {
streamType = fetchResults.getParcelable(RESULT_STREAM_TYPE).toString();
} else {
streamType = "unknown";
}
// construct details string
StringBuilder sb = new StringBuilder("");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_external_storage));
sb.append("\n");
sb.append(mFolder);
sb.append("\n\n");
if (mStationUri.getScheme().startsWith("file")) {
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_read_file_location));
} else {
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_download_station_url));
}
sb.append("\n");
sb.append(mStationUri);
if ((mStationUri.getLastPathSegment() != null && !mStationUri.getLastPathSegment().contains("m3u")) ||
(mStationUri.getLastPathSegment() != null && !mStationUri.getLastPathSegment().contains("pls")) ) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_hint_m3u));
}
if (playListType != null) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_playlist_type));
sb.append("\n");
sb.append(playListType);
}
if (streamType != null) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_stream_type));
sb.append("\n");
sb.append(streamType);
}
if (fileContent != null) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_file_content));
sb.append("\n");
sb.append(fileContent);
}
return sb.toString();
}
/* Builds more detailed read error string */
private String buildReadErrorDetails(Bundle fetchResults) {
// construct details string
StringBuilder sb = new StringBuilder("");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_external_storage));
sb.append("\n");
sb.append(mFolder);
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_read));
sb.append("\n");
sb.append(mStationUri);
if (!mStationUri.getLastPathSegment().contains("m3u") || !mStationUri.getLastPathSegment().contains("pls") ) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_hint_m3u));
}
if (fetchResults != null && fetchResults.getBoolean(RESULT_FETCH_STATUS)) {
String fileContent = fetchResults.getString(RESULT_FILE_CONTENT);
if (fileContent != null) {
sb.append("\n\n");
sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_file_content));
sb.append("\n");
sb.append(fileContent);
} else {
LogHelper.v(LOG_TAG, "no content in local file");
}
}
return sb.toString();
}
}
|
package sg.rc4.collegelaundry;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.joda.time.DateTime;
import org.joda.time.Period;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import sg.rc4.collegelaundry.utility.Vibrator;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
private final int DEFAULT_NOTIFICATION_ID = 4021495;
@Bind(R.id.timerDisplay)
TextView timerDisplay;
Timer displayUpdateTimer;
DateTime dtLaundryDone;
boolean hasDoneAlerted = false;
SharedPreferences pref;
private int timerSeconds = 2100;
private int notificationId = DEFAULT_NOTIFICATION_ID;
public MainActivityFragment() {
}
@Override
public void setArguments(Bundle arguments){
if (arguments != null) {
if (arguments.containsKey("timer")) {
timerSeconds = arguments.getInt("timer");
}
if (arguments.containsKey("notificationId")) {
notificationId = arguments.getInt("notificationId");
}
}
}
public void alert(){
Vibrator v = new Vibrator(getContext());
v.vibrate(2000);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.drawable.ic_stat_college_laundry_notification_icon)
.setContentTitle("Your laundry is done!")
.setContentText("College Laundry");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(getActivity(), MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getActivity());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(notificationId, mBuilder.build());
}
protected Context getContext() {
return getActivity().getApplicationContext();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onResume() {
Log.i("DEBUG", "MainActivityFragment::onResume");
super.onResume();
pref = getActivity().getSharedPreferences(getString(R.string.app_name), 0);
String laundryDoneString = pref.getString(getString(R.string.dtLaundryDoneKey) + notificationId, null);
Log.i("DEBUG", "MainActivityFragment::onResume - " + laundryDoneString + " NOTIF: " + notificationId);
if (laundryDoneString != null) {
dtLaundryDone = new DateTime(laundryDoneString);
pref.edit().remove(getString(R.string.dtLaundryDoneKey) + notificationId).commit();
}
}
@Override
public void onPause() {
super.onPause();
Log.i("DEBUG", "MainActivityFragment::onPause" + " NOTIF: " + notificationId);
SharedPreferences.Editor editor = pref.edit();
if (dtLaundryDone != null) {
editor.putString(getString(R.string.dtLaundryDoneKey) + notificationId, dtLaundryDone.toString());
}
editor.apply();
}
public void onStart() {
super.onStart();
displayUpdateTimer = new Timer();
displayUpdateTimer.schedule(new TimerTask() {
@Override
public void run() {
Activity activity = getActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (dtLaundryDone == null) {
timerDisplay.setText(R.string.timerDisplay);
} else {
Period diff = new Period(new DateTime(), dtLaundryDone);
int totalSeconds = diff.toStandardSeconds().getSeconds();
if (totalSeconds < 0) {
if (!hasDoneAlerted) {
alert();
hasDoneAlerted = true;
}
// the laundry has been done!!!
if (totalSeconds > -20) {
timerDisplay.setText("Laundry is done!");
} else {
// the laundry has been done!!!
timerDisplay.setText("Done for " + DateUtils.formatElapsedTime(-1 * totalSeconds));
}
} else {
timerDisplay.setText(DateUtils.formatElapsedTime(totalSeconds));
}
}
}
});
}
}, 200, 200);
}
@OnClick(R.id.timerDisplay)
void timerDisplayTap(View v) {
AlarmManager alarm = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE);
Intent intent = new Intent(getContext(), OnAlarmReceive.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (dtLaundryDone == null) {
hasDoneAlerted = false;
dtLaundryDone = (new DateTime()).plusSeconds(timerSeconds);
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ timerSeconds * 1000, pendingIntent);
} else {
// remove the notification
NotificationManager mNotificationManager =
(NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
dtLaundryDone = null;
// cancel the alarm
alarm.cancel(pendingIntent);
}
}
}
|
package cn.sevensencond.petmonitor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DevicePageActivity extends Activity {
private TextView mSpotName = null;
private TextView mSpotNumber = null;
private TextView mLastLocationTime = null;
private TextView mLastLocationStatus = null;
private TextView mLastLocationAddress = null;
private TextView mSpotPhoneNumber = null;
private TextView mSpotpageDownarrow = null;
private TextView mSpotpageUparrow = null;
private ListView mOperationList = null;
private LinearLayout mLocationInfo = null;
private LinearLayout mWaitingLinear = null;
private ImageView mHeadImage = null;
private ImageView mSettingImage = null;
private ImageView mBatteryImage = null;
private Button mButtonShare = null;
private List<Map<String, Object>> getData()
{
ArrayList localArrayList = new ArrayList();
HashMap localHashMap1 = new HashMap();
localHashMap1.put("operationImg", Integer.valueOf(R.drawable.listitem_trackobject));
localHashMap1.put("operationTitle", getString(R.string.location_label));
localHashMap1.put("operationDesc", getString(R.string.locationdesc_label));
localHashMap1.put("operationTips", "");
localArrayList.add(localHashMap1);
HashMap localHashMap2 = new HashMap();
localHashMap2.put("operationImg", Integer.valueOf(R.drawable.listitem_history));
localHashMap2.put("operationTitle", getString(R.string.history));
localHashMap2.put("operationDesc", getString(R.string.history_desc));
localHashMap2.put("operationTips", "");
localArrayList.add(localHashMap2);
HashMap localHashMap3 = new HashMap();
localHashMap3.put("operationImg", Integer.valueOf(R.drawable.listitem_fence));
localHashMap3.put("operationTitle", getString(R.string.fence));
localHashMap3.put("operationDesc", getString(R.string.fence_desc));
localHashMap3.put("operationTips", getString(R.string.fencein));
localArrayList.add(localHashMap3);
HashMap localHashMap9 = new HashMap();
localHashMap9.put("operationImg", Integer.valueOf(R.drawable.listitem_tracking));
localHashMap9.put("operationTitle", getString(R.string.following));
localHashMap9.put("operationDesc", getString(R.string.follow_desc));
localHashMap9.put("operationTips", "");
localArrayList.add(localHashMap9);
HashMap localHashMap7 = new HashMap();
localHashMap7.put("operationImg", Integer.valueOf(R.drawable.listitem_trackormode));
localHashMap7.put("operationTitle", getString(R.string.trackormode));
localHashMap7.put("operationDesc", getString(R.string.trackormode_desc));
localHashMap7.put("operationTips", "");
localArrayList.add(localHashMap7);
HashMap localHashMap8 = new HashMap();
localHashMap8.put("operationImg", Integer.valueOf(R.drawable.listitem_sos));
localHashMap8.put("operationTitle", getString(R.string.trackorsos));
localHashMap8.put("operationDesc", getString(R.string.sossetting));
localHashMap8.put("operationTips", "");
localArrayList.add(localHashMap8);
HashMap localHashMap4 = new HashMap();
localHashMap4.put("operationImg", Integer.valueOf(R.drawable.listitem_gps));
localHashMap4.put("operationTitle", getString(R.string.gps_status));
localHashMap4.put("operationDesc", getString(R.string.gps_status_desc));
localHashMap4.put("operationTips", getString(R.string.gps_enable));
localArrayList.add(localHashMap4);
// HashMap localHashMap5 = new HashMap();
// localHashMap5.put("operationImg", Integer.valueOf(R.drawable.listitem_deletetrackor));
// localHashMap5.put("operationTitle", getString(R.string.cancel_share));
// localHashMap5.put("operationDesc", getString(R.string.cancel_share_desc));
// localHashMap5.put("operationTips", "");
// localArrayList.add(localHashMap5);
HashMap localHashMap6 = new HashMap();
localHashMap6.put("operationImg", Integer.valueOf(R.drawable.listitem_deletetrackor));
localHashMap6.put("operationTitle", getString(R.string.delete_label));
localHashMap6.put("operationDesc", getString(R.string.deletedesc_label));
localHashMap6.put("operationTips", "");
localArrayList.add(localHashMap6);
return localArrayList;
}
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.spotpage_text_name)
{
Log.d("Device", "start device setting");
Intent localIntent3 = new Intent(DevicePageActivity.this, DeviceSettingActivity.class);
// localIntent3.putExtra("com.bigbangtech.whereru.clip", true);
// localIntent3.putExtra("com.bigbangtech.whereru.trackerserial", SpotPage.this.curTracker.serialNumber);
startActivity(localIntent3);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DevicePage", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.devicepage);
this.mSpotName = ((TextView)findViewById(R.id.spotpage_text_name));
this.mSpotName.setOnClickListener(this.clickListener);
this.mSpotNumber = ((TextView)findViewById(R.id.spotpage_text_number));
this.mLastLocationTime = ((TextView)findViewById(R.id.last_location_time));
this.mLastLocationStatus = ((TextView)findViewById(R.id.last_location_status));
this.mLastLocationAddress = ((TextView)findViewById(R.id.last_location_address));
this.mSpotPhoneNumber = ((TextView)findViewById(R.id.spotpage_phone_number));
this.mSpotpageDownarrow = ((TextView)findViewById(R.id.spotpage_downarrow));
this.mSpotpageUparrow = ((TextView)findViewById(R.id.spotpage_uparrow));
this.mOperationList = ((ListView)findViewById(R.id.spotpage_listview_operation));
this.mLocationInfo = ((LinearLayout)findViewById(R.id.devicepage_linear_locationInfo));
this.mWaitingLinear = ((LinearLayout)findViewById(R.id.devicepage_linear_getLocation));
this.mHeadImage = ((ImageView)findViewById(R.id.spotpage_image_head));
this.mSettingImage = ((ImageView)findViewById(R.id.spotpage_personal_setting));
// this.mHeadImage.setOnClickListener(this.clickListener);
// this.mSettingImage.setOnClickListener(this.clickListener);
this.mBatteryImage = ((ImageView)findViewById(R.id.spotpage_image_battery));
this.mButtonShare = ((Button)findViewById(R.id.spotpage_share));
// this.mButtonShare.setOnClickListener(this.clickListener);
Bundle localBundle = getIntent().getBundleExtra("cn.sevensencond.petmonitor.devicePage");
String deviceName = localBundle.getString("cn.sevensencond.petmonitor.devicename");
mSpotName.setText(deviceName);
mLocationInfo.setVisibility(View.VISIBLE);
mWaitingLinear.setVisibility(View.GONE);
// stub text first
// mSpotName.setText("075");
mSpotPhoneNumber.setText("18800000000");
mSpotNumber.setText("18600000000");
mLastLocationTime.setText("2012-12-21 00:00:00");
mLastLocationStatus.setText("");
mLastLocationAddress.setText("");
List localList = getData();
int i = R.layout.operationlistitem;
String[] arrayOfString = { "operationImg", "operationTitle", "operationDesc", "operationTips" };
int[] arrayOfInt = new int[4];
arrayOfInt[0] = R.id.operationlisteitem_img_icon;
arrayOfInt[1] = R.id.operationlisteitem_text_title;
arrayOfInt[2] = R.id.operationlisteitem_text_info;
arrayOfInt[3] = R.id.operationlisteitem_text_tip;
SimpleAdapter localSimpleAdapter = new SimpleAdapter(this, localList, i, arrayOfString, arrayOfInt);
this.mOperationList.setAdapter(localSimpleAdapter);
}
}
|
package uk.ac.soton.ecs.comp3005.l3;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.ColourSpace;
import org.openimaj.image.colour.RGBColour;
import org.openimaj.image.renderer.RenderHints;
import org.openimaj.math.geometry.point.Point2dImpl;
import org.openimaj.math.geometry.shape.Ellipse;
import org.openimaj.math.geometry.shape.EllipseUtilities;
import org.openimaj.math.geometry.transforms.TransformUtilities;
import org.openimaj.math.statistics.distribution.CachingMultivariateGaussian;
import uk.ac.soton.ecs.comp3005.utils.Utils;
import uk.ac.soton.ecs.comp3005.utils.annotations.Demonstration;
import Jama.Matrix;
/**
* Demonstration of 2D covariance
*
* @author Jonathon Hare ([email protected])
*/
@Demonstration(title = "2D Covariance Matrix Demo")
public class CovarianceDemo implements Slide {
protected static final Font FONT = Font.decode("Monaco-48");
protected Matrix covariance;
protected BufferedImage bimg;
protected MBFImage image;
protected ImageComponent imageComp;
protected JSlider xxSlider;
protected JSlider yySlider;
protected JSlider xySlider;
protected JTextField xxField;
protected JTextField xyField;
protected JTextField yxField;
protected JTextField yyField;
protected boolean drawData = true;
protected boolean drawEllipse = false;
@Override
public Component getComponent(int width, int height) throws IOException {
covariance = Matrix.identity(2, 2);
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height));
base.setLayout(new GridBagLayout());
image = new MBFImage(400, 400, ColourSpace.RGB);
imageComp = new DisplayUtilities.ImageComponent(true, false);
imageComp.setShowPixelColours(false);
imageComp.setShowXYPosition(false);
imageComp.setAllowZoom(false);
imageComp.setAllowPanning(false);
base.add(imageComp);
final JPanel sep = new JPanel();
sep.setOpaque(false);
sep.setPreferredSize(new Dimension(80, 450));
base.add(sep);
xxSlider = new JSlider();
yySlider = new JSlider();
xySlider = new JSlider();
xySlider.setMinimum(-100);
xySlider.setMaximum(100);
xxSlider.setValue(100);
xySlider.setValue(0);
yySlider.setValue(100);
xxSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setXX();
}
});
yySlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setYY();
}
});
xySlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setXY();
}
});
final GridBagConstraints c = new GridBagConstraints();
final JPanel matrix = new JPanel(new GridBagLayout());
c.gridwidth = 1;
c.gridheight = 1;
c.gridy = 0;
c.gridx = 0;
matrix.add(xxField = new JTextField(5), c);
xxField.setFont(FONT);
xxField.setEditable(false);
c.gridx = 1;
matrix.add(xyField = new JTextField(5), c);
xyField.setFont(FONT);
xyField.setEditable(false);
c.gridy = 1;
c.gridx = 0;
matrix.add(yxField = new JTextField(5), c);
yxField.setFont(FONT);
yxField.setEditable(false);
c.gridx = 1;
matrix.add(yyField = new JTextField(5), c);
yyField.setFont(FONT);
yyField.setEditable(false);
final JPanel controls = new JPanel(new GridBagLayout());
controls.setOpaque(false);
c.gridwidth = 2;
c.gridheight = 1;
c.gridy = 0;
c.gridx = 0;
controls.add(matrix, c);
c.gridwidth = 2;
c.gridy = 2;
c.gridx = 0;
controls.add(new JSeparator(), c);
c.gridy = 3;
c.gridx = 0;
controls.add(new JSeparator(), c);
c.gridwidth = 1;
c.gridy = 4;
c.gridx = 0;
final JLabel xxLabel = new JLabel("XX:");
xxLabel.setFont(FONT);
controls.add(xxLabel, c);
c.gridx = 1;
controls.add(xxSlider, c);
c.gridy = 5;
c.gridx = 0;
final JLabel yyLabel = new JLabel("YY:");
yyLabel.setFont(FONT);
controls.add(yyLabel, c);
c.gridx = 1;
controls.add(yySlider, c);
c.gridy = 6;
c.gridx = 0;
final JLabel xyLabel = new JLabel("XY:");
xyLabel.setFont(FONT);
xyLabel.setHorizontalAlignment(JLabel.RIGHT);
controls.add(xyLabel, c);
c.gridx = 1;
controls.add(xySlider, c);
c.gridwidth = 2;
c.gridy = 7;
c.gridx = 0;
controls.add(new JSeparator(), c);
c.gridy = 5;
c.gridx = 0;
controls.add(new JSeparator(), c);
c.gridwidth = 1;
c.gridy = 8;
c.gridx = 0;
controls.add(new JLabel("Show data points:"), c);
c.gridx = 1;
final JCheckBox checkBox = new JCheckBox();
checkBox.setSelected(drawData);
checkBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
drawData = ((JCheckBox) e.getSource()).isSelected();
updateImage();
}
});
controls.add(checkBox, c);
c.gridwidth = 1;
c.gridy = 9;
c.gridx = 0;
controls.add(new JLabel("Show ellipse:"), c);
c.gridx = 1;
final JCheckBox checkBox2 = new JCheckBox();
checkBox2.setSelected(drawEllipse);
checkBox2.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
drawEllipse = ((JCheckBox) e.getSource()).isSelected();
updateImage();
}
});
controls.add(checkBox2, c);
base.add(controls);
updateImage();
return base;
}
protected void updateImage() {
xxField.setText(String.format("%2.2f", covariance.get(0, 0)));
xyField.setText(String.format("%2.2f", covariance.get(0, 1)));
yxField.setText(String.format("%2.2f", covariance.get(1, 0)));
yyField.setText(String.format("%2.2f", covariance.get(1, 1)));
image.fill(RGBColour.WHITE);
image.drawLine(image.getWidth() / 2, 0, image.getWidth() / 2, image.getHeight(), 3, RGBColour.BLACK);
image.drawLine(0, image.getHeight() / 2, image.getWidth(), image.getHeight() / 2, 3, RGBColour.BLACK);
Ellipse e = EllipseUtilities.ellipseFromCovariance(image.getWidth() / 2, image.getHeight() / 2, covariance,
100);
e = e.transformAffine(TransformUtilities.scaleMatrixAboutPoint(1, -1, image.getWidth() / 2, image.getHeight() / 2));
if (!Double.isNaN(e.getMajor()) && !Double.isNaN(e.getMinor()) && covariance.rank() == 2) {
final Matrix mean = new Matrix(new double[][] { { image.getWidth() / 2, image.getHeight() / 2 } });
final CachingMultivariateGaussian gauss = new CachingMultivariateGaussian(mean, covariance);
if (drawData) {
final Random rng = new Random();
for (int i = 0; i < 1000; i++) {
final double[] sample = gauss.sample(rng);
Point2dImpl pt = new Point2dImpl((float) sample[0], (float) sample[1]);
pt = pt.transform(TransformUtilities.scaleMatrixAboutPoint(40, -40, image.getWidth() / 2,
image.getHeight() / 2));
image.drawPoint(pt, RGBColour.BLUE, 3);
}
}
if (drawEllipse)
image.createRenderer(RenderHints.ANTI_ALIASED).drawShape(e, 3, RGBColour.RED);
}
this.imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg));
}
protected void setYY() {
covariance.set(1, 1, yySlider.getValue() / 100d);
updateImage();
}
protected void setXY() {
covariance.set(1, 0, xySlider.getValue() / 100d);
covariance.set(0, 1, xySlider.getValue() / 100d);
updateImage();
}
protected void setXX() {
covariance.set(0, 0, xxSlider.getValue() / 100d);
updateImage();
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new CovarianceDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
|
package af.algorithms;
import af.model.Pathway;
import af.model.WayPoint;
import java.util.Properties;
public class ShortRouteCalculator implements RouteCalculator {
Properties props;
@Override
public Pathway calcRoute(Pathway pw) {
pw.addWaypoint(new WayPoint("one", 0, 0));
pw.addWaypoint(new WayPoint("two", 0, 0));
return pw;
}
@Override
public void setCalcOptions(Properties props) {
this.props = props;
}
}
|
package org.commcare.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.CommCareApplication;
import org.commcare.dalvik.R;
import org.commcare.tasks.ConnectionDiagnosticTask;
import org.commcare.tasks.DataSubmissionListener;
import org.commcare.tasks.LogSubmissionTask;
import org.commcare.utils.CommCareUtil;
import org.commcare.utils.MarkupUtil;
import org.commcare.views.ManagedUi;
import org.commcare.views.UiElement;
import org.commcare.views.dialogs.CustomProgressDialog;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
/**
* Activity that will diagnose various connection problems that a user may be facing.
*
* @author srengesh
*/
@ManagedUi(R.layout.connection_diagnostic)
public class ConnectionDiagnosticActivity extends CommCareActivity<ConnectionDiagnosticActivity> {
private static final String TAG = ConnectionDiagnosticActivity.class.getSimpleName();
public static final String logUnsetPostURLMessage = "CCHQ ping test: post URL not set.";
@UiElement(value = R.id.run_connection_test, locale = "connection.test.run")
Button btnRunTest;
@UiElement(value = R.id.output_message, locale = "connection.test.messages")
TextView txtInteractiveMessages;
@UiElement(value = R.id.settings_button, locale = "connection.test.access.settings")
Button settingsButton;
@UiElement(value = R.id.report_button, locale = "connection.test.report.button.message")
Button reportButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnRunTest.setOnClickListener(v -> {
ConnectionDiagnosticTask<ConnectionDiagnosticActivity> mConnectionDiagnosticTask =
new ConnectionDiagnosticTask<ConnectionDiagnosticActivity>(getApplicationContext()) {
@Override
//<R> receiver, <C> result.
//<C> is the return from DoTaskBackground, of type ArrayList<Boolean>
protected void deliverResult(ConnectionDiagnosticActivity receiver, Test failedTest) {
//user-caused connection issues
if (failedTest == Test.isOnline ||
failedTest == Test.googlePing) {
//get the appropriate display message based on what the problem is
String displayMessage = failedTest == Test.isOnline ?
Localization.get("connection.task.internet.fail")
: Localization.get("connection.task.remote.ping.fail");
receiver.txtInteractiveMessages.setText(displayMessage);
receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);
receiver.settingsButton.setVisibility(View.VISIBLE);
} else if (failedTest == Test.commCarePing) {
//unable to ping commcare -- report this to cchq
receiver.txtInteractiveMessages.setText(
Localization.get("connection.task.commcare.html.fail"));
receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);
receiver.reportButton.setVisibility(View.VISIBLE);
} else if (failedTest == null) {
receiver.txtInteractiveMessages.setText(Localization.get("connection.task.success"));
receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);
receiver.settingsButton.setVisibility(View.INVISIBLE);
receiver.reportButton.setVisibility(View.INVISIBLE);
}
}
@Override
protected void deliverUpdate(ConnectionDiagnosticActivity receiver, String... update) {
receiver.txtInteractiveMessages.setText((Localization.get("connection.test.update.message")));
}
@Override
protected void deliverError(ConnectionDiagnosticActivity receiver, Exception e) {
receiver.txtInteractiveMessages.setText(Localization.get("connection.test.error.message"));
receiver.transplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
};
mConnectionDiagnosticTask.connect(ConnectionDiagnosticActivity.this);
mConnectionDiagnosticTask.executeParallel();
});
//Set a button that allows you to change your airplane mode settings
this.settingsButton.setOnClickListener(v -> startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)));
this.reportButton.setOnClickListener(v -> {
String url = LogSubmissionTask.getSubmissionUrl(CommCareApplication.instance().getCurrentApp().getAppPreferences());
if (url != null) {
CommCareUtil.executeLogSubmission(url, false);
ConnectionDiagnosticActivity.this.finish();
Toast.makeText(
CommCareApplication.instance(),
Localization.get("connection.task.report.commcare.popup"),
Toast.LENGTH_LONG).show();
} else {
Logger.log(ConnectionDiagnosticTask.CONNECTION_DIAGNOSTIC_REPORT, logUnsetPostURLMessage);
ConnectionDiagnosticActivity.this.txtInteractiveMessages.setText(MarkupUtil.localizeStyleSpannable(ConnectionDiagnosticActivity.this, "connection.task.unset.posturl"));
ConnectionDiagnosticActivity.this.txtInteractiveMessages.setVisibility(View.VISIBLE);
}
});
}
/**
* Implementation of generateProgressDialog() for DialogController -- other methods
* handled entirely in CommCareActivity
*/
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
if (taskId == ConnectionDiagnosticTask.CONNECTION_ID) {
String title = Localization.get("connection.test.run.title");
String message = Localization.get("connection.test.now.running");
CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId);
dialog.setCancelable();
return dialog;
} else {
Log.w(TAG, "taskId passed to generateProgressDialog does not match "
+ "any valid possibilities in ConnectionDiagnosticActivity");
return null;
}
}
}
|
package org.commcare.dalvik.activities;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.commcare.android.database.global.models.ApplicationRecord;
import org.commcare.android.fragments.SetupEnterURLFragment;
import org.commcare.android.fragments.SetupInstallFragment;
import org.commcare.android.fragments.SetupKeepInstallFragment;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.ManagedUi;
import org.commcare.android.logic.BarcodeScanListenerDefaultImpl;
import org.commcare.android.logic.GlobalConstants;
import org.commcare.android.models.notifications.NotificationMessage;
import org.commcare.android.models.notifications.NotificationMessageFactory;
import org.commcare.android.resource.AppInstallStatus;
import org.commcare.android.tasks.ResourceEngineListener;
import org.commcare.android.tasks.ResourceEngineTask;
import org.commcare.android.tasks.RetrieveParseVerifyMessageListener;
import org.commcare.android.tasks.RetrieveParseVerifyMessageTask;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApp;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.dialogs.CustomProgressDialog;
import org.commcare.resources.model.UnresolvedResourceException;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.PropertyUtils;
import org.joda.time.DateTime;
import java.io.IOException;
import java.security.SignatureException;
import java.util.List;
/**
* Responsible for identifying the state of the application (uninstalled,
* installed) and performing any necessary setup to get to a place where
* CommCare can load normally.
*
* If the startup activity identifies that the app is installed properly it
* should not ever require interaction or be visible to the user.
*
* @author ctsims
*/
@ManagedUi(R.layout.first_start_screen_modern)
public class CommCareSetupActivity extends CommCareActivity<CommCareSetupActivity>
implements ResourceEngineListener, SetupEnterURLFragment.URLInstaller,
SetupKeepInstallFragment.StartStopInstallCommands, RetrieveParseVerifyMessageListener {
private static final String TAG = CommCareSetupActivity.class.getSimpleName();
public static final String KEY_PROFILE_REF = "app_profile_ref";
private static final String KEY_UI_STATE = "current_install_ui_state";
private static final String KEY_OFFLINE = "offline_install";
private static final String KEY_FROM_EXTERNAL = "from_external";
private static final String KEY_FROM_MANAGER = "from_manager";
/**
* Should the user be logged out when this activity is done?
*/
public static final String KEY_REQUIRE_REFRESH = "require_referesh";
public static final String KEY_INSTALL_FAILED = "install_failed";
/**
* Activity is being launched by auto update, instead of being triggered
* manually.
*/
public static final String KEY_LAST_INSTALL = "last_install_time";
/**
* How many sms messages to scan over looking for commcare install link
*/
private static final int SMS_CHECK_COUNT = 100;
/**
* UI configuration states.
*/
public enum UiState {
IN_URL_ENTRY,
CHOOSE_INSTALL_ENTRY_METHOD,
READY_TO_INSTALL,
ERROR
}
private UiState uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;
private static final int MODE_ARCHIVE = Menu.FIRST;
private static final int MODE_SMS = Menu.FIRST + 2;
public static final int BARCODE_CAPTURE = 1;
private static final int ARCHIVE_INSTALL = 3;
private static final int DIALOG_INSTALL_PROGRESS = 4;
private boolean startAllowed = true;
private String incomingRef;
private CommCareApp ccApp;
/**
* Indicates that this activity was launched from the AppManagerActivity
*/
private boolean fromManager;
/**
* Indicates that this activity was launched from an outside application (such as a bit.ly
* url entered in a browser)
*/
private boolean fromExternal;
/**
* Indicates that the current install attempt will be made from a .ccz file, so we do
* not need to check for internet connectivity
*/
private boolean offlineInstall;
//region UIState fragments
private final FragmentManager fm = getSupportFragmentManager();
private final SetupKeepInstallFragment startInstall = new SetupKeepInstallFragment();
private final SetupInstallFragment installFragment = new SetupInstallFragment();
//endregion
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CommCareSetupActivity oldActivity = (CommCareSetupActivity)this.getDestroyedActivityState();
this.fromManager = this.getIntent().
getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false);
//Retrieve instance state
if (savedInstanceState == null) {
Log.v("UiState", "SavedInstanceState is null, not getting anything from it =/");
if (Intent.ACTION_VIEW.equals(this.getIntent().getAction())) {
//We got called from an outside application, it's gonna be a wild ride!
fromExternal = true;
incomingRef = this.getIntent().getData().toString();
if (incomingRef.contains(".ccz")) {
// make sure this is in the file system
boolean isFile = incomingRef.contains("file:
if (isFile) {
// remove file:// prepend
incomingRef = incomingRef.substring(incomingRef.indexOf("
Intent i = new Intent(this, InstallArchiveActivity.class);
i.putExtra(InstallArchiveActivity.ARCHIVE_REFERENCE, incomingRef);
startActivityForResult(i, ARCHIVE_INSTALL);
} else {
fail(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Bad_Archive_File), true);
}
} else {
this.uiState = UiState.READY_TO_INSTALL;
//Now just start up normally.
}
} else {
incomingRef = this.getIntent().getStringExtra(KEY_PROFILE_REF);
}
} else {
String uiStateEncoded = savedInstanceState.getString(KEY_UI_STATE);
this.uiState = uiStateEncoded == null ? UiState.CHOOSE_INSTALL_ENTRY_METHOD : UiState.valueOf(UiState.class, uiStateEncoded);
Log.v("UiState", "uiStateEncoded is: " + uiStateEncoded +
", so my uiState is: " + uiState);
incomingRef = savedInstanceState.getString("profileref");
fromExternal = savedInstanceState.getBoolean(KEY_FROM_EXTERNAL);
fromManager = savedInstanceState.getBoolean(KEY_FROM_MANAGER);
offlineInstall = savedInstanceState.getBoolean(KEY_OFFLINE);
// Uggggh, this might not be 100% legit depending on timing, what
// if we've already reconnected and shut down the dialog?
startAllowed = savedInstanceState.getBoolean("startAllowed");
}
// reclaim ccApp for resuming installation
if (oldActivity != null) {
this.ccApp = oldActivity.ccApp;
}
Log.v("UiState", "Current vars: " +
"UIState is: " + this.uiState + " " +
"incomingRef is: " + incomingRef + " " +
"startAllowed is: " + startAllowed + " "
);
uiStateScreenTransition();
performSMSInstall(false);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// removes the back button from the action bar
actionBar.setDisplayHomeAsUpEnabled(false);
}
}
}
@Override
protected void onResume() {
super.onResume();
// If clicking the regular app icon brought us to CommCareSetupActivity
// (because that's where we were last time the app was up), but there are now
// 1 or more available apps, we want to redirect to CCHomeActivity
if (!fromManager && !fromExternal &&
CommCareApplication._().usableAppsPresent()) {
Intent i = new Intent(this, CommCareHomeActivity.class);
startActivity(i);
}
}
@Override
public void onURLChosen(String url) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "SetupEnterURLFragment returned: " + url);
}
incomingRef = url;
this.uiState = UiState.READY_TO_INSTALL;
uiStateScreenTransition();
}
private void uiStateScreenTransition() {
Fragment fragment;
FragmentTransaction ft = fm.beginTransaction();
switch (uiState) {
case READY_TO_INSTALL:
if (incomingRef == null || incomingRef.length() == 0) {
Log.e(TAG, "During install: IncomingRef is empty!");
Toast.makeText(getApplicationContext(), "Invalid URL: '" +
incomingRef + "'", Toast.LENGTH_SHORT).show();
return;
}
// the buttonCommands were already set when the fragment was
// attached, no need to set them here
fragment = startInstall;
break;
case IN_URL_ENTRY:
fragment = restoreInstallSetupFragment();
this.offlineInstall = false;
break;
case CHOOSE_INSTALL_ENTRY_METHOD:
fragment = installFragment;
this.offlineInstall = false;
break;
default:
return;
}
ft.replace(R.id.setup_fragment_container, fragment);
ft.commit();
}
private Fragment restoreInstallSetupFragment() {
Fragment fragment = null;
List<Fragment> fgmts = fm.getFragments();
int lastIndex = fgmts != null ? fgmts.size() - 1 : -1;
if (lastIndex > -1) {
fragment = fgmts.get(lastIndex);
if (BuildConfig.DEBUG) {
Log.v(TAG, "Last fragment: " + fragment);
}
}
if (!(fragment instanceof SetupEnterURLFragment)) {
// last fragment wasn't url entry, so default to the installation method chooser
fragment = installFragment;
}
return fragment;
}
@Override
protected void onStart() {
super.onStart();
uiStateScreenTransition();
}
@Override
protected int getWakeLockLevel() {
return PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_UI_STATE, uiState.toString());
outState.putString("profileref", incomingRef);
outState.putBoolean("startAllowed", startAllowed);
outState.putBoolean(KEY_OFFLINE, offlineInstall);
outState.putBoolean(KEY_FROM_EXTERNAL, fromExternal);
outState.putBoolean(KEY_FROM_MANAGER, fromManager);
Log.v("UiState", "Saving instance state: " + outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String result = null;
switch (requestCode) {
case BARCODE_CAPTURE:
if (resultCode == Activity.RESULT_OK) {
result = data.getStringExtra(BarcodeScanListenerDefaultImpl.SCAN_RESULT);
String dbg = "Got url from barcode scanner: " + result;
Log.i(TAG, dbg);
}
break;
case ARCHIVE_INSTALL:
if (resultCode == Activity.RESULT_OK) {
offlineInstall = true;
result = data.getStringExtra(InstallArchiveActivity.ARCHIVE_REFERENCE);
}
break;
}
if (result == null) return;
incomingRef = result;
this.uiState = UiState.READY_TO_INSTALL;
try {
// check if the reference can be derived without erroring out
ReferenceManager._().DeriveReference(incomingRef);
} catch (InvalidReferenceException ire) {
// Couldn't process reference, return to basic ui state to ask user
// for new install reference
incomingRef = null;
Toast.makeText(getApplicationContext(),
Localization.get("install.bad.ref"),
Toast.LENGTH_LONG).show();
this.uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;
}
uiStateScreenTransition();
}
private String getRef() {
return incomingRef;
}
private CommCareApp getCommCareApp() {
ApplicationRecord newRecord =
new ApplicationRecord(PropertyUtils.genUUID().replace("-", ""),
ApplicationRecord.STATUS_UNINITIALIZED);
return new CommCareApp(newRecord);
}
@Override
public void startBlockingForTask(int id) {
super.startBlockingForTask(id);
this.startAllowed = false;
}
@Override
public void stopBlockingForTask(int id) {
super.stopBlockingForTask(id);
this.startAllowed = true;
}
private void startResourceInstall() {
if (startAllowed) {
CommCareApp app = getCommCareApp();
ccApp = app;
CustomProgressDialog lastDialog = getCurrentDialog();
// used to tell the ResourceEngineTask whether or not it should
// sleep before it starts, set based on whether we are currently
// in keep trying mode.
boolean shouldSleep = (lastDialog != null) && lastDialog.isChecked();
ResourceEngineTask<CommCareSetupActivity> task =
new ResourceEngineTask<CommCareSetupActivity>(app,
DIALOG_INSTALL_PROGRESS, shouldSleep) {
@Override
protected void deliverResult(CommCareSetupActivity receiver,
AppInstallStatus result) {
switch (result) {
case Installed:
receiver.reportSuccess(true);
break;
case UpToDate:
receiver.reportSuccess(false);
break;
case MissingResourcesWithMessage:
// fall through to more general case:
case MissingResources:
receiver.failMissingResource(this.missingResourceException, result);
break;
case IncompatibleReqs:
receiver.failBadReqs(badReqCode, vRequired, vAvailable, majorIsProblem);
break;
case NoLocalStorage:
receiver.failWithNotification(AppInstallStatus.NoLocalStorage);
break;
case BadCertificate:
receiver.failWithNotification(AppInstallStatus.BadCertificate);
break;
case DuplicateApp:
receiver.failWithNotification(AppInstallStatus.DuplicateApp);
break;
default:
receiver.failUnknown(AppInstallStatus.UnknownFailure);
break;
}
}
@Override
protected void deliverUpdate(CommCareSetupActivity receiver,
int[]... update) {
receiver.updateResourceProgress(update[0][0], update[0][1], update[0][2]);
}
@Override
protected void deliverError(CommCareSetupActivity receiver,
Exception e) {
receiver.failUnknown(AppInstallStatus.UnknownFailure);
}
};
task.connect(this);
task.execute(getRef());
} else {
Log.i(TAG, "During install: blocked a resource install press since a task was already running");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MODE_ARCHIVE, 0, Localization.get("menu.archive")).setIcon(android.R.drawable.ic_menu_upload);
menu.add(0, MODE_SMS, 1, Localization.get("menu.sms")).setIcon(android.R.drawable.stat_notify_chat);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
/**
* Scan SMS messages for texts with profile references.
* @param installTriggeredManually if scan was triggered manually, then
* install automatically if reference is found
*/
private void performSMSInstall(boolean installTriggeredManually){
this.scanSMSLinks(installTriggeredManually);
}
/**
* Scan the most recent incoming text messages for a message with a
* verified link to a commcare app and install it. Message scanning stops
* after the number of scanned messages reaches 'SMS_CHECK_COUNT'.
*
* @param installTriggeredManually don't install the found app link
*/
private void scanSMSLinks(final boolean installTriggeredManually){
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
DateTime oneDayAgo = (new DateTime()).minusDays(1);
Cursor cursor = getContentResolver().query(SMS_INBOX,
null, "date >? ",
new String[] {"" + oneDayAgo.getMillis() },
"date DESC");
if (cursor == null) {
return;
}
int messageIterationCount = 0;
try {
boolean attemptedInstall = false;
while (cursor.moveToNext() && messageIterationCount <= SMS_CHECK_COUNT) { // must check the result to prevent exception
messageIterationCount++;
String textMessageBody = cursor.getString(cursor.getColumnIndex("body"));
if (textMessageBody.contains(GlobalConstants.SMS_INSTALL_KEY_STRING)) {
attemptedInstall = true;
RetrieveParseVerifyMessageTask mTask =
new RetrieveParseVerifyMessageTask<CommCareSetupActivity>(this, installTriggeredManually) {
@Override
protected void deliverResult(CommCareSetupActivity receiver, String result) {
if (installTriggeredManually) {
if (result != null) {
receiver.incomingRef = result;
receiver.uiState = UiState.READY_TO_INSTALL;
receiver.uiStateScreenTransition();
receiver.startResourceInstall();
} else {
// only notify if this was manually triggered, since most people won't use this
Toast.makeText(receiver, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show();
}
} else {
if (result != null) {
receiver.incomingRef = result;
receiver.uiState = UiState.READY_TO_INSTALL;
receiver.uiStateScreenTransition();
Toast.makeText(receiver, Localization.get("menu.sms.ready"), Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void deliverUpdate(CommCareSetupActivity receiver, Void... update) {
//do nothing for now
}
@Override
protected void deliverError(CommCareSetupActivity receiver, Exception e) {
if (e instanceof SignatureException) {
e.printStackTrace();
Toast.makeText(receiver, Localization.get("menu.sms.not.verified"), Toast.LENGTH_LONG).show();
} else if (e instanceof IOException) {
e.printStackTrace();
Toast.makeText(receiver, Localization.get("menu.sms.not.retrieved"), Toast.LENGTH_LONG).show();
} else {
e.printStackTrace();
Toast.makeText(receiver, Localization.get("notification.install.unknown.title"), Toast.LENGTH_LONG).show();
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, textMessageBody);
} else {
mTask.execute(textMessageBody);
}
break;
}
}
// attemptedInstall will only be true if we found no texts with the SMS_INSTALL_KEY_STRING tag
// if we found one, notification will be handle by the task receiver
if(!attemptedInstall && installTriggeredManually) {
Toast.makeText(this, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show();
}
}
finally {
cursor.close();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == MODE_ARCHIVE) {
Intent i = new Intent(getApplicationContext(), InstallArchiveActivity.class);
startActivityForResult(i, ARCHIVE_INSTALL);
}
if (item.getItemId() == MODE_SMS) {
performSMSInstall(true);
}
return true;
}
/**
* Return to or launch home activity.
*
* @param requireRefresh should the user be logged out upon returning to
* home activity?
* @param failed did installation occur successfully?
*/
private void done(boolean requireRefresh, boolean failed) {
if (Intent.ACTION_VIEW.equals(CommCareSetupActivity.this.getIntent().getAction())) {
//Call out to CommCare Home
Intent i = new Intent(getApplicationContext(), CommCareHomeActivity.class);
i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);
startActivity(i);
} else {
//Good to go
Intent i = new Intent(getIntent());
i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);
i.putExtra(KEY_INSTALL_FAILED, failed);
setResult(RESULT_OK, i);
}
finish();
}
/**
* Raise failure message and return to the home activity with cancel code
*/
private void fail(NotificationMessage message, boolean alwaysNotify) {
Toast.makeText(this, message.getTitle(), Toast.LENGTH_LONG).show();
if (alwaysNotify) {
CommCareApplication._().reportNotificationMessage(message);
}
// Last install attempt failed, so restore to starting uistate to try again
uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;
uiStateScreenTransition();
}
// All final paths from the Update are handled here (Important! Some
// interaction modes should always auto-exit this activity) Everything here
// should call one of: fail() or done()
/* All methods for implementation of ResourceEngineListener */
@Override
public void reportSuccess(boolean appChanged) {
//If things worked, go ahead and clear out any warnings to the contrary
CommCareApplication._().clearNotifications("install_update");
if (!appChanged) {
Toast.makeText(this, Localization.get("updates.success"), Toast.LENGTH_LONG).show();
}
done(appChanged, false);
}
@Override
public void failMissingResource(UnresolvedResourceException ure, AppInstallStatus statusMissing) {
fail(NotificationMessageFactory.message(statusMissing, new String[]{null, ure.getResource().getDescriptor(), ure.getMessage()}), ure.isMessageUseful());
}
@Override
public void failBadReqs(int code, String vRequired, String vAvailable, boolean majorIsProblem) {
String versionMismatch = Localization.get("install.version.mismatch", new String[]{vRequired, vAvailable});
String error;
if (majorIsProblem) {
error = Localization.get("install.major.mismatch");
} else {
error = Localization.get("install.minor.mismatch");
}
fail(NotificationMessageFactory.message(AppInstallStatus.IncompatibleReqs, new String[]{null, versionMismatch, error}), true);
}
@Override
public void failUnknown(AppInstallStatus unknown) {
fail(NotificationMessageFactory.message(unknown), false);
}
@Override
public void updateResourceProgress(int done, int total, int phase) {
updateProgress(Localization.get("profile.found", new String[]{"" + done, "" + total}), DIALOG_INSTALL_PROGRESS);
updateProgressBar(done, total, DIALOG_INSTALL_PROGRESS);
}
@Override
public void failWithNotification(AppInstallStatus statusfailstate) {
fail(NotificationMessageFactory.message(statusfailstate), true);
}
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
if (taskId != DIALOG_INSTALL_PROGRESS) {
Log.w(TAG, "taskId passed to generateProgressDialog does not match "
+ "any valid possibilities in CommCareSetupActivity");
return null;
}
String title = Localization.get("updates.resources.initialization");
String message = Localization.get("updates.resources.profile");
CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId);
dialog.setCancelable(false);
String checkboxText = Localization.get("install.keep.trying");
CustomProgressDialog lastDialog = getCurrentDialog();
boolean isChecked = (lastDialog != null) && lastDialog.isChecked();
dialog.addCheckbox(checkboxText, isChecked);
dialog.addProgressBar();
return dialog;
}
//region StartStopInstallCommands implementation
@Override
public void onStartInstallClicked() {
if (!offlineInstall && isNetworkNotConnected()) {
failWithNotification(AppInstallStatus.NoConnection);
} else {
startResourceInstall();
}
}
@Override
public void onStopInstallClicked() {
incomingRef = null;
uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;
uiStateScreenTransition();
}
public void setUiState(UiState newState) {
uiState = newState;
}
@Override
public void downloadLinkReceived(String url) {
if (url != null) {
incomingRef = url;
uiState = UiState.READY_TO_INSTALL;
uiStateScreenTransition();
Toast.makeText(this, Localization.get("menu.sms.ready"), Toast.LENGTH_LONG).show();
}
}
@Override
public void downloadLinkReceivedAutoInstall(String url) {
if(url != null){
incomingRef = url;
uiState = UiState.READY_TO_INSTALL;
uiStateScreenTransition();
startResourceInstall();
} else{
// only notify if this was manually triggered, since most people won't use this
Toast.makeText(this, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show();
}
}
@Override
public void exceptionReceived(Exception e) {
if(e instanceof SignatureException){
e.printStackTrace();
Toast.makeText(this, Localization.get("menu.sms.not.verified"), Toast.LENGTH_LONG).show();
} else if(e instanceof IOException){
e.printStackTrace();
Toast.makeText(this, Localization.get("menu.sms.not.retrieved"), Toast.LENGTH_LONG).show();
} else{
e.printStackTrace();
Toast.makeText(this, Localization.get("notification.install.unknown.title"), Toast.LENGTH_LONG).show();
}
}
}
|
package com.peterjosling.scroball;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static com.google.common.truth.Truth.assertThat;
@RunWith(JUnit4.class)
public class PlaybackItemTest {
Track track = ImmutableTrack.builder()
.track("Track")
.artist("Artist")
.build();
@Test
public void updateAmountPlayed_hasNoEffectWhenNotPlaying() {
long timestamp = System.currentTimeMillis() - 10 * 1000;
PlaybackItem playbackItem1 = new PlaybackItem(track, timestamp);
PlaybackItem playbackItem2 = new PlaybackItem(track, timestamp);
assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);
assertThat(playbackItem2.getAmountPlayed()).isEqualTo(0);
playbackItem1.updateAmountPlayed();
playbackItem2.updateAmountPlayed();
assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);
assertThat(playbackItem2.getAmountPlayed()).isEqualTo(0);
}
@Test
public void updateAmountPlayed_updatesWhenPlaying() {
long delay = 10 * 1000;
long alreadyPlayed = 2000;
long startTime = System.currentTimeMillis() - delay;
PlaybackItem playbackItem1 = new PlaybackItem(track, startTime);
playbackItem1.startPlaying();
PlaybackItem playbackItem2 = new PlaybackItem(track, startTime, alreadyPlayed);
assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);
assertThat(playbackItem2.getAmountPlayed()).isEqualTo(alreadyPlayed);
playbackItem1.stopPlaying();
playbackItem2.updateAmountPlayed();
// assertThat(playbackItem1.getAmountPlayed() / 1000).isEqualTo(delay / 1000);
// assertThat(playbackItem2.getAmountPlayed() / 1000).isEqualTo((delay + alreadyPlayed) / 1000);
// TODO use fake clock to fix this test.
}
@Test
public void updateAmountPlayed_updatesStartTimeToAvoidCountingTwice() {
// TODO
}
}
|
package musikerverwaltung;
import java.awt.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import java.awt.Font;
public class MusicLounge02 extends JFrame {
// VersionsNr. festlegen
private static final long serialVersionUID = 02L;
// Felder:
// Schriften:
private Font fheader;
// Farben
private Color bgheader, bginfo, bgmain, bgnew, bgfooter;
// Contentpane
private Container copa;
// JPanel
private JPanel jpall, jpheader, jpmain, jpinfo, jpnew, jpfooter;
// JLabels
private JLabel jlheader, jlsearch;
// JTextField
private JTextField jtfsearch;
// Konstruktor
private MusicLounge02() {
// Titel (Aufruf mit super aus der Basisklasse)
super("MusicLounge");
// Sauberes Schlieen ermoeglichen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Schriften erzeugen
fheader = new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 25);
// Farben erzeugen
bgheader = new Color(176, 176, 176);
bginfo = new Color(122, 139, 139);
bgmain = new Color(217, 217, 217);
bgnew = new Color(122, 139, 139);
bgfooter = new Color(176, 176, 176);
// Gibt ContentPane Objekt zurueck
copa = getContentPane();
// JPanel erzeugen mit BorderLayout
jpall = new JPanel(new BorderLayout());
jpheader = new JPanel();
jpmain = new JPanel();
jpinfo = new JPanel();
jpnew = new JPanel();
jpfooter = new JPanel();
// Farben hinzufuegen
jpheader.setBackground(bgheader);
jpinfo.setBackground(bginfo);
jpmain.setBackground(bgmain);
jpnew.setBackground(bgnew);
jpfooter.setBackground(bgfooter);
// JPanels der >jpall< hinzufuegen
jpall.add(jpheader, BorderLayout.NORTH);
jpall.add(jpmain, BorderLayout.CENTER);
jpall.add(jpinfo, BorderLayout.EAST);
jpall.add(jpnew, BorderLayout.WEST);
jpall.add(jpfooter, BorderLayout.SOUTH);
// JLabel erzeugen
jlheader = new JLabel("MusicLounge");
jlsearch = new JLabel("Suche");
// Schriftart hinzufuegen
jlheader.setFont(fheader);
// JLabel der >jpheader< hinzufuegen
jpheader.add(jlheader);
jpheader.add(jlsearch);
// JPanel der ContentPane hinzufuegen
copa.add(jpall);
// Automatische Groesse setzen
pack();
// Frame sichtbar machen
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Konfliktfreies spaeteres paralleles Betreiben des Dialoges
// sicherstellen
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MusicLounge02();
}
});
}
}
|
package necromunda;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import necromunda.Fighter.State;
import necromunda.MaterialFactory.MaterialIdentifier;
import necromunda.Necromunda.Phase;
import necromunda.Necromunda.SelectionMode;
import weapons.Ammunition;
import weapons.RangeCombatWeapon;
import weapons.Weapon;
import weapons.WebPistol;
import weapons.RangeCombatWeapon.WeaponType;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.ScreenshotAppState;
import com.jme3.asset.TextureKey;
import com.jme3.asset.plugins.ClasspathLocator;
import com.jme3.bounding.BoundingBox;
import com.jme3.bounding.BoundingSphere;
import com.jme3.bounding.BoundingVolume;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.collision.shapes.CylinderCollisionShape;
import com.jme3.bullet.control.GhostControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.collision.Collidable;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.material.plugins.NeoTextureMaterialKey;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Ray;
import com.jme3.math.Rectangle;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.BloomFilter;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.control.BillboardControl;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Cylinder;
import com.jme3.scene.shape.Quad;
import com.jme3.scene.shape.Sphere;
import com.jme3.system.AppSettings;
import com.jme3.texture.Image;
import com.jme3.texture.Texture;
import com.jme3.util.SkyFactory;
public class Necromunda3dProvider extends SimpleApplication implements Observer {
public static final float MAX_COLLISION_NORMAL_ANGLE = 0.05f;
public static final float MAX_SLOPE = 0.05f;
public static final float NOT_TOUCH_DISTANCE = 0.01f;
public static final float MAX_LADDER_DISTANCE = 0.5f;
public static final boolean ENABLE_PHYSICS_DEBUG = false;
public static final Vector3f GROUND_BUFFER = new Vector3f(0, NOT_TOUCH_DISTANCE, 0);
private Necromunda game;
private boolean invertMouse;
private FighterNode selectedFighterNode;
private List<FighterNode> validTargetFighterNodes;
private List<FighterNode> fighterNodes;
private Node buildingsNode;
private Node selectedBuildingNode;
private RigidBodyControl buildingsControl;
private Line currentPath;
private ClimbPath currentClimbPath;
private Node currentPathBoxNode;
private Line currentLineOfSight;
private Node currentLineOfSightBoxNode;
private TemplateNode currentTemplateNode;
private List<TemplateNode> templateNodes;
private List<TemplateRemover> templateRemovers;
private boolean physicsTickLock1;
private boolean physicsTickLock2;
private List<FighterNode> targetedFighterNodes;
private List<FighterNode> validSustainedFireTargetFighterNodes;
private boolean rightButtonDown;
private LinkedList<Node> buildingNodes;
private Ladder currentLadder;
private List<Ladder> currentLadders;
private BitmapText statusMessage;
private MaterialFactory materialFactory;
private String terrainType;
public Necromunda3dProvider(Necromunda game) {
this.game = game;
fighterNodes = new ArrayList<FighterNode>();
buildingsNode = new Node("buildingsNode");
buildingNodes = new LinkedList<Node>();
templateNodes = new ArrayList<TemplateNode>();
templateRemovers = new ArrayList<TemplateRemover>();
targetedFighterNodes = new ArrayList<FighterNode>();
validSustainedFireTargetFighterNodes = new ArrayList<FighterNode>();
validTargetFighterNodes = new ArrayList<FighterNode>();
AppSettings settings = new AppSettings(false);
settings.setTitle("Necromunda");
settings.setSettingsDialogImage("/Textures/Splashscreen01.png");
setSettings(settings);
}
@Override
public void simpleInitApp() {
BulletAppState bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
ScreenshotAppState screenshotAppState = new ScreenshotAppState();
stateManager.attach(screenshotAppState);
assetManager.registerLocator("", ClasspathLocator.class.getName());
assetManager.registerLoader("com.jme3.material.plugins.NeoTextureMaterialLoader", "tgr");
materialFactory = new MaterialFactory(assetManager, this);
Node tableNode = createTableNode();
rootNode.attachChild(tableNode);
createBuildings();
PhysicsSpace physicsSpace = getPhysicsSpace();
physicsSpace.addCollisionListener(new PhysicsCollisionListenerImpl());
physicsSpace.addTickListener(new PhysicsTickListenerImpl());
Node objectsNode = new Node("objectsNode");
rootNode.attachChild(objectsNode);
rootNode.attachChild(buildingsNode);
cam.setLocation(new Vector3f(0, 20, 50));
getFlyByCamera().setMoveSpeed(20f);
guiNode.detachAllChildren();
if (invertMouse) {
invertMouse();
}
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-0.5f, -1.5f, -1).normalize());
sun.setColor(ColorRGBA.White);
rootNode.addLight(sun);
AmbientLight ambientLight = new AmbientLight();
ambientLight.setColor(new ColorRGBA(0.2f, 0.2f, 0.2f, 1.0f));
rootNode.addLight(ambientLight);
initCrossHairs();
initStatusMessage();
TextureKey key0 = new TextureKey("Textures/sky_top_bottom.PNG", true);
key0.setGenerateMips(true);
key0.setAsCube(true);
Texture tex0 = assetManager.loadTexture(key0);
TextureKey key1 = new TextureKey("Textures/sky_left.PNG", true);
key1.setGenerateMips(true);
key1.setAsCube(true);
Texture tex1 = assetManager.loadTexture(key1);
TextureKey key2 = new TextureKey("Textures/sky_right.PNG", true);
key2.setGenerateMips(true);
key2.setAsCube(true);
Texture tex2 = assetManager.loadTexture(key2);
TextureKey key3 = new TextureKey("Textures/sky_front.PNG", true);
key3.setGenerateMips(true);
key3.setAsCube(true);
Texture tex3 = assetManager.loadTexture(key3);
TextureKey key4 = new TextureKey("Textures/sky_back.PNG", true);
key4.setGenerateMips(true);
key4.setAsCube(true);
Texture tex4 = assetManager.loadTexture(key4);
Geometry sky = (Geometry) SkyFactory.createSky(assetManager, tex1, tex2, tex3, tex4, tex0, tex0);
// Fix bug which sometimes culls the skybox
sky.setLocalScale(100);
rootNode.attachChild(sky);
MouseListener mouseListener = new MouseListener();
inputManager.addMapping("leftClick", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addMapping("rightClick", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(mouseListener, "leftClick");
inputManager.addListener(mouseListener, "rightClick");
inputManager.addMapping("Move_Left", new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping("Move_Right", new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping("Move_Up", new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addMapping("Move_Down", new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addListener(mouseListener, "Move_Left", "Move_Right", "Move_Up", "Move_Down");
KeyboardListener keyboardListener = new KeyboardListener();
inputManager.addMapping("Break", new KeyTrigger(KeyInput.KEY_B));
inputManager.addListener(keyboardListener, "Break");
inputManager.addMapping("Move", new KeyTrigger(KeyInput.KEY_M));
inputManager.addListener(keyboardListener, "Move");
inputManager.addMapping("Run", new KeyTrigger(KeyInput.KEY_R));
inputManager.addListener(keyboardListener, "Run");
inputManager.addMapping("Climb", new KeyTrigger(KeyInput.KEY_C));
inputManager.addListener(keyboardListener, "Climb");
inputManager.addMapping("Cycle", new KeyTrigger(KeyInput.KEY_Y));
inputManager.addListener(keyboardListener, "Cycle");
inputManager.addMapping("Yes", new KeyTrigger(KeyInput.KEY_Y));
inputManager.addListener(keyboardListener, "Yes");
inputManager.addMapping("Mode", new KeyTrigger(KeyInput.KEY_O));
inputManager.addListener(keyboardListener, "Mode");
inputManager.addMapping("Shoot", new KeyTrigger(KeyInput.KEY_H));
inputManager.addListener(keyboardListener, "Shoot");
inputManager.addMapping("NextPhase", new KeyTrigger(KeyInput.KEY_N));
inputManager.addListener(keyboardListener, "NextPhase");
inputManager.addMapping("No", new KeyTrigger(KeyInput.KEY_N));
inputManager.addListener(keyboardListener, "No");
inputManager.addMapping("EndTurn", new KeyTrigger(KeyInput.KEY_E));
inputManager.addListener(keyboardListener, "EndTurn");
inputManager.addMapping("SkipBuilding", new KeyTrigger(KeyInput.KEY_K));
inputManager.addListener(keyboardListener, "SkipBuilding");
if (ENABLE_PHYSICS_DEBUG) {
physicsSpace.enableDebug(assetManager);
//createLadderLines();
}
}
private Node createTableNode() {
Box box = new Box(new Vector3f(24, -0.5f, 24), 24, 0.5f, 24);
Geometry tableGeometry = new Geometry("tableGeometry", box);
tableGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.TABLE));
Node tableNode = new Node("tableNode");
tableNode.attachChild(tableGeometry);
return tableNode;
}
private void createBuildings() {
for (Building building : game.getBuildings()) {
BuildingNode buildingNode = new BuildingNode("buildingNode");
for (String identifier : building.getIdentifiers()) {
Material buildingMaterial = materialFactory.createBuildingMaterial(identifier);
Spatial model = assetManager.loadModel("Building" + identifier + ".mesh.xml");
model.setMaterial(buildingMaterial);
buildingNode.attachChild(model);
//Create ladders
Material selectedMaterial = materialFactory.createMaterial(MaterialIdentifier.SELECTED);
List<Ladder> ladders = Ladder.createLaddersFrom("/Building" + identifier + ".ladder", selectedMaterial);
for (Ladder ladder : ladders) {
buildingNode.setLadders(ladders);
buildingNode.attachChild(ladder.getLineNode());
}
}
buildingNodes.add(buildingNode);
}
}
private void createLadderLines() {
for (Ladder ladder : getLaddersFrom(buildingsNode)) {
com.jme3.scene.shape.Line lineShape = new com.jme3.scene.shape.Line(Vector3f.ZERO, Vector3f.UNIT_Y);
Geometry lineGeometry = new Geometry("line", lineShape);
lineGeometry.setMaterial(materialFactory.createMaterial(MaterialFactory.MaterialIdentifier.SELECTED));
ladder.getLineNode().attachChild(lineGeometry);
}
}
private List<Ladder> getLaddersFrom(Node buildingsNode) {
List<Ladder> ladders = new ArrayList<Ladder>();
List<Spatial> buildingNodes = buildingsNode.getChildren();
for (Spatial buildingNode : buildingNodes) {
ladders.addAll(((BuildingNode)buildingNode).getLadders());
}
return ladders;
}
private void invertMouse() {
inputManager.deleteMapping("FLYCAM_Up");
inputManager.deleteMapping("FLYCAM_Down");
inputManager.addMapping("FLYCAM_Up", new MouseAxisTrigger(MouseInput.AXIS_Y, true), new KeyTrigger(KeyInput.KEY_DOWN));
inputManager.addMapping("FLYCAM_Down", new MouseAxisTrigger(MouseInput.AXIS_Y, false), new KeyTrigger(KeyInput.KEY_UP));
inputManager.addListener(getFlyByCamera(), "FLYCAM_Up", "FLYCAM_Down");
}
@Override
public void update(Observable o, Object arg) {
updateModels();
statusMessage.setText(getStatusTextFrom(game));
}
private void updateModels() {
Iterator<FighterNode> it = fighterNodes.iterator();
selectedFighterNode = null;
while (it.hasNext()) {
FighterNode fighterNode = it.next();
Fighter fighter = fighterNode.getFighter();
if (fighter.isOutOfAction()) {
it.remove();
getObjectsNode().detachChild(fighterNode);
GhostControl control = fighterNode.getGhostControl();
getPhysicsSpace().remove(control);
}
if (fighter == game.getSelectedFighter()) {
selectedFighterNode = fighterNode;
setBaseSelected(fighterNode);
}
else if (targetedFighterNodes.contains(fighterNode)) {
setBaseTargeted(fighterNode);
}
else {
setBaseNormal(fighterNode);
}
Node figureNode = (Node) fighterNode.getChild("figureNode");
figureNode.detachChildNamed("symbol");
if (fighter.isPinned()) {
fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_PINNED));
}
else if (fighter.isDown()) {
fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_DOWN));
}
else if (fighter.isSedated()) {
fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_SEDATED));
}
else if (fighter.isComatose()) {
fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_COMATOSE));
}
List<Ladder> laddersInReach = getLaddersInReach(fighterNode.getLocalTranslation(), fighter.getBaseRadius());
if (!laddersInReach.isEmpty()) {
fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_LADDER));
}
}
if (currentTemplateNode != null) {
colouriseBasesUnderTemplate(currentTemplateNode);
}
for (TemplateNode templateNode : templateNodes) {
colouriseBasesUnderTemplate(templateNode);
}
}
private Node getObjectsNode() {
return (Node) rootNode.getChild("objectsNode");
}
private Node getBuildingsNode() {
return (Node) rootNode.getChild("buildingsNode");
}
private Node getTableNode() {
return (Node) rootNode.getChild("tableNode");
}
public void setInvertMouse(boolean invertMouse) {
this.invertMouse = invertMouse;
}
private void colouriseBasesUnderTemplate(TemplateNode templateNode) {
List<FighterNode> fighterNodesUnderTemplate = getFighterNodesUnderTemplate(templateNode, fighterNodes);
for (FighterNode fighterNodeUnderTemplate : fighterNodesUnderTemplate) {
setBaseTargeted(fighterNodeUnderTemplate);
}
}
private void executeKeyboardAction(String name) {
Necromunda.setStatusMessage("");
Fighter selectedFighter = game.getSelectedFighter();
if (name.equals("NextPhase")) {
tearDownCurrentPath();
game.setSelectionMode(SelectionMode.SELECT);
game.nextPhase();
}
else if (name.equals("EndTurn")) {
tearDownCurrentPath();
game.setSelectionMode(SelectionMode.SELECT);
game.endTurn();
turnStarted();
}
else if (name.equals("SkipBuilding") && game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {
skipBuilding();
}
else if (selectedFighter == null) {
Necromunda.setStatusMessage("You must select a fighter first.");
}
else {
if (game.getSelectionMode().equals(SelectionMode.SELECT) && game.getCurrentGang().getGangMembers().contains(selectedFighterNode.getFighter())) {
if (name.equals("Break") && game.getPhase().equals(Phase.MOVEMENT)) {
if (selectedFighter.isPinned()) {
Necromunda.setStatusMessage("This ganger can not break the web.");
}
else {
if (selectedFighter.isWebbed()) {
int webRoll = Utils.rollD6();
if ((webRoll + selectedFighter.getStrength()) >= 9) {
selectedFighter.setWebbed(false);
Necromunda.appendToStatusMessage("This ganger has broken the web.");
}
else {
WebPistol.dealWebDamageTo(selectedFighter);
}
}
else {
Necromunda.setStatusMessage("This ganger is not webbed.");
}
}
}
else if (name.equals("Move") && game.getPhase().equals(Phase.MOVEMENT)) {
if (selectedFighter.canMove() && !selectedFighter.hasRun()) {
if (!selectedFighter.hasMoved()) {
selectedFighter.setIsGoingToRun(false);
}
game.setSelectionMode(SelectionMode.MOVE);
setUpMovement();
}
else {
Necromunda.setStatusMessage("This ganger cannot move.");
}
}
else if (name.equals("Run") && game.getPhase().equals(Phase.MOVEMENT)) {
if (selectedFighter.canRun() && !selectedFighter.hasMoved()) {
if (!selectedFighter.hasRun()) {
selectedFighter.setIsGoingToRun(true);
}
game.setSelectionMode(SelectionMode.MOVE);
setUpMovement();
}
else {
Necromunda.setStatusMessage("This ganger cannot run.");
}
}
else if (name.equals("Shoot") && game.getPhase().equals(Phase.SHOOTING)) {
if (selectedFighter.canShoot()) {
if (!selectedFighter.getWeapons().isEmpty()) {
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
if (weapon == null) {
weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);
selectedFighter.setSelectedRangeCombatWeapon(weapon);
}
if (weapon.isBroken()) {
Necromunda.setStatusMessage("The selected weapon is broken.");
}
else if (!weapon.isEnabled()) {
Necromunda.setStatusMessage("The selected weapon is disabled.");
}
else if (weapon.isMoveOrFire() && selectedFighter.hasMoved()) {
Necromunda.setStatusMessage("The selected weapon cannot be fired after moving.");
}
else {
weapon.resetNumberOfShots();
game.setSelectionMode(SelectionMode.TARGET);
updateValidTargetFighterNodes();
setUpTargeting();
}
}
else {
Necromunda.setStatusMessage("This ganger has no weapons.");
}
}
else {
Necromunda.setStatusMessage("This ganger cannot shoot.");
}
}
else if (name.equals("Cycle")) {
List<Weapon> weapons = selectedFighter.getWeapons();
if (!weapons.isEmpty()) {
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
if (weapon == null) {
weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);
}
else {
int index = weapons.indexOf(weapon);
if (index < weapons.size() - 1) {
weapon = (RangeCombatWeapon) weapons.get(index + 1);
}
else {
weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);
}
}
selectedFighter.setSelectedRangeCombatWeapon(weapon);
}
else {
Necromunda.setStatusMessage("This ganger has no weapons.");
}
}
else if (name.equals("Mode")) {
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
if (weapon != null) {
List<Ammunition> ammunitions = weapon.getAmmunitions();
int index = ammunitions.indexOf(weapon.getCurrentAmmunition());
if (index == -1) {
weapon.setCurrentAmmunition(ammunitions.get(0));
}
else {
if (index < ammunitions.size() - 1) {
weapon.setCurrentAmmunition(ammunitions.get(index + 1));
}
else {
weapon.setCurrentAmmunition(ammunitions.get(0));
}
}
}
else {
Necromunda.setStatusMessage("No weapon selected.");
}
}
}
else if (name.equals("Climb")) {
if (game.getSelectionMode().equals(SelectionMode.MOVE)) {
currentLadders = getLaddersInReach(currentPath.getOrigin(), selectedFighter.getBaseRadius());
if (currentLadders.isEmpty()) {
Necromunda.setStatusMessage("There is no ladder in reach.");
}
else {
currentLadder = currentLadders.get(0);
game.setSelectionMode(SelectionMode.CLIMB);
climbLadder(currentLadder);
}
}
else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {
int ladderIndex = currentLadders.indexOf(currentLadder);
if (ladderIndex < currentLadders.size() - 1) {
ladderIndex += 1;
}
else {
ladderIndex = 0;
}
currentLadder = currentLadders.get(ladderIndex);
climbLadder(currentLadder);
}
}
}
}
private void climbLadder(Ladder ladder) {
Vector3f currentPathOrigin;
if (currentPath != null) {
currentPathOrigin = currentPath.getOrigin();
tearDownCurrentPath();
}
else {
currentPathOrigin = currentClimbPath.getStart().clone();
}
currentClimbPath = new ClimbPath(currentPathOrigin.clone());
Vector3f nearestLadderCollisionPoint = getLadderCollisionPoint(ladder);
currentClimbPath.addToLength(nearestLadderCollisionPoint.distance(currentPathOrigin));
selectedFighterNode.setLocalTranslation(getLadderCollisionPoint(ladder.getPeer()));
currentClimbPath.addToLength(nearestLadderCollisionPoint.distance(selectedFighterNode.getLocalTranslation()));
}
private void executeMouseAction(String name, boolean isPressed) {
if (name.equals("leftClick")) {
onLeftClick(isPressed);
}
else if (name.equals("rightClick")) {
onRightClick(isPressed);
}
}
private void onLeftClick(boolean isPressed) {
if (isPressed) {
Necromunda.setStatusMessage("");
if (game.getSelectionMode().equals(SelectionMode.SELECT)) {
select();
}
else if (game.getSelectionMode().equals(SelectionMode.MOVE)) {
move();
}
else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {
climb();
}
else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {
target();
}
else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {
deployBuilding();
}
else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_MODEL)) {
deployModel();
}
}
}
private void deployBuilding() {
Vector3f nearestIntersection = getTableCollisionPoint();
if (nearestIntersection == null) {
return;
}
selectedBuildingNode = selectedBuildingNode.clone(false);
selectedBuildingNode.setLocalTranslation(nearestIntersection);
buildingsNode.attachChild(selectedBuildingNode);
}
private void skipBuilding() {
buildingsNode.detachChild(selectedBuildingNode);
selectedBuildingNode = buildingNodes.poll();
Vector3f nearestIntersection = getTableCollisionPoint();
if (nearestIntersection == null) {
return;
}
if (selectedBuildingNode == null) {
CollisionShape sceneShape = CollisionShapeFactory.createMeshShape(buildingsNode);
buildingsControl = new RigidBodyControl(sceneShape, 0);
buildingsControl.setKinematic(false);
buildingsNode.addControl(buildingsControl);
getPhysicsSpace().add(buildingsNode);
game.setSelectionMode(SelectionMode.DEPLOY_MODEL);
updateModelPosition();
}
else {
selectedBuildingNode.setLocalTranslation(nearestIntersection);
buildingsNode.attachChild(selectedBuildingNode);
}
}
private void updateModelPosition() {
Vector3f nearestIntersection = getSceneryCollisionPoint();
if (nearestIntersection == null) {
return;
}
if (selectedFighterNode == null) {
selectedFighterNode = new FighterNode("fighterNode", game.getSelectedFighter(), materialFactory);
getPhysicsSpace().add(selectedFighterNode.getGhostControl());
getObjectsNode().attachChild(selectedFighterNode);
fighterNodes.add(selectedFighterNode);
game.updateStatus();
}
selectedFighterNode.setLocalTranslation(nearestIntersection);
lockPhysics();
}
private void deployModel() {
Vector3f contactPoint = getSceneryCollisionPoint();
List<FighterNode> fighterNodesWithinDistance = getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE);
if ((contactPoint != null) && (selectedFighterNode != null) && hasValidPosition(selectedFighterNode) && fighterNodesWithinDistance.isEmpty()) {
game.fighterDeployed();
}
/*List<Vector3f> pointCloud = selectedFighterNode.getCollisionShapePointCloud();
Material material = materialFactory.createMaterial(MaterialIdentifier.SELECTED);
for (Vector3f vector : pointCloud) {
Quad quad = new Quad(0.01f, 0.01f);
Geometry geometry = new Geometry("cloudpoint", quad);
geometry.setMaterial(material);
geometry.setLocalTranslation(vector);
rootNode.attachChild(geometry);
}*/
}
private void select() {
if (selectedFighterNode != null) {
deselectFighter();
}
FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();
if (fighterNodeUnderCursor != null) {
selectFighter(fighterNodeUnderCursor);
}
}
private void move() {
if (hasValidPosition(selectedFighterNode) && currentPath.isValid()
&& (getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE).isEmpty())) {
List<FighterNode> fighterNodesWithinDistance = getFighterNodesWithinDistance(selectedFighterNode, Necromunda.RUN_SPOT_DISTANCE);
List<FighterNode> hostileFighterNodesWithinDistance = getHostileFighterNodesFrom(fighterNodesWithinDistance);
List<FighterNode> hostileFighterNodesWithinDistanceAndWithLineOfSight = getFighterNodesWithLineOfSightFrom(selectedFighterNode,
hostileFighterNodesWithinDistance);
if (selectedFighterNode.getFighter().isGoingToRun() && (!hostileFighterNodesWithinDistanceAndWithLineOfSight.isEmpty())) {
Necromunda.setStatusMessage("You cannot run so close to an enemy fighter.");
}
else {
commitMovement();
}
}
}
private void climb() {
if (hasValidPosition(selectedFighterNode) && (getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE).isEmpty())) {
if (currentClimbPath.getLength() <= game.getSelectedFighter().getRemainingMovementDistance()) {
commitClimb();
}
else {
Necromunda.setStatusMessage("This ganger cannot climb that far.");
}
}
}
private void target() {
Fighter selectedFighter = game.getSelectedFighter();
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
if (!weapon.isTargeted()) {
weapon.trigger();
fireTemplate(currentTemplateNode);
removeTargetingFacilities();
game.setSelectionMode(SelectionMode.SELECT);
}
else {
FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();
if (fighterNodeUnderCursor == null) {
return;
}
if (!getHostileFighterNodesFrom(fighterNodes).contains(fighterNodeUnderCursor)) {
Necromunda.setStatusMessage("This fighter is not hostile.");
return;
}
List<Collidable> collidables = getBoundingVolumes();
if (currentTemplateNode != null) {
collidables.removeAll(currentTemplateNode.getBoundingSpheres());
}
collidables.add(getBuildingsNode());
/*List<FighterNode> otherFighterNodes = new ArrayList<FighterNode>(fighterNodes);
otherFighterNodes.remove(selectedFighterNode);
otherFighterNodes.remove(fighterNodeUnderCursor);
collidables.addAll(otherFighterNodes);*/
VisibilityInfo visibilityInfo = getVisibilityInfo(selectedFighterNode, fighterNodeUnderCursor, collidables);
if (/*!currentLineOfSight.isValid() ||*/ (visibilityInfo.getNumberOfVisiblePoints() == 0) || isPhysicsLocked()) {
Necromunda.setStatusMessage("Object out of sight.");
return;
}
if (validSustainedFireTargetFighterNodes.isEmpty() && (!validTargetFighterNodes.contains(fighterNodeUnderCursor))) {
Necromunda.setStatusMessage("This fighter is not the nearest target.");
return;
}
boolean targetAdded = addTarget(fighterNodeUnderCursor);
if (targetAdded) {
weapon.targetAdded();
}
if (weapon.getNumberOfShots() > 0) {
return;
}
float visiblePercentage = visibilityInfo.getVisiblePercentage();
Necromunda.appendToStatusMessage("Visible percentage: " + (visiblePercentage * 100));
int hitModifier = 0;
if ((visiblePercentage < 1.0) && (visiblePercentage >= 0.5)) {
hitModifier = -1;
}
else if (visiblePercentage < 0.5) {
hitModifier = -2;
}
fireTargetedWeapon(weapon, hitModifier);
removeTargetingFacilities();
targetedFighterNodes.clear();
validSustainedFireTargetFighterNodes.clear();
}
game.setSelectionMode(SelectionMode.SELECT);
}
private void onRightClick(boolean isPressed) {
if (isPressed) {
rightButtonDown = true;
if (game.getSelectionMode().equals(SelectionMode.MOVE)) {
tearDownCurrentPath();
game.setSelectionMode(SelectionMode.SELECT);
deselectFighter();
}
else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {
abortClimbing();
game.setSelectionMode(SelectionMode.SELECT);
deselectFighter();
}
else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {
removeTargetingFacilities();
game.setSelectionMode(SelectionMode.SELECT);
deselectFighter();
}
}
else {
rightButtonDown = false;
}
}
private FighterNode getFighterNodeUnderCursor() {
List<Collidable> collidables = new ArrayList<Collidable>();
collidables.add(getObjectsNode());
CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);
FighterNode fighterNodeUnderCursor = null;
if (closestCollision != null) {
Geometry geometry = closestCollision.getGeometry();
fighterNodeUnderCursor = (FighterNode) getParent(geometry, "fighterNode");
}
return fighterNodeUnderCursor;
}
private void updateValidTargetFighterNodes() {
validTargetFighterNodes.clear();
List<FighterNode> visibleHostileFighterNodes = getFighterNodesWithLineOfSightFrom(selectedFighterNode, getHostileFighterNodesFrom(fighterNodes));
boolean normalFighterNodeFound = false;
while ((!normalFighterNodeFound) && (!visibleHostileFighterNodes.isEmpty())) {
FighterNode fighterNode = getNearestFighterNodeFrom(selectedFighterNode, visibleHostileFighterNodes);
Fighter fighter = fighterNode.getFighter();
if (fighter.isNormal() || fighter.isPinned()) {
normalFighterNodeFound = true;
}
validTargetFighterNodes.add(fighterNode);
visibleHostileFighterNodes.remove(fighterNode);
}
}
private boolean addTarget(FighterNode fighterNode) {
if (validSustainedFireTargetFighterNodes.isEmpty()) {
addFirstTarget(fighterNode);
return true;
}
else {
return addSubsequentTarget(fighterNode);
}
}
private void addFirstTarget(FighterNode fighterNode) {
targetedFighterNodes.add(fighterNode);
List<FighterNode> sustainedFireNeighbours = getFighterNodesWithinDistance(getFighterNodeUnderCursor(), Necromunda.SUSTAINED_FIRE_RADIUS);
validSustainedFireTargetFighterNodes.add(fighterNode);
validSustainedFireTargetFighterNodes.addAll(sustainedFireNeighbours);
}
private boolean addSubsequentTarget(FighterNode fighterNode) {
if (validSustainedFireTargetFighterNodes.contains(fighterNode)) {
targetedFighterNodes.add(fighterNode);
return true;
}
else {
Necromunda.setStatusMessage("This target is too far away from the first.");
return false;
}
}
private void tearDownCurrentPath() {
if (currentPath != null) {
selectedFighterNode.setLocalTranslation(currentPath.getOrigin());
}
if (currentClimbPath != null) {
selectedFighterNode.setLocalTranslation(currentClimbPath.getStart());
}
rootNode.detachChildNamed("currentPathBoxNode");
if (currentPathBoxNode != null) {
GhostControl physicsGhostObject = currentPathBoxNode.getControl(GhostControl.class);
getPhysicsSpace().remove(physicsGhostObject);
}
currentPath = null;
currentPathBoxNode = null;
}
private void abortClimbing() {
if (currentClimbPath != null) {
selectedFighterNode.setLocalTranslation(currentClimbPath.getStart());
}
currentClimbPath = null;
}
private void removeTargetingFacilities() {
rootNode.detachChildNamed("currentLineOfSightBoxNode");
rootNode.detachChildNamed("currentLineOfSightLine");
if (currentLineOfSightBoxNode != null) {
GhostControl physicsGhostObject = currentLineOfSightBoxNode.getControl(GhostControl.class);
getPhysicsSpace().remove(physicsGhostObject);
}
currentLineOfSight = null;
currentLineOfSightBoxNode = null;
removeCurrentWeaponTemplate();
}
private void removeCurrentWeaponTemplate() {
rootNode.detachChildNamed("currentTemplateNode");
currentTemplateNode = null;
}
private void commitMovement() {
Fighter selectedObject = game.getSelectedFighter();
Vector3f movementVector = currentPath.getVector();
float distance = movementVector.length();
float remainingMovementDistance = selectedObject.getRemainingMovementDistance() - distance;
selectedObject.setRemainingMovementDistance(remainingMovementDistance);
currentPath.getOrigin().set(selectedFighterNode.getLocalTranslation());
for (Fighter object : selectedObject.getGang().getGangMembers()) {
if (object != selectedObject) {
if (object.hasMoved() || object.hasRun()) {
object.setRemainingMovementDistance(0);
}
}
}
if (selectedObject.isGoingToRun()) {
selectedObject.setHasRun(true);
}
else {
selectedObject.setHasMoved(true);
}
if (selectedObject.isSpotted() && selectedObject.hasRun()) {
selectedObject.setRemainingMovementDistance(0);
game.setSelectionMode(SelectionMode.SELECT);
}
if (selectedObject.getRemainingMovementDistance() < 0.01f) {
selectedObject.setRemainingMovementDistance(0);
tearDownCurrentPath();
game.setSelectionMode(SelectionMode.SELECT);
}
}
private void commitClimb() {
Fighter selectedObject = game.getSelectedFighter();
float distance = currentClimbPath.getLength();
System.out.println("Climb Path Length: " + distance);
float remainingMovementDistance = selectedObject.getRemainingMovementDistance() - distance;
selectedObject.setRemainingMovementDistance(remainingMovementDistance);
currentClimbPath.getStart().set(selectedFighterNode.getLocalTranslation());
for (Fighter object : selectedObject.getGang().getGangMembers()) {
if (object != selectedObject) {
if (object.hasMoved() || object.hasRun()) {
object.setRemainingMovementDistance(0);
}
}
}
if (selectedObject.isGoingToRun()) {
selectedObject.setHasRun(true);
}
else {
selectedObject.setHasMoved(true);
}
if (selectedObject.getRemainingMovementDistance() < 0.01f) {
selectedObject.setRemainingMovementDistance(0);
}
abortClimbing();
deselectFighter();
game.setSelectionMode(SelectionMode.SELECT);
}
private Geometry getPathBoxGeometryFor(FighterNode fighterNode) {
Vector3f halfExtents = getHalfExtentsOf(fighterNode);
float pathLength = 0;
if (currentPath != null) {
pathLength = currentPath.length();
}
Box box = new Box(halfExtents.getX(), halfExtents.getY(), pathLength / 2);
Geometry boxGeometry = new Geometry("currentPathBoxGeometry", box);
boxGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.PATH));
boxGeometry.setQueueBucket(Bucket.Transparent);
return boxGeometry;
}
private CollisionShape getPathBoxCollisionShapeOf(FighterNode fighterNode, Line path) {
Vector3f halfExtents = getHalfExtentsOf(fighterNode);
float pathLength = 0;
if (path != null) {
pathLength = path.length();
}
Vector3f vector = new Vector3f(halfExtents.getX(), halfExtents.getY(), pathLength / 2);
BoxCollisionShape collisionShape = new BoxCollisionShape(vector);
return collisionShape;
}
private Vector3f getHalfExtentsOf(FighterNode fighterNode) {
GhostControl control = fighterNode.getGhostControl();
CylinderCollisionShape shape = (CylinderCollisionShape) control.getCollisionShape();
Vector3f halfExtents = shape.getHalfExtents();
return halfExtents;
}
private void selectFighter(FighterNode fighterNode) {
Fighter fighter = fighterNode.getFighter();
/*
* if (fighter.getGang() == game.getCurrentGang()) {
* game.setSelectedFighter(fighter); }
*/
game.setSelectedFighter(fighter);
}
private void deselectFighter() {
game.setSelectedFighter(null);
}
private void setBaseSelected(Node model) {
Spatial base = model.getChild("base");
base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.SELECTED));
}
private void setBaseTargeted(Node model) {
Spatial base = model.getChild("base");
base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.TARGETED));
}
private void setBaseNormal(Node model) {
Spatial base = model.getChild("base");
base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.NORMAL));
}
private boolean hasValidPosition(FighterNode fighterNode) {
if (!fighterNode.isPositionValid() || isPhysicsLocked()) {
System.out.println("Position invalid...");
return false;
}
else {
return true;
}
}
private Node getParent(Spatial spatial, String name) {
Node parent = spatial.getParent();
if (parent == null) {
return null;
}
else if (parent.getName().equals(name)) {
return parent;
}
else {
return getParent(parent, name);
}
}
private void initCrossHairs() {
guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
BitmapText crosshair = new BitmapText(guiFont, false);
crosshair.setSize(guiFont.getCharSet().getRenderedSize() * 2);
// crosshairs
crosshair.setText("+");
// center
crosshair.setLocalTranslation(settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2, settings.getHeight() / 2
+ crosshair.getLineHeight() / 2, 0);
guiNode.attachChild(crosshair);
}
private void initStatusMessage() {
guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
statusMessage = new BitmapText(guiFont, false);
statusMessage.setSize(guiFont.getCharSet().getRenderedSize());
statusMessage.setLocalTranslation(10, 120, 0);
guiNode.attachChild(statusMessage);
}
private VisibilityInfo getVisibilityInfo(FighterNode source, FighterNode target, List<Collidable> collidables) {
Vector3f sourceUpTranslation = new Vector3f(0, source.getFighter().getBaseRadius() * 1.5f, 0);
Vector3f sourceLocation = source.getLocalTranslation().add(sourceUpTranslation);
List<Vector3f> pointCloud = target.getCollisionShapePointCloud();
int numberOfVisiblePoints = 0;
for (Vector3f vector : pointCloud) {
Vector3f direction = vector.subtract(sourceLocation);
CollisionResult closestCollision = Utils.getNearestCollisionFrom(sourceLocation, direction, collidables);
if (closestCollision != null) {
float distanceToTarget = direction.length();
float distanceToCollisionPoint = closestCollision.getContactPoint().subtract(sourceLocation).length();
if (distanceToCollisionPoint >= distanceToTarget) {
numberOfVisiblePoints++;
}
}
else {
numberOfVisiblePoints++;
}
}
VisibilityInfo visibilityInfo = new VisibilityInfo(numberOfVisiblePoints, pointCloud.size());
return visibilityInfo;
}
private List<Collidable> getBoundingVolumes() {
List<Collidable> boundingVolumes = new ArrayList<Collidable>();
for (TemplateNode templateNode : templateNodes) {
boundingVolumes.addAll(templateNode.getBoundingSpheres());
}
return boundingVolumes;
}
private Vector3f getTableCollisionPoint() {
List<Collidable> collidables = new ArrayList<Collidable>();
collidables.add(getTableNode());
CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);
if (closestCollision != null) {
return closestCollision.getContactPoint().add(GROUND_BUFFER);
}
else {
return null;
}
}
private Vector3f getSceneryCollisionPoint() {
List<Collidable> collidables = new ArrayList<Collidable>();
collidables.add(getTableNode());
collidables.add(getBuildingsNode());
CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);
if ((closestCollision != null) && closestCollision.getContactNormal().angleBetween(Vector3f.UNIT_Y) <= MAX_COLLISION_NORMAL_ANGLE) {
return closestCollision.getContactPoint().add(GROUND_BUFFER);
}
else {
return null;
}
}
private Vector3f getLadderCollisionPoint(Ladder ladder) {
CollisionResults results = new CollisionResults();
Ray ray = new Ray(ladder.getWorldEnd(), Vector3f.UNIT_Y.mult(-1));
getTableNode().collideWith(ray, results);
getBuildingsNode().collideWith(ray, results);
CollisionResult closestCollision = results.getClosestCollision();
if (closestCollision != null && closestCollision.getContactNormal().angleBetween(Vector3f.UNIT_Y) <= MAX_COLLISION_NORMAL_ANGLE) {
return closestCollision.getContactPoint().add(GROUND_BUFFER);
}
else {
return null;
}
}
private class PhysicsCollisionListenerImpl implements PhysicsCollisionListener {
@Override
public void collision(PhysicsCollisionEvent event) {
Spatial a = event.getNodeA();
Spatial b = event.getNodeB();
Spatial selectedCollisionShapeNode = null;
if (selectedFighterNode != null) {
selectedCollisionShapeNode = selectedFighterNode.getChild("collisionShapeNode");
}
Spatial targetedCollisionShapeNode = null;
FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();
if (fighterNodeUnderCursor != null) {
targetedCollisionShapeNode = fighterNodeUnderCursor.getChild("collisionShapeNode");
}
if ((a == selectedCollisionShapeNode) && (b.getName().equals("buildingsNode")) || (b == selectedCollisionShapeNode)
&& (a.getName().equals("buildingsNode"))) {
selectedFighterNode.setPositionValid(false);
}
else if ((a == selectedCollisionShapeNode) && (b.getName().equals("collisionShapeNode")) || (b == selectedCollisionShapeNode)
&& (a.getName().equals("collisionShapeNode"))) {
selectedFighterNode.setPositionValid(false);
}
else if ((b.getName().equals("currentLineOfSightBoxNode")
&& ((a.getName().equals("collisionShapeNode") && (a != selectedCollisionShapeNode) && (a != targetedCollisionShapeNode))) || (a.getName()
.equals("currentLineOfSightBoxNode"))
&& ((b.getName().equals("collisionShapeNode") && (b != selectedCollisionShapeNode) && (b != targetedCollisionShapeNode))))) {
if (currentLineOfSight != null) {
currentLineOfSight.setValid(false);
}
}
else if ((a.getName().equals("currentLineOfSightBoxNode")) && (b.getName().equals("buildingsNode"))
|| (b.getName().equals("currentLineOfSightBoxNode")) && (a.getName().equals("buildingsNode"))) {
if (currentLineOfSight != null) {
currentLineOfSight.setValid(false);
}
}
else if ((a.getName().equals("currentPathBoxNode")) && ((b.getName().equals("collisionShapeNode")) && (b != selectedCollisionShapeNode))
|| (b.getName().equals("currentPathBoxNode")) && ((a.getName().equals("collisionShapeNode")) && (a != selectedCollisionShapeNode))) {
if (currentPath != null) {
currentPath.setValid(false);
}
}
else if ((a.getName().equals("currentPathBoxNode")) && (b.getName().equals("buildingsNode")) || (b.getName().equals("currentPathBoxNode"))
&& (a.getName().equals("buildingsNode"))) {
if (currentPath != null) {
currentPath.setValid(false);
}
}
}
}
private class PhysicsTickListenerImpl implements PhysicsTickListener {
@Override
public void prePhysicsTick(PhysicsSpace space, float f) {
}
@Override
public void physicsTick(PhysicsSpace space, float f) {
if (!physicsTickLock1) {
physicsTickLock1 = true;
}
else {
physicsTickLock2 = true;
}
}
}
private class MouseListener implements ActionListener, AnalogListener {
public void onAction(String name, boolean isPressed, float tpf) {
executeMouseAction(name, isPressed);
game.updateStatus();
}
public void onAnalog(String name, float value, float tpf) {
if (game.getSelectionMode().equals(SelectionMode.MOVE)) {
setUpMovement();
}
else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {
setUpTargeting();
}
else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_MODEL)) {
updateModelPosition();
}
else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {
if (rightButtonDown) {
if ((selectedBuildingNode != null) && isMouseMovement(name)) {
float direction = 1;
if (name.equals("Move_Left")) {
direction = -1;
}
selectedBuildingNode.rotate(0, value * 3 * direction, 0);
}
}
else {
Vector3f nearestIntersection = getTableCollisionPoint();
if (nearestIntersection == null) {
return;
}
if (selectedBuildingNode == null) {
selectedBuildingNode = buildingNodes.poll();
buildingsNode.attachChild(selectedBuildingNode);
}
selectedBuildingNode.setLocalTranslation(nearestIntersection);
}
}
updateModels();
}
}
private boolean isMouseMovement(String name) {
if (name.equals("Move_Left") || name.equals("Move_Right") || name.equals("Move_Up") || name.equals("Move_Down")) {
return true;
}
else {
return false;
}
}
private class KeyboardListener implements ActionListener {
@Override
public void onAction(String name, boolean isPressed, float tpf) {
if (isPressed) {
executeKeyboardAction(name);
game.updateStatus();
}
}
}
private class TemplateRemover {
private TemplateNode temporaryWeaponTemplate;
private int timer;
public TemplateRemover(TemplateNode temporaryWeaponTemplate) {
this.temporaryWeaponTemplate = temporaryWeaponTemplate;
this.timer = 2000;
}
public void remove() {
rootNode.detachChild(temporaryWeaponTemplate);
templateNodes.remove(temporaryWeaponTemplate);
updateModels();
}
public int getTimer() {
return timer;
}
public void setTimer(int timer) {
this.timer = timer;
}
}
private List<Ladder> getLaddersInReach(Vector3f origin, float baseRadius) {
List<Ladder> laddersInReach = new ArrayList<Ladder>();
for (Ladder ladder : (List<Ladder>)getLaddersFrom(buildingsNode)) {
float distance = ladder.getWorldStart().distance(origin);
if ((distance - baseRadius) <= MAX_LADDER_DISTANCE) {
laddersInReach.add(ladder);
}
}
return laddersInReach;
}
private void unpinFighters() {
for (FighterNode fighterNode : fighterNodes) {
Fighter fighter = fighterNode.getFighter();
if (game.getCurrentGang().getGangMembers().contains(fighter) && fighter.isPinned()) {
List<FighterNode> surroundingFighterNodes = getFighterNodesWithinDistance(fighterNode, Necromunda.UNPIN_BY_INITIATIVE_DISTANCE);
List<Fighter> reliableMates = new ArrayList<Fighter>();
for (FighterNode surroundingFighterNode : surroundingFighterNodes) {
Fighter surroundingFighter = surroundingFighterNode.getFighter();
if (fighter.getGang().getGangMembers().contains(surroundingFighter) && surroundingFighter.isReliableMate()) {
reliableMates.add(surroundingFighter);
}
}
if (!reliableMates.isEmpty() || fighter instanceof Leader) {
fighter.unpinByInitiative();
}
else {
Necromunda.appendToStatusMessage(String.format("%s has no reliable mates around.", fighter));
}
}
}
}
private void turnStarted() {
unpinFighters();
removeTemplates();
moveTemplates();
applyTemplateEffects();
removeTemplateTrails();
}
private void removeTemplates() {
Iterator<TemplateNode> it = templateNodes.iterator();
while (it.hasNext()) {
TemplateNode templateNode = it.next();
if (templateNode.isTemplateToBeRemoved()) {
it.remove();
rootNode.detachChild(templateNode);
}
}
}
private void moveTemplates() {
for (TemplateNode templateNode : templateNodes) {
if (templateNode.isTemplateMoving()) {
float distance = templateNode.getDriftDistance();
float angle = templateNode.getDriftAngle();
Vector3f start = templateNode.getLocalTranslation().clone();
List<Collidable> collidables = new ArrayList<Collidable>();
collidables.add(getBuildingsNode());
templateNode.moveAndCollide(distance, angle, collidables);
templateNode.attachTrail(start);
}
}
}
private void applyTemplateEffects() {
for (TemplateNode templateNode : templateNodes) {
List<FighterNode> affectedFighterNodes = getFighterNodesUnderTemplate(templateNode, fighterNodes);
templateNode.dealDamageTo(affectedFighterNodes);
}
}
private void removeTemplateTrails() {
for (TemplateNode templateNode : templateNodes) {
templateNode.removeTrail();
}
}
private void setUpMovement() {
updateCurrentPath();
if (currentPath != null) {
updateCurrentPathBox();
}
}
private void updateCurrentPath() {
Vector3f nearestIntersection = getSceneryCollisionPoint();
Vector3f objectPosition = null;
if (currentPath == null) {
objectPosition = selectedFighterNode.getLocalTranslation();
}
else {
objectPosition = currentPath.getOrigin();
}
if (nearestIntersection == null) {
return;
}
float slope = FastMath.abs(nearestIntersection.getY() - objectPosition.getY());
if (slope > MAX_SLOPE) {
return;
}
if (currentPath == null) {
currentPath = new Line(objectPosition.clone(), nearestIntersection);
}
Vector3f movementVector = nearestIntersection.subtract(currentPath.getOrigin());
float distance = movementVector.length();
float remainingMovementDistance = game.getSelectedFighter().getRemainingMovementDistance();
if (distance > remainingMovementDistance) {
movementVector.normalizeLocal().multLocal(remainingMovementDistance);
}
currentPath.getDirection().set(currentPath.getOrigin().add(movementVector));
}
private void updateCurrentPathBox() {
CollisionShape boxCollisionShape = getPathBoxCollisionShapeOf(selectedFighterNode, currentPath);
GhostControl physicsGhostObject;
if (currentPathBoxNode == null) {
physicsGhostObject = new GhostControl(boxCollisionShape);
currentPathBoxNode = new Node("currentPathBoxNode");
currentPathBoxNode.addControl(physicsGhostObject);
getPhysicsSpace().add(physicsGhostObject);
}
else {
currentPathBoxNode.detachChildNamed("currentPathBoxGeometry");
physicsGhostObject = currentPathBoxNode.getControl(GhostControl.class);
physicsGhostObject.setCollisionShape(boxCollisionShape);
}
currentPath.setValid(true);
currentPathBoxNode.attachChild(getPathBoxGeometryFor(selectedFighterNode));
rootNode.attachChild(currentPathBoxNode);
Vector3f halfExtents = getHalfExtentsOf(selectedFighterNode);
Vector3f upTranslation = new Vector3f(0, halfExtents.getY(), 0);
Vector3f vector = currentPath.getOrigin().add(currentPath.getVector().mult(0.5f)).addLocal(upTranslation);
currentPathBoxNode.setLocalTranslation(vector);
currentPathBoxNode.lookAt(currentPath.getDirection().add(upTranslation), Vector3f.UNIT_Y);
selectedFighterNode.setLocalTranslation(currentPath.getDirection());
lockPhysics();
}
private void setUpTargeting() {
Fighter selectedFighter = game.getSelectedFighter();
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
Ammunition currentAmmunition = weapon.getCurrentAmmunition();
if (currentAmmunition.isTemplated()) {
Line line = null;
if (weapon.isTargeted()) {
if (getFighterNodeUnderCursor() == null) {
removeTargetingFacilities();
return;
}
updateCurrentLineOfSight();
updateCurrentLineOfSightLine();
updateCurrentLineOfSightBox();
line = currentLineOfSight;
}
else {
Vector3f upTranslation = new Vector3f(0, selectedFighter.getBaseRadius() * 1.5f, 0);
line = new Line(selectedFighterNode.getLocalTranslation().add(upTranslation), getSceneryCollisionPoint().add(upTranslation));
}
if (currentTemplateNode == null) {
currentTemplateNode = TemplateNode.createTemplateNode(assetManager, currentAmmunition);
}
Vector3f lineOfSightVector = line.getDirection().subtract(line.getOrigin());
lineOfSightVector = lineOfSightVector.normalize();
if (weapon.isTemplateAttached()) {
currentTemplateNode.rotateUpTo(lineOfSightVector);
currentTemplateNode.setLocalTranslation(line.getOrigin());
}
else {
currentTemplateNode.setLocalTranslation(line.getDirection());
}
rootNode.detachChildNamed("currentTemplateNode");
rootNode.attachChild(currentTemplateNode);
}
else {
if (getFighterNodeUnderCursor() != null) {
updateCurrentLineOfSight();
updateCurrentLineOfSightLine();
updateCurrentLineOfSightBox();
}
else {
removeTargetingFacilities();
}
}
}
private void updateCurrentLineOfSight() {
Vector3f sourceCenter = selectedFighterNode.getChild("collisionShapeNode").getWorldTranslation().clone().add(0, selectedFighterNode.getCenterToHeadOffset(), 0);
Vector3f targetCenter = getFighterNodeUnderCursor().getChild("collisionShapeNode").getWorldTranslation().clone();
if (currentLineOfSight == null) {
currentLineOfSight = new Line(sourceCenter, targetCenter);
}
else {
currentLineOfSight.getOrigin().set(sourceCenter);
currentLineOfSight.getDirection().set(targetCenter);
}
}
private void updateCurrentLineOfSightLine() {
Geometry lineGeometry = (Geometry) rootNode.getChild("currentLineOfSightLine");
Vector3f start = currentLineOfSight.getOrigin();
Vector3f end = currentLineOfSight.getDirection();
if (lineGeometry == null) {
com.jme3.scene.shape.Line line = new com.jme3.scene.shape.Line(start, end);
lineGeometry = new Geometry("currentLineOfSightLine", line);
lineGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.SELECTED));
rootNode.attachChild(lineGeometry);
}
else {
com.jme3.scene.shape.Line line = (com.jme3.scene.shape.Line) lineGeometry.getMesh();
line.updatePoints(start, end);
}
}
private void updateCurrentLineOfSightBox() {
float lineOfSightLength = getLineLength(currentLineOfSight);
Vector3f halfExtents = new Vector3f(0.1f, 0.1f, lineOfSightLength * 0.5f);
CollisionShape boxCollisionShape = new BoxCollisionShape(halfExtents);
GhostControl physicsGhostObject;
if (currentLineOfSightBoxNode == null) {
physicsGhostObject = new GhostControl(boxCollisionShape);
currentLineOfSightBoxNode = new Node("currentLineOfSightBoxNode");
currentLineOfSightBoxNode.addControl(physicsGhostObject);
getPhysicsSpace().add(physicsGhostObject);
rootNode.attachChild(currentLineOfSightBoxNode);
}
else {
physicsGhostObject = currentLineOfSightBoxNode.getControl(GhostControl.class);
physicsGhostObject.setCollisionShape(boxCollisionShape);
}
currentLineOfSight.setValid(true);
Vector3f vector = currentLineOfSight.getOrigin().add(currentLineOfSight.getVector().mult(0.5f));
currentLineOfSightBoxNode.setLocalTranslation(vector);
lockPhysics();
currentLineOfSightBoxNode.lookAt(currentLineOfSight.getDirection(), Vector3f.UNIT_Y);
}
private float getLineLength(Line line) {
return line.getOrigin().distance(line.getDirection());
}
private PhysicsSpace getPhysicsSpace() {
return stateManager.getState(BulletAppState.class).getPhysicsSpace();
}
private void lockPhysics() {
physicsTickLock1 = false;
physicsTickLock2 = false;
}
private boolean isPhysicsLocked() {
return !physicsTickLock1 || !physicsTickLock2;
}
private List<FighterNode> getHostileFighterNodesFrom(List<FighterNode> fighterNodes) {
List<FighterNode> hostileFighterNodes = new ArrayList<FighterNode>();
for (FighterNode fighterNode : fighterNodes) {
Fighter fighter = fighterNode.getFighter();
if (game.getHostileGangers().contains(fighter)) {
hostileFighterNodes.add(fighterNode);
}
}
return hostileFighterNodes;
}
private List<FighterNode> getFighterNodesWithLineOfSightFrom(FighterNode source, List<FighterNode> fighterNodes) {
List<FighterNode> fighterNodesWithLineOfSight = new ArrayList<FighterNode>();
List<Collidable> collidables = getBoundingVolumes();
collidables.add(getBuildingsNode());
for (FighterNode fighterNode : fighterNodes) {
if (getVisibilityInfo(source, fighterNode, collidables).getNumberOfVisiblePoints() > 0) {
fighterNodesWithLineOfSight.add(fighterNode);
}
}
return fighterNodesWithLineOfSight;
}
private FighterNode getNearestFighterNodeFrom(FighterNode source, List<FighterNode> fighterNodes) {
float nearestDistance = Float.MAX_VALUE;
FighterNode nearestFighterNode = null;
for (FighterNode fighterNode : fighterNodes) {
float distance = source.getLocalTranslation().distance(fighterNode.getLocalTranslation());
if (distance < nearestDistance) {
nearestDistance = distance;
nearestFighterNode = fighterNode;
}
}
return nearestFighterNode;
}
private List<FighterNode> getFighterNodesWithinDistance(FighterNode fighterNode, float maxDistance) {
List<FighterNode> otherFighterNodes = new ArrayList<FighterNode>();
Fighter fighter = fighterNode.getFighter();
for (FighterNode otherFighterNode : fighterNodes) {
if (otherFighterNode == fighterNode) {
continue;
}
Fighter otherFighter = otherFighterNode.getFighter();
float distance = fighterNode.getLocalTranslation().distance(otherFighterNode.getLocalTranslation());
distance -= fighter.getBaseRadius() + otherFighter.getBaseRadius();
if (distance < maxDistance) {
otherFighterNodes.add(otherFighterNode);
}
}
return otherFighterNodes;
}
private List<FighterNode> getFighterNodesUnderTemplate(TemplateNode templateNode, List<FighterNode> fighterNodes) {
List<FighterNode> fighterNodesUnderTemplate = new ArrayList<FighterNode>();
for (FighterNode fighterNode : fighterNodes) {
CylinderCollisionShape shape = (CylinderCollisionShape) fighterNode.getGhostControl().getCollisionShape();
Vector3f halfExtents = shape.getHalfExtents();
Vector3f localTranslation = fighterNode.getLocalTranslation().clone();
Fighter fighter = fighterNode.getFighter();
localTranslation.y += fighter.getBaseRadius() * 1.5f;
BoundingBox boundingBox = new BoundingBox(localTranslation, halfExtents.x, halfExtents.y, halfExtents.z);
for (BoundingSphere sphere : templateNode.getBoundingSpheres()) {
if (boundingBox.intersectsSphere(sphere)) {
fighterNodesUnderTemplate.add(fighterNode);
break;
}
}
}
return fighterNodesUnderTemplate;
}
private void fireTargetedWeapon(RangeCombatWeapon weapon, int hitModifier) {
weapon.trigger();
Iterator<FighterNode> targetedFighterNodesIterator = targetedFighterNodes.iterator();
while (targetedFighterNodesIterator.hasNext()) {
FighterNode fighterNode = targetedFighterNodesIterator.next();
float distance = fighterNode.getLocalTranslation().distance(selectedFighterNode.getLocalTranslation());
if (distance > weapon.getMaximumRange()) {
Necromunda.appendToStatusMessage("Object out of range.");
targetedFighterNodesIterator.remove();
continue;
}
Fighter selectedFighter = game.getSelectedFighter();
int targetHitRoll = 7 - selectedFighter.getBallisticSkill() - weapon.getRangeModifier(distance) - hitModifier;
if (targetHitRoll >= 10) {
Necromunda.appendToStatusMessage(String.format("You need a %s to hit - impossible!", targetHitRoll));
targetedFighterNodesIterator.remove();
continue;
}
Necromunda.appendToStatusMessage(String.format("Target hit roll is %s.", targetHitRoll));
int hitRoll = Utils.rollD6();
if ((targetHitRoll > 6) && (hitRoll == 6)) {
targetHitRoll -= 3;
hitRoll = Utils.rollD6();
}
if ((hitRoll < targetHitRoll) || (hitRoll <= 1)) {
Necromunda.appendToStatusMessage(String.format("Rolled a %s and missed...", hitRoll));
shotHasMissed(weapon.isScattering());
targetedFighterNodesIterator.remove();
continue;
}
Necromunda.appendToStatusMessage(String.format("Rolled a %s and hit!", hitRoll));
fireAtTarget(hitRoll);
targetedFighterNodesIterator.remove();
}
}
private void fireAtTarget(int hitRoll) {
Fighter selectedFighter = game.getSelectedFighter();
RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();
weapon.hitRoll(hitRoll);
if (currentTemplateNode != null) {
fireTemplate(currentTemplateNode);
queueTemplateNodeForRemoval(currentTemplateNode);
}
else {
applyShotToTargets(weapon);
}
}
private void shotHasMissed(boolean isScattering) {
if (currentTemplateNode != null) {
boolean hasEffect = true;
if (isScattering) {
List<Collidable> collidables = new ArrayList<Collidable>();
collidables.add(getBuildingsNode());
hasEffect = currentTemplateNode.scatter(getLineLength(currentLineOfSight), collidables);
}
if (hasEffect) {
fireTemplate(currentTemplateNode);
}
queueTemplateNodeForRemoval(currentTemplateNode);
}
}
private void queueTemplateNodeForRemoval(TemplateNode templateNode) {
templateNodes.add(templateNode);
if (!currentTemplateNode.isTemplatePersistent()) {
templateNode.setName("temporaryTemplateNode");
TemplateRemover templateRemover = new TemplateRemover(templateNode);
templateRemovers.add(templateRemover);
}
else {
templateNode.setName("persistentTemplateNode");
}
}
private void applyShotToTargets(RangeCombatWeapon weapon) {
List<FighterNode> affectedFighterNodes = new ArrayList<FighterNode>();
FighterNode affectedFighterNode = targetedFighterNodes.get(0);
affectedFighterNodes.add(affectedFighterNode);
if (weapon.getAdditionalTargetRange() > 0) {
List<FighterNode> fighterNodesWithinRange = getFighterNodesWithinDistance(affectedFighterNode, weapon.getAdditionalTargetRange());
List<FighterNode> visibleFighterNodes = getFighterNodesWithLineOfSightFrom(selectedFighterNode, fighterNodesWithinRange);
affectedFighterNodes.addAll(visibleFighterNodes);
}
pinFighters(affectedFighterNodes);
for (FighterNode fighterNode : affectedFighterNodes) {
Fighter fighter = fighterNode.getFighter();
weapon.dealDamageTo(fighter);
}
}
private void fireTemplate(TemplateNode templateNode) {
List<FighterNode> affectedFighterNodes = getFighterNodesUnderTemplate(templateNode, fighterNodes);
pinFighters(affectedFighterNodes);
templateNode.dealDamageTo(affectedFighterNodes);
}
private void pinFighters(List<FighterNode> fighterNodes) {
for (FighterNode fighterNode : fighterNodes) {
Fighter fighter = fighterNode.getFighter();
if (fighter.isNormal()) {
fighter.setState(State.PINNED);
}
}
}
private String getStatusTextFrom(Necromunda game) {
StringBuilder statusText = new StringBuilder();
String string = String.format("Turn %s, %s\n", game.getTurn(), game.getCurrentGang().toString());
statusText.append(string);
if (game.getSelectedFighter() != null) {
Fighter ganger = (Fighter) game.getSelectedFighter();
statusText.append(String.format("%s, %s, %sFlesh Wounds: %s\n", ganger.getName(), ganger.getState(), (ganger.isWebbed() ? "Webbed, " : ""), ganger
.getFleshWounds()));
RangeCombatWeapon weapon = ganger.getSelectedRangeCombatWeapon();
if (weapon != null) {
String broken = weapon.isBroken() ? " (Broken), " : ", ";
String mode = (weapon.getAmmunitions().size() > 1) ? String.format(" Ammunition: %s, ", weapon.getCurrentAmmunition().getName()) : "";
statusText.append(String.format("%s%s%s%s\n", weapon, broken, mode, weapon.getProfileString()));
}
else {
statusText.append("No weapon selected\n");
}
}
else {
statusText.append("\n\n");
}
if (Necromunda.getStatusMessage() != null) {
statusText.append(String.format("%s\n", Necromunda.getStatusMessage()));
}
else {
statusText.append("\n");
}
if (game.getPhase() != null) {
statusText.append(game.getPhase().toString());
}
else {
statusText.append(" ");
}
return statusText.toString();
}
@Override
public void simpleUpdate(float tpf) {
int millis = (int) (tpf * 1000);
Iterator<TemplateRemover> it = templateRemovers.iterator();
while (it.hasNext()) {
TemplateRemover templateRemover = it.next();
templateRemover.setTimer(templateRemover.getTimer() - millis);
if (templateRemover.getTimer() < 0) {
templateRemover.remove();
it.remove();
}
}
}
public String getTerrainType() {
return terrainType;
}
public void setTerrainType(String terrainType) {
this.terrainType = terrainType;
}
}
|
package com.wegas.core.ejb;
import com.wegas.core.event.internal.EngineInvocationEvent;
import com.wegas.core.exception.WegasException;
import com.wegas.core.persistence.AbstractEntity;
import com.wegas.core.persistence.game.GameModelContent;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.persistence.game.Script;
import com.wegas.core.persistence.variable.VariableDescriptor;
import com.wegas.core.persistence.variable.VariableInstance;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.*;
import java.util.Map.Entry;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.enterprise.event.ObserverException;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Francois-Xavier Aeberhard <[email protected]>
*/
@Stateless
@LocalBean
public class ScriptFacade implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(ScriptFacade.class);
@PersistenceContext(unitName = "wegasPU")
private EntityManager em;
@EJB
private PlayerFacade playerEntityFacade;
@EJB
private VariableDescriptorFacade variableDescriptorFacade;
@Inject
private ScriptEventFacade event;
@Inject
private RequestManager requestManager;
@Inject
Event<EngineInvocationEvent> engineInvocationEvent;
/**
*
* Fires an engineInvocationEvent, which should be intercepted to customize
* engine scope.
*
* @param script
* @param arguments
* @return
* @throws WegasException
*/
public Object eval(Script script, Map<String, AbstractEntity> arguments) throws WegasException {
if (script == null) {
return null;
}
ScriptEngine engine = requestManager.getCurrentEngine();
if (engine == null) {
ScriptEngineManager mgr = new ScriptEngineManager(); // Instantiate the corresponding script engine
try {
engine = mgr.getEngineByName(script.getLanguage());
// Invocable invocableEngine = (Invocable) engine;
} catch (NullPointerException ex) {
logger.error("Could not find language", ex.getMessage(), ex.getStackTrace());
throw new WegasException("Could not instantiate script engine for script" + script);
}
try {
engineInvocationEvent.fire(
new EngineInvocationEvent(requestManager.getPlayer(), engine));// Fires the engine invocation event, to allow extensions
} catch (ObserverException ex) {
throw (WegasException) ex.getCause();
}
requestManager.setCurrentEngine(engine);
}
for (Entry<String, AbstractEntity> arg : arguments.entrySet()) { // Inject the arguments
engine.put(arg.getKey(), arg.getValue());
}
try {
engine.put(ScriptEngine.FILENAME, script.getContent()); //@TODO: JAVA 8 filename in scope
return engine.eval(script.getContent());
} catch (ScriptException ex) {
// requestManager.addException(
// new com.wegas.core.exception.ScriptException(script.getContent(), ex.getLineNumber(), ex.getMessage()));
// throw new ScriptException(ex.getMessage(), script.getContent(), ex.getLineNumber());
throw new com.wegas.core.exception.ScriptException(script.getContent(), ex.getLineNumber(), ex.getMessage());
}
}
/**
* Default customization of our engine: inject the script library, the root
* variable instances and some libraries.
*
* @param evt
*/
public void onEngineInstantiation(@Observes EngineInvocationEvent evt) {
evt.getEngine().put("self", evt.getPlayer()); // Inject current player
evt.getEngine().put("gameModel", evt.getPlayer().getGameModel()); // Inject current gameModel
evt.getEngine().put("Variable", variableDescriptorFacade); // Inject the variabledescriptor facade
evt.getEngine().put("VariableDescriptorFacade", variableDescriptorFacade);// @backwardcompatibility
evt.getEngine().put("RequestManager", requestManager); // Inject the request manager
evt.getEngine().put("Event", event); // Inject the Event manager
event.detachAll();
this.injectStaticScript(evt);
for (Entry<String, GameModelContent> arg
: evt.getPlayer().getGameModel().getScriptLibrary().entrySet()) { // Inject the script library
evt.getEngine().put(ScriptEngine.FILENAME, "Server script " + arg.getKey()); //@TODO: JAVA 8 filename in scope
try {
evt.getEngine().eval(arg.getValue().getContent());
} catch (ScriptException ex) {
throw new com.wegas.core.exception.ScriptException("Server script " + arg.getKey(), ex.getLineNumber(), ex.getMessage());
}
}
for (VariableDescriptor vd
: evt.getPlayer().getGameModel().getChildVariableDescriptors()) { // Inject the variable instances in the script
VariableInstance vi = vd.getInstance(evt.getPlayer());
try {
evt.getEngine().put(vd.getName(), vi);
} catch (IllegalArgumentException ex) {
//logger.error("Missing name for Variable label [" + vd.getLabel() + "]");
}
}
}
/**
* Inject script files specified in GameModel's property scriptFiles into
* engine
*
* @param evt EngineInvocationEvent
* @throws ScriptException
*/
private void injectStaticScript(EngineInvocationEvent evt) {
String currentPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
Integer index = currentPath.indexOf("WEB-INF");
if (index < 1) { // @ TODO find an other way to get web app root currently war packaging required.
return;
}
String root = currentPath.substring(0, index);
String[] files = new String[0];
if (evt.getPlayer().getGameModel().getProperties().getScriptUri() != null) { //@TODO : precompile? cache ?
files = evt.getPlayer().getGameModel().getProperties().getScriptUri().split(";");
}
for (String f : getJavaScriptsRecursively(root, files)) {
evt.getEngine().put(ScriptEngine.FILENAME, "Script file " + f); //@TODO: JAVA 8 filename in scope
try {
evt.getEngine().eval(new java.io.FileReader(f));
logger.info("File " + f + " successfully injected");
} catch (FileNotFoundException ex) {
logger.warn("File " + f + " was not found");
} catch (ScriptException ex) {
throw new com.wegas.core.exception.ScriptException(f, ex.getLineNumber(), ex.getMessage());
}
}
}
/**
* extract all javascript files from the files list. If one of the files is
* a directory, recurse through it and fetch *.js.
*
* Note: When iterating, if a script and its minified version stands in the directory,
* the minified is ignored (debugging purpose)
*
* @param root
* @param files
* @return
*/
private Collection<String> getJavaScriptsRecursively(String root, String[] files) {
List<File> queue = new LinkedList<>();
List<String> result = new LinkedList<>();
for (String file : files) {
File f = new File(root + "/" + file);
// Put directories in the recurse queue and files in result list
// this test may look redundant with the one done bellow... but...
// actually, it ensures a -min.js script given by the user is never ignored
if (f.isDirectory()) {
queue.add(f);
} else {
result.add(f.getPath());
}
}
while (queue.size() > 0) {
File current = queue.remove(0);
System.out.flush();
if (!Files.isSymbolicLink(current.toPath()) && current.canRead()) {
if (current.isDirectory()) {
File[] listFiles = current.listFiles();
if (listFiles == null) {
break;
} else {
queue.addAll(Arrays.asList(listFiles));
}
} else {
if (current.isFile()
&& current.getName().endsWith(".js") // Is a javascript
&& !isMinifedDuplicata(current)) { // avoid minified version when original exists
result.add(current.getPath());
}
}
}
}
return result;
}
/**
* check if the given file is a minified version of an existing one
*
* @param file
* @return
*/
private boolean isMinifedDuplicata(File file) {
if (file.getName().endsWith("-min.js")) {
String siblingPath = file.getPath().replaceAll("-min.js$", ".js");
File f = new File(siblingPath);
return f.exists();
}
return false;
}
/**
*
* @param scripts
* @param arguments
* @return
* @throws WegasException
*/
public Object eval(List<Script> scripts, Map<String, AbstractEntity> arguments) throws WegasException {
Object ret;
if (scripts.isEmpty()) {
return null;
}
while (scripts.remove(null)) {
} //remove null scripts
StringBuilder buf = new StringBuilder();
for (Script s : scripts) { // Evaluate each script
try {
buf.append(s.getContent());
buf.append(";");
} catch (NullPointerException ex) {
//script does not exist
}
//result = engine.eval(s.getContent());
}
return this.eval(new Script(buf.toString()));
}
/**
*
* @param scripts
* @return
* @throws WegasException
*/
public Object eval(List<Script> scripts) throws WegasException {
return this.eval(scripts, new HashMap<String, AbstractEntity>());
}
/**
*
* @param p
* @param s
* @return
* @throws WegasException
*/
public Object eval(Player p, Script s) throws WegasException {
requestManager.setPlayer(p);
return this.eval(s);
}
/**
*
* @param p
* @param s
* @return
* @throws WegasException
*/
public Object eval(Player p, List<Script> s) throws WegasException {
requestManager.setPlayer(p);
return this.eval(s);
}
/**
*
* @param player
* @param s
* @param arguments
* @return
* @throws WegasException
*/
public Object eval(Player player, Script s, Map<String, AbstractEntity> arguments) throws WegasException {
requestManager.setPlayer(player);
return this.eval(s, arguments);
}
/**
*
* @param player
* @param scripts
* @param arguments
* @return
* @throws WegasException
*/
public Object eval(Player player, List<Script> scripts, Map<String, AbstractEntity> arguments) throws WegasException {
requestManager.setPlayer(player); // Set up request's execution context
return this.eval(scripts, arguments);
}
/**
*
* @param playerId
* @param s
* @return
* @throws WegasException
*/
public Object eval(Long playerId, Script s) throws WegasException {
requestManager.setPlayer(playerEntityFacade.find(playerId));
return this.eval(s);
}
/**
*
* @param s
* @return
* @throws WegasException
*/
public Object eval(Script s) throws WegasException {
return this.eval(s, new HashMap<String, AbstractEntity>());
}
}
|
package joliex.wsdl;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Francesco
*/
public enum NameSpacesEnum {
XML_SCH("xs","http:
SOAP("soap","http://schemas.xmlsoap.org/wsdl/soap/"),
SOAPoverHTTP("soapOhttp","http://schemas.xmlsoap.org/soap/http/"),
WSDL("wsdl","http://schemas.xmlsoap.org/wsdl/");
private String prefix;
private String nameSpaceURI;
NameSpacesEnum(String prefix,String nameSpaceURI){
this.prefix=prefix;
this.nameSpaceURI=nameSpaceURI;
}
/**
* @return the nameSpace
*/ public String getNameSpaceURI()
{
return nameSpaceURI;
}
/**
* @return the prefix
*/ public String getNameSpacePrefix()
{
return prefix;
}
}
|
package de.fosd.jdime.gui;
import javafx.application.Application;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.regex.Pattern;
/**
* A simple JavaFX GUI for JDime.
*/
public final class GUI extends Application {
private static final String TITLE = "JDime";
private static final String JDIME_CONF_FILE = "JDime.properties";
private static final String JDIME_DEFAULT_ARGS_KEY = "DEFAULT_ARGS";
private static final String JDIME_DEFAULT_LEFT_KEY = "DEFAULT_LEFT";
private static final String JDIME_DEFAULT_BASE_KEY = "DEFAULT_BASE";
private static final String JDIME_DEFAULT_RIGHT_KEY = "DEFAULT_RIGHT";
private static final String JDIME_EXEC_KEY = "JDIME_EXEC";
private static final String JVM_DEBUG_PARAMS = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005";
private static final String STARTSCRIPT_JVM_ENV_VAR = "JAVA_OPTS";
public static final Pattern DUMP_GRAPH = Pattern.compile(".*-mode\\s+dumpgraph.*");
@FXML
TextArea output;
@FXML
TextField left;
@FXML
TextField base;
@FXML
TextField right;
@FXML
TextField jDime;
@FXML
TextField cmdArgs;
@FXML
CheckBox debugMode;
@FXML
private TabPane tabPane;
@FXML
private Tab outputTab;
@FXML
private GridPane controlsPane;
@FXML
private Button historyPrevious;
@FXML
private Button historyNext;
private Properties config;
private File lastChooseDir;
private List<TextField> textFields;
private IntegerProperty historyIndex;
private ObservableList<State> history;
private SimpleListProperty<State> historyListProp;
private State inProgress;
/**
* Launches the GUI with the given <code>args</code>.
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource(getClass().getSimpleName() + ".fxml"));
loader.setController(this);
Parent root = loader.load();
Scene scene = new Scene(root);
textFields = Arrays.asList(left, base, right, jDime, cmdArgs);
historyIndex = new SimpleIntegerProperty(0);
history = FXCollections.observableArrayList();
historyListProp = new SimpleListProperty<>(history);
config = new Properties();
BooleanBinding noPrev = historyListProp.emptyProperty().or(historyIndex.isEqualTo(0));
BooleanBinding noNext = historyListProp.emptyProperty().or(historyIndex.greaterThanOrEqualTo(historyListProp.sizeProperty()));
historyNext.disableProperty().bind(noNext);
historyPrevious.disableProperty().bind(noPrev);
loadConfigFile();
loadDefaults();
primaryStage.setTitle(TITLE);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* Loads default values for the <code>TextField</code>s from the config file.
*/
private void loadDefaults() {
getConfig(JDIME_EXEC_KEY).ifPresent(s -> jDime.setText(s.trim()));
getConfig(JDIME_DEFAULT_ARGS_KEY).ifPresent(s -> cmdArgs.setText(s.trim()));
getConfig(JDIME_DEFAULT_LEFT_KEY).ifPresent(left::setText);
getConfig(JDIME_DEFAULT_BASE_KEY).ifPresent(base::setText);
getConfig(JDIME_DEFAULT_RIGHT_KEY).ifPresent(right::setText);
}
/**
* Checks whether the current working directory contains a file called {@value #JDIME_CONF_FILE} and if so loads
* the mappings contained in it into the <code>Properties</code> instance <code>config</code> which is used
* by {@link #getConfig(String)}.
*/
private void loadConfigFile() {
File configFile = new File(JDIME_CONF_FILE);
if (configFile.exists()) {
Charset cs = StandardCharsets.UTF_8;
try {
config.load(new InputStreamReader(new BufferedInputStream(new FileInputStream(configFile)), cs));
} catch (IOException e) {
System.err.println("Could not load " + configFile);
System.err.println(e.getMessage());
}
}
}
/**
* Checks whether the file {@value #JDIME_CONF_FILE} in the current directory contains a mapping for the given key
* and if so returns the mapped value. If the file contains no mapping the system environment variables are checked.
* If no environment variable named <code>key</code> exists an empty <code>Optional</code> will be returned.
*
* @param key the configuration key
* @return optionally the mapped value
*/
private Optional<String> getConfig(String key) {
String value = config.getProperty(key, System.getProperty(key));
if (value != null) {
return Optional.of(value);
} else {
return Optional.empty();
}
}
/**
* Shows a <code>FileChooser</code> and returns the chosen <code>File</code>. Sets <code>lastChooseDir</code>
* to the parent file of the returned <code>File</code>.
*
* @param event
* the <code>ActionEvent</code> that occurred in the action listener
*
* @return the chosen <code>File</code> or <code>null</code> if the dialog was closed
*/
private File getChosenFile(ActionEvent event) {
FileChooser chooser = new FileChooser();
Window window = ((Node) event.getTarget()).getScene().getWindow();
if (lastChooseDir != null && lastChooseDir.isDirectory()) {
chooser.setInitialDirectory(lastChooseDir);
}
return chooser.showOpenDialog(window);
}
/**
* Called when the 'Choose' button for the left file is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseLeft(ActionEvent event) {
File leftArtifact = getChosenFile(event);
if (leftArtifact != null) {
lastChooseDir = leftArtifact.getParentFile();
left.setText(leftArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the base file is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseBase(ActionEvent event) {
File baseArtifact = getChosenFile(event);
if (baseArtifact != null) {
lastChooseDir = baseArtifact.getParentFile();
base.setText(baseArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the right file is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseRight(ActionEvent event) {
File rightArtifact = getChosenFile(event);
if (rightArtifact != null) {
lastChooseDir = rightArtifact.getParentFile();
right.setText(rightArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the JDime executable is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseJDime(ActionEvent event) {
File jDimeBinary = getChosenFile(event);
if (jDimeBinary != null) {
lastChooseDir = jDimeBinary.getParentFile();
jDime.setText(jDimeBinary.getAbsolutePath());
}
}
/**
* Called when the '>' button for the history is clicked.
*/
public void historyNext() {
historyIndex.setValue(historyIndex.get() + 1);
if (historyIndex.get() == history.size()) {
inProgress.applyTo(this);
} else {
history.get(historyIndex.get()).applyTo(this);
}
}
/**
* Called when the '<' button for the history is clicked.
*/
public void historyPrevious() {
if (historyIndex.get() == history.size()) {
inProgress = State.of(this);
}
historyIndex.setValue(historyIndex.get() - 1);
history.get(historyIndex.get()).applyTo(this);
}
/**
* Called when the 'Run' button is clicked.
*/
public void runClicked() {
boolean valid = textFields.stream().allMatch(tf -> {
if (tf == cmdArgs) {
return true;
}
if (tf == base) {
return tf.getText().trim().isEmpty() || new File(tf.getText()).exists();
}
return new File(tf.getText()).exists();
});
if (!valid) {
return;
}
controlsPane.setDisable(true);
Task<String> jDimeExec = new Task<String>() {
@Override
protected String call() throws Exception {
ProcessBuilder builder = new ProcessBuilder();
List<String> command = new ArrayList<>();
command.add(jDime.getText());
command.addAll(Arrays.asList(cmdArgs.getText().trim().split("\\s+")));
command.add(left.getText());
command.add(base.getText());
command.add(right.getText());
builder.command(command);
File workingDir = new File(jDime.getText()).getParentFile();
if (workingDir != null && workingDir.exists()) {
builder.directory(workingDir);
}
if (debugMode.isSelected()) {
builder.environment().put(STARTSCRIPT_JVM_ENV_VAR, JVM_DEBUG_PARAMS);
}
Process process = builder.start();
StringBuilder text = new StringBuilder();
Charset cs = StandardCharsets.UTF_8;
try (BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream(), cs))) {
r.lines().forEach(line -> {
text.append(line).append(System.lineSeparator());
updateMessage(text.toString());
});
}
process.waitFor();
return text.toString();
}
};
jDimeExec.messageProperty().addListener((observable, oldValue, newValue) -> {
output.setText(newValue);
});
jDimeExec.setOnSucceeded(event -> {
boolean dumpGraph = DUMP_GRAPH.matcher(cmdArgs.getText()).matches();
if (dumpGraph) {
GraphvizParser parser = new GraphvizParser(jDimeExec.getValue());
parser.setOnSucceeded(roots -> addTabs(parser.getValue()));
new Thread(parser).start();
}
State currentState = State.of(GUI.this);
if (history.isEmpty() || !history.get(history.size() - 1).equals(currentState)) {
history.add(currentState);
historyIndex.setValue(history.size());
}
controlsPane.setDisable(false);
});
new Thread(jDimeExec).start();
}
/**
* Adds <code>Tab</code>s containing <code>TreeTableView</code>s for every <code>TreeDumpNode</code> root in the
* given <code>List</code>.
*
* @param roots
* the roots of the trees to display
*/
private void addTabs(List<TreeItem<TreeDumpNode>> roots) {
tabPane.getTabs().retainAll(FXCollections.singletonObservableList(outputTab));
roots.forEach(root -> tabPane.getTabs().add(getTreeTableViewTab(root)));
}
/**
* Returns a <code>Tab</code> containing a <code>TreeTableView</code> displaying the with the given
* <code>root</code>.
*
* @param root
* the root of the tree to display
* @return a <code>Tab</code> containing the tree
*/
private Tab getTreeTableViewTab(TreeItem<TreeDumpNode> root) {
TreeTableView<TreeDumpNode> tableView = new TreeTableView<>(root);
TreeTableColumn<TreeDumpNode, String> id = new TreeTableColumn<>("ID");
TreeTableColumn<TreeDumpNode, String> label = new TreeTableColumn<>("AST Type");
tableView.setRowFactory(param -> {
TreeTableRow<TreeDumpNode> row = new TreeTableRow<>();
TreeDumpNode node = row.getItem();
if (node == null) {
return row;
}
String color = node.getFillColor();
if (color != null) {
BackgroundFill fill = new BackgroundFill(Color.valueOf(color), CornerRadii.EMPTY, Insets.EMPTY);
row.setBackground(new Background(fill));
}
return row;
});
id.setCellValueFactory(param -> param.getValue().getValue().idProperty());
label.setCellValueFactory(param -> param.getValue().getValue().labelProperty());
tableView.getColumns().setAll(Arrays.asList(label, id));
return new Tab("Tree View", tableView);
}
}
|
package Distribution_DMAT;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static int a=3;
public static char[] is=new char[a*3];
//private static char[] is = new char[] { '1', '2', '4', '5', '6', '7', '8', '9','2'};
private static int total;
private static int m = 4;
public static void main(String[] args) {
for(int i=0;i<a*3;a++){
is[i]=(char)('0'+i%(a*3)+1);
}
List<Integer> iL = new ArrayList<Integer>();
new Test().plzh("", iL, m);
System.out.println("total : " + total);
}
private void plzh(String s, List<Integer> iL, int m) {
if(m == 0) {
System.out.println(s);
total++;
return;
}
List<Integer> iL2;
for(int i = 0; i < is.length; i++) {
iL2 = new ArrayList<Integer>();
iL2.addAll(iL);
if(!iL.contains(i)) {
String str = s + is[i];
iL2.add(i);
plzh(str, iL2, m-1);
}
}
}
}
|
package com.lmn.Arbiter_Android.Activities;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import com.lmn.Arbiter_Android.ArbiterProject;
import com.lmn.Arbiter_Android.ArbiterState;
import com.lmn.Arbiter_Android.InsertProjectHelper;
import com.lmn.Arbiter_Android.OOMWorkaround;
import com.lmn.Arbiter_Android.R;
import com.lmn.Arbiter_Android.About.About;
import com.lmn.Arbiter_Android.ConnectivityListeners.SyncConnectivityListener;
import com.lmn.Arbiter_Android.CordovaPlugins.ArbiterCordova;
import com.lmn.Arbiter_Android.DatabaseHelpers.ApplicationDatabaseHelper;
import com.lmn.Arbiter_Android.DatabaseHelpers.ProjectDatabaseHelper;
import com.lmn.Arbiter_Android.DatabaseHelpers.TableHelpers.ControlPanelHelper;
import com.lmn.Arbiter_Android.DatabaseHelpers.TableHelpers.SyncTableHelper;
import com.lmn.Arbiter_Android.Dialog.ArbiterDialogs;
import com.lmn.Arbiter_Android.Dialog.Dialogs.FailedSyncHelper;
import com.lmn.Arbiter_Android.Dialog.Dialogs.InsertFeatureDialog;
import com.lmn.Arbiter_Android.Dialog.ProgressDialog.SyncProgressDialog;
import com.lmn.Arbiter_Android.GeometryEditor.GeometryEditor;
import com.lmn.Arbiter_Android.Map.Map;
import com.lmn.Arbiter_Android.Notifications.Sync;
import com.lmn.Arbiter_Android.OnReturnToMap.OnReturnToMap;
import com.lmn.Arbiter_Android.OnReturnToMap.ReturnToMapJob;
import com.lmn.Arbiter_Android.ProjectStructure.ProjectStructure;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
public class MapActivity extends FragmentActivity implements CordovaInterface,
Map.MapChangeListener, Map.CordovaMap, HasThreadPool{
private ArbiterDialogs dialogs;
private String TAG = "MAP_ACTIVITY";
private ArbiterProject arbiterProject;
private InsertProjectHelper insertHelper;
private MapChangeHelper mapChangeHelper;
private IncompleteProjectHelper incompleteProjectHelper;
private boolean menuPrepared;
@SuppressWarnings("unused")
private SyncConnectivityListener syncConnectivityListener;
private NotificationBadge notificationBadge;
// For CORDOVA
private CordovaWebView cordovaWebView;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private CordovaPlugin activityResultCallback;
protected boolean activityResultKeepRunning;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
private FailedSyncHelper failedSyncHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
Config.init(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Init(savedInstanceState);
this.keepRunning = this.getBooleanProperty("KeepRunning", true);
dialogs = new ArbiterDialogs(getApplicationContext(), getResources(), getSupportFragmentManager());
cordovaWebView = (CordovaWebView) findViewById(R.id.webView1);
cordovaWebView.loadUrl(ArbiterCordova.mainUrl, 5000);
mapChangeHelper = new MapChangeHelper(this,
cordovaWebView, incompleteProjectHelper);
}
private String getProjectPath(){
String projectName = ArbiterProject.getArbiterProject()
.getOpenProject(this);
return ProjectStructure.getProjectPath(projectName);
}
private SQLiteDatabase getProjectDatabase(){
return ProjectDatabaseHelper.getHelper(getApplicationContext(),
getProjectPath(), false).getWritableDatabase();
}
private void Init(Bundle savedInstanceState){
getProjectStructure();
InitApplicationDatabase();
InitArbiterProject();
setListeners();
clearControlPanelKVP();
this.failedSyncHelper =
new FailedSyncHelper(this, getProjectDatabase());
this.failedSyncHelper.checkIncompleteSync();
}
private void clearControlPanelKVP(){
ControlPanelHelper helper = new ControlPanelHelper(this);
helper.clearControlPanel();
}
private void InitApplicationDatabase(){
ApplicationDatabaseHelper.
getHelper(getApplicationContext());
}
private void getProjectStructure(){
ProjectStructure.getProjectStructure();
}
private void InitArbiterProject(){
arbiterProject = ArbiterProject.getArbiterProject();
// This will also ensure that a project exists
arbiterProject.getOpenProject(this);
}
/**
* Set listeners
*/
private void setListeners(){
final MapActivity activity = this;
ImageButton layersButton = (ImageButton) findViewById(R.id.layersButton);
layersButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
if(arbiterProject != null) {
String openProject = arbiterProject.getOpenProject(activity);
if(openProject.equals(activity.getResources().getString(R.string.default_project_name))) {
// create new project
Map.getMap().createNewProject(cordovaWebView);
} else {
dialogs.showLayersDialog();
}
}
}
});
ImageButton syncButton = (ImageButton) findViewById(R.id.syncButton);
syncButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
if(makeSureNotEditing()){
SyncProgressDialog.show(activity);
Map.getMap().sync(cordovaWebView);
}
}
});
syncConnectivityListener = new SyncConnectivityListener(getApplicationContext(), syncButton);
ImageButton aoiButton = (ImageButton) findViewById(R.id.AOIButton);
aoiButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Map.getMap().zoomToAOI(cordovaWebView);
}
});
ImageButton locationButton = (ImageButton) findViewById(R.id.locationButton);
locationButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Map.getMap().zoomToCurrentPosition(cordovaWebView);
}
});
ImageButton zoomInButton = (ImageButton) findViewById(R.id.zoomInButton);
zoomInButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Map.getMap().zoomIn(cordovaWebView);
}
});
ImageButton zoomOutButton = (ImageButton) findViewById(R.id.zoomOutButton);
zoomOutButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Map.getMap().zoomOut(cordovaWebView);
}
});
initIncompleteProjectHelper();
incompleteProjectHelper.setSyncButton(syncButton);
}
// Return true if not editing
private boolean makeSureNotEditing(){
int editMode = mapChangeHelper.getEditMode();
if(editMode == GeometryEditor.Mode.OFF || editMode == GeometryEditor.Mode.SELECT){
return true;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.finish_editing_title);
builder.setMessage(R.string.finish_editing_message);
builder.setIcon(R.drawable.icon);
builder.setPositiveButton(android.R.string.ok, null);
builder.create().show();
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
public NotificationBadge getNotificationBadge(){
return this.notificationBadge;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_map, menu);
Log.w("MapActivity", "MapActivity onCreateOptionsMenu");
if(this.notificationBadge == null){
this.notificationBadge = new NotificationBadge(this, menu);
}
return true;
}
private void initIncompleteProjectHelper(){
if(incompleteProjectHelper == null){
incompleteProjectHelper = new IncompleteProjectHelper(this);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu){
if(!this.menuPrepared){
initIncompleteProjectHelper();
incompleteProjectHelper.setInsertButton(menu);
this.menuPrepared = true;
}
return true;
}
private void openInsertFeatureDialog(){
String title = getResources().getString(R.string.insert_feature_title);
String cancel = getResources().getString(android.R.string.cancel);
DialogFragment frag = InsertFeatureDialog.newInstance(title, cancel);
frag.show(getSupportFragmentManager(), InsertFeatureDialog.TAG);
}
private void startAOIActivity(){
Intent aoiIntent = new Intent(this, AOIActivity.class);
this.startActivity(aoiIntent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_new_feature:
if(makeSureNotEditing()){
openInsertFeatureDialog();
}
return true;
case R.id.action_servers:
dialogs.showServersDialog();
return true;
case R.id.action_projects:
if(makeSureNotEditing()){
Map.getMap().goToProjects(cordovaWebView);
}
return true;
case R.id.action_aoi:
if(makeSureNotEditing()){
if(arbiterProject != null) {
String openProject = arbiterProject.getOpenProject(this);
if(openProject.equals(this.getResources().getString(R.string.default_project_name))) {
this.runOnUiThread(new Runnable(){
@Override
public void run(){
Activity context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.error));
builder.setIcon(context.getResources().getDrawable(R.drawable.icon));
builder.setMessage(context.getResources().getString(R.string.error_aoi_create_project));
builder.create().show();
}
});
} else {
startAOIActivity();
}
}
}
return true;
case R.id.action_about:
new About(this).displayAboutDialog();;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
if (this.cordovaWebView == null) {
return;
} else if(this.isFinishing()){
this.cordovaWebView.handlePause(this.keepRunning);
}
}
private void executeOnReturnToMapJobs(){
OnReturnToMap onReturnToMap = OnReturnToMap.getOnReturnToMap();
ReturnToMapJob job = onReturnToMap.pop();
while(job != null){
job.run(this);
job = onReturnToMap.pop();
}
}
private void checkNotificationsAreComputed(){
final Activity activity = this;
SyncProgressDialog.show(this, getResources().getString(R.string.loading),
getResources().getString(R.string.please_wait));
getThreadPool().execute(new Runnable(){
@Override
public void run(){
SyncTableHelper helper = new SyncTableHelper(getProjectDatabase());
final Sync sync = helper.checkNotificationsAreComputed();
activity.runOnUiThread(new Runnable(){
@Override
public void run(){
if(sync != null && !sync.getNotificationsAreSet()){
Map.getMap().getNotifications(cordovaWebView, Integer.toString(sync.getId()));
}else{
SyncProgressDialog.dismiss(activity);
}
}
});
}
});
}
@Override
protected void onStart(){
super.onStart();
checkNotificationsAreComputed();
}
@Override
protected void onResume(){
super.onResume();
Log.w(TAG, TAG + " onResume");
if (this.cordovaWebView == null) {
return;
}
this.cordovaWebView.handleResume(this.keepRunning,
this.activityResultKeepRunning);
// If app doesn't want to run in background
if (!this.keepRunning || this.activityResultKeepRunning) {
// Restore multitasking state
if (this.activityResultKeepRunning) {
this.keepRunning = this.activityResultKeepRunning;
this.activityResultKeepRunning = false;
}
}
executeOnReturnToMapJobs();
if(arbiterProject != null){
getThreadPool().execute(new Runnable(){
@Override
public void run(){
OOMWorkaround oom = new OOMWorkaround(getActivity());
oom.resetSavedBounds(false);
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
// Creating a project
if(ArbiterState.getArbiterState().isCreatingProject()){
SyncProgressDialog.show(getActivity());
insertHelper = new InsertProjectHelper(getActivity());
insertHelper.insert();
}
// Setting the aoi
else if(ArbiterState.getArbiterState().isSettingAOI()){
Log.w(TAG, TAG + ".onResume() setting aoi");
SyncProgressDialog.show(getActivity());
updateProjectAOI();
}else{
// Project changed
if(!arbiterProject.isSameProject(getApplicationContext())){
arbiterProject.makeSameProject();
Map.getMap().resetWebApp(cordovaWebView);
// If the user changed projects, check to
// see if the project has an aoi or not
incompleteProjectHelper.checkForAOI();
}
}
}
});
}
});
}
}
private void updateProjectAOI(){
final String aoi = ArbiterState.getArbiterState().getNewAOI();
updateProjectAOI(aoi);
}
private void updateProjectAOI(String aoi){
Map.getMap().updateAOI(cordovaWebView, aoi);
// Set the new aoi to null so the we know we're
// not setting the aoi anymore.
ArbiterState.getArbiterState().setNewAOI(null);
}
@Override
protected void onDestroy(){
super.onDestroy();
if(this.cordovaWebView != null){
Log.w("MapActivity", "MapActivity onDestroy");
cordovaWebView.handleDestroy();
}
if(this.failedSyncHelper != null){
this.failedSyncHelper.dismiss();
}
if(this.notificationBadge != null){
this.notificationBadge.onDestroy();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
/**
* Map.MapChangeListener methods
*/
public MapChangeHelper getMapChangeHelper(){
return this.mapChangeHelper;
}
/**
* Map.CordovaMap methods
*/
@Override
public CordovaWebView getWebView(){
return this.cordovaWebView;
}
/**
* Cordova methods
*/
@Override
public Activity getActivity() {
return this;
}
@Override
public ExecutorService getThreadPool() {
return threadPool;
}
@Override
public Object onMessage(String message, Object obj) {
Log.d(TAG, message);
if(message.equals("onPageFinished")){
if(obj instanceof String){
if(((String) obj).equals("about:blank")){
this.cordovaWebView.loadUrl(ArbiterCordova.mainUrl);
}
this.cordovaWebView.clearHistory();
}
}
return null;
}
@Override
public void setActivityResultCallback(CordovaPlugin plugin) {
this.activityResultCallback = plugin;
}
@Override
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
CordovaPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
/**
* Get boolean property for activity.
*
* @param name
* @param defaultValue
* @return the boolean value of the named property
*/
public boolean getBooleanProperty(String name, boolean defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
name = name.toLowerCase(Locale.getDefault());
Boolean p;
try {
p = (Boolean) bundle.get(name);
} catch (ClassCastException e) {
String s = bundle.get(name).toString();
if ("true".equals(s)) {
p = true;
}
else {
p = false;
}
}
if (p == null) {
return defaultValue;
}
return p.booleanValue();
}
}
|
package com.sun.star.wizards.web.export;
import com.sun.star.beans.PropertyValue;
import com.sun.star.document.MacroExecMode;
import com.sun.star.document.UpdateDocMode;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XStorable;
import com.sun.star.io.IOException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.XCloseable;
import com.sun.star.wizards.common.Desktop;
import com.sun.star.wizards.common.FileAccess;
import com.sun.star.wizards.common.Properties;
import com.sun.star.wizards.document.OfficeDocument;
import com.sun.star.wizards.text.TextDocument;
import com.sun.star.wizards.web.data.CGArgument;
import com.sun.star.wizards.web.data.CGDocument;
import com.sun.star.wizards.web.data.CGExporter;
import com.sun.star.wizards.web.data.TypeDetection;
/**
*
* @author rpiterman
*/
public abstract class AbstractExporter implements Exporter {
protected CGExporter exporter;
protected FileAccess fileAccess;
protected void storeToURL(Object officeDocument, Properties props, String targetUrl, String filterName, PropertyValue[] filterData)
throws IOException {
props = new Properties();
props.put("FilterName", filterName);
if (filterData.length>0)
props.put("FilterData", filterData);
XStorable xs = ((XStorable)UnoRuntime.queryInterface(XStorable.class,officeDocument));
PropertyValue[] o = props.getProperties();
xs.storeToURL(targetUrl, o);
}
protected void storeToURL(Object officeDocument, String targetUrl, String filterName, PropertyValue[] filterData)
throws IOException {
storeToURL(officeDocument, new Properties(), targetUrl, filterName, filterData);
}
protected void storeToURL(Object officeDocument, String targetUrl, String filterName )
throws IOException {
storeToURL(officeDocument, new Properties(), targetUrl, filterName, new PropertyValue[0]);
}
protected String getArgument(String name, CGExporter p) {
return ((CGArgument)p.cp_Arguments.getElement(name)).cp_Value;
}
protected Object openDocument(CGDocument doc, XMultiServiceFactory xmsf)
throws com.sun.star.io.IOException
{
Object document = null;
//open the document.
try {
XDesktop desktop = Desktop.getDesktop(xmsf);
Properties props = new Properties();
props.put("Hidden", Boolean.TRUE);
props.put("MacroExecutionMode", new Short(MacroExecMode.NEVER_EXECUTE));
props.put( "UpdateDocMode", new Short(UpdateDocMode.NO_UPDATE));
document = (
(XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class,
desktop)).loadComponentFromURL(
doc.cp_URL,
"_blank",
0,
props.getProperties());
} catch (com.sun.star.lang.IllegalArgumentException iaex) {
}
//try to get the number of pages in the document;
try {
pageCount(doc,document);
}
catch (Exception ex) {
//Here i do nothing since pages is not *so* important.
}
return document;
}
protected void closeDocument(Object doc,XMultiServiceFactory xmsf) {
/*OfficeDocument.dispose(
xmsf,
(XComponent) UnoRuntime.queryInterface(XComponent.class, doc));*/
try {
XCloseable xc = (XCloseable)UnoRuntime.queryInterface(XCloseable.class, doc);
xc.close(false);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void pageCount(CGDocument doc, Object document) {
if (doc.appType.equals(TypeDetection.WRITER_DOC))
doc.pages = TextDocument.getPageCount(document);
else if (doc.appType.equals(TypeDetection.IMPRESS_DOC))
doc.pages = OfficeDocument.getSlideCount(document);
else if (doc.appType.equals(TypeDetection.DRAW_DOC))
doc.pages = OfficeDocument.getSlideCount(document);
}
public void init(CGExporter exporter_) {
exporter = exporter_;
}
protected FileAccess getFileAccess(XMultiServiceFactory xmsf) {
if ( fileAccess == null )
try {
fileAccess = new FileAccess(xmsf);
}
catch (Exception ex) {}
return fileAccess;
}
protected void calcFileSize(CGDocument doc, String url, XMultiServiceFactory xmsf) {
/*if the exporter exports to a
* binary format, get the size of the destination.
*/
if (exporter.cp_Binary)
doc.sizeBytes = getFileAccess(xmsf).getSize(url);
}
}
|
package org._3pq.jgrapht.graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org._3pq.jgrapht.DirectedGraph;
import org._3pq.jgrapht.Edge;
import org._3pq.jgrapht.EdgeFactory;
import org._3pq.jgrapht.Graph;
import org._3pq.jgrapht.ListenableGraph;
import org._3pq.jgrapht.UndirectedGraph;
import org._3pq.jgrapht.event.GraphEdgeChangeEvent;
import org._3pq.jgrapht.event.GraphListener;
import org._3pq.jgrapht.event.GraphVertexChangeEvent;
/**
* A subgraph is a graph that has a subset of vertices and a subset of edges
* with respect to some base graph. More formally, a subgraph G(V,E) that is
* based on a base graph Gb(Vb,Eb) satisfies the following <b><i>subgraph
* property</i></b>: V is a subset of Vb and E is a subset of Eb. Other than
* this property, a subgraph is a graph with any respect and fully complies
* with the <code>Graph</code> interface.
*
* <p>
* If the base graph is a {@link org._3pq.jgrapht.ListenableGraph}, the
* subgraph becomes a "live-window" on the the base graph and guarantees the
* subgraph property. If an edge or a vertex is removed from the base graph,
* it is automatically removed from the subgraph. Subgraph listeners are
* informed on such removal only if it results in a cascaded removal from the
* subgraph. If edges or vertices are added to the base graph, the subgraph
* remains unaffected.
* </p>
*
* <p>
* If the base graph is <i>not</i> a ListenableGraph, then the subgraph
* property cannot be guaranteed. If edges or vertices are removed from the
* base graph, they are <i>not</i> removed from the subgraph.
* </p>
*
* <p>
* Modifications to Subgraph are allowed as long as the subgraph property is
* maintained. Addition of vertices or edges are allowed as long as they also
* exist in the base graph. Removal of vertices or edges is always allowed.
* The base graph is <i>never</i> affected by any modification made to the
* subgraph.
* </p>
*
* <p>
* PERFORMANCE NOTE: The intention of Subgraph is to provide a "window" on a
* base graph, so that changes made to vertex instances or to edge instances
* in the subgraph are immediately reflected in the base graph, and vice
* versa. For that to happen, vertices and edges of the subgraph must be
* reference-equal (and not only value-equal) to their respective ones in the
* base graph. By default, this class verifies that this reference-equality is
* maintained, but at a performance cost. You can avoid this cost by setting
* the verifyIntegrity flag off. However, you must <i>exercise care</i> and
* make sure that all vertices or edges you add to the subgraph are
* reference-equal to the ones contained in the base graph.
* </p>
*
* <p>
* At the time of writing, there is no easy and performance-friendly way to
* programmatically ensure the reference-equality requirement: there is a
* design flaw in the <code>java.util.Set</code> interface in that it provides
* no way of obtaining a reference to an object already contained in a Set. If
* fixed in the future the verifyIntegrity flag could be eliminated.
* </p>
*
* @author Barak Naveh
*
* @see org._3pq.jgrapht.Graph
* @see java.util.Set
* @since Jul 18, 2003
*/
public class Subgraph extends AbstractGraph {
private static final String REF_NOT_EQUAL_TO_BASE =
"value-equal but not reference equal to base graph";
private static final String NO_SUCH_EDGE_IN_BASE =
"no such edge in base graph";
private static final String NO_SUCH_VERTEX_IN_BASE =
"no such vertex in base graph";
Set m_edgeSet = new HashSet( ); // friendly to improve performance
Set m_vertexSet = new HashSet( ); // friendly to improve performance
private transient Set m_unmodifiableEdgeSet = null;
private transient Set m_unmodifiableVertexSet = null;
private Graph m_base;
private boolean m_verifyIntegrity = true;
/**
* Creates a new Subgraph.
*
* @param base the base (backing) graph on which the subgraph will be
* based.
* @param vertexSubset vertices to include in the subgraph. If
* <code>null</code> then all vertices are included.
* @param edgeSubset edges to in include in the subgraph. If
* <code>null</code> then all the edges whose vertices found in the
* graph are included.
*/
public Subgraph( Graph base, Set vertexSubset, Set edgeSubset ) {
super( );
m_base = base;
if( m_base instanceof ListenableGraph ) {
( (ListenableGraph) m_base ).addGraphListener( new BaseGraphListener( ) );
}
addVerticesUsingFilter( base.vertexSet( ), vertexSubset );
addEdgesUsingFilter( base.edgeSet( ), edgeSubset );
}
/**
* @see org._3pq.jgrapht.Graph#getAllEdges(Object, Object)
*/
public List getAllEdges( Object sourceVertex, Object targetVertex ) {
List edges = null;
if( containsVertex( sourceVertex ) && containsVertex( targetVertex ) ) {
edges = new ArrayList( );
List baseEdges = m_base.getAllEdges( sourceVertex, targetVertex );
for( Iterator iter = baseEdges.iterator( ); iter.hasNext( ); ) {
Edge e = (Edge) iter.next( );
if( m_edgeSet.contains( e ) ) { // add if subgraph also contains it
edges.add( e );
}
}
}
return edges;
}
/**
* @see org._3pq.jgrapht.Graph#getEdge(Object, Object)
*/
public Edge getEdge( Object sourceVertex, Object targetVertex ) {
List edges = getAllEdges( sourceVertex, targetVertex );
if( edges == null || edges.isEmpty( ) ) {
return null;
}
else {
return (Edge) edges.get( 0 );
}
}
/**
* @see org._3pq.jgrapht.Graph#getEdgeFactory()
*/
public EdgeFactory getEdgeFactory( ) {
return m_base.getEdgeFactory( );
}
/**
* Sets the the check integrity flag.
*
* <p>
* WARNING: See discussion in the class description.
* </p>
*
* @param verifyIntegrity
*
* @see Subgraph
*/
public void setVerifyIntegrity( boolean verifyIntegrity ) {
m_verifyIntegrity = verifyIntegrity;
}
/**
* Returns the value of the verifyIntegrity flag.
*
* @return the value of the verifyIntegrity flag.
*/
public boolean isVerifyIntegrity( ) {
return m_verifyIntegrity;
}
/**
* @see org._3pq.jgrapht.Graph#addEdge(Object, Object)
*/
public Edge addEdge( Object sourceVertex, Object targetVertex ) {
assertVertexExist( sourceVertex );
assertVertexExist( targetVertex );
if( !m_base.containsEdge( sourceVertex, targetVertex ) ) {
throw new IllegalArgumentException( NO_SUCH_EDGE_IN_BASE );
}
List edges = m_base.getAllEdges( sourceVertex, targetVertex );
for( Iterator iter = edges.iterator( ); iter.hasNext( ); ) {
Edge e = (Edge) iter.next( );
if( !containsEdge( e ) ) {
m_edgeSet.add( e );
return e;
}
}
return null;
}
public boolean addEdge( Edge e ) {
if( e == null ) {
throw new NullPointerException( );
}
if( !m_base.containsEdge( e ) ) {
throw new IllegalArgumentException( NO_SUCH_EDGE_IN_BASE );
}
assertVertexExist( e.getSource( ) );
assertVertexExist( e.getTarget( ) );
assertBaseContainsEdgeInstance( e );
if( containsEdge( e ) ) {
return false;
}
else {
m_edgeSet.add( e );
return true;
}
}
public boolean addVertex( Object v ) {
if( v == null ) {
throw new NullPointerException( );
}
if( !m_base.containsVertex( v ) ) {
throw new IllegalArgumentException( NO_SUCH_VERTEX_IN_BASE );
}
assertBaseContainsVertexInstance( v );
if( containsVertex( v ) ) {
return false;
}
else {
m_vertexSet.add( v );
return true;
}
}
/**
* @see org._3pq.jgrapht.Graph#containsEdge(Edge)
*/
public boolean containsEdge( Edge e ) {
return m_edgeSet.contains( e );
}
/**
* @see org._3pq.jgrapht.Graph#containsVertex(Object)
*/
public boolean containsVertex( Object v ) {
return m_vertexSet.contains( v );
}
/**
* @see UndirectedGraph#degreeOf(Object)
*/
public int degreeOf( Object vertex ) {
return ( (UndirectedGraph) m_base ).degreeOf( vertex );
}
/**
* @see org._3pq.jgrapht.Graph#edgeSet()
*/
public Set edgeSet( ) {
if( m_unmodifiableEdgeSet == null ) {
m_unmodifiableEdgeSet = Collections.unmodifiableSet( m_edgeSet );
}
return m_unmodifiableEdgeSet;
}
/**
* @see org._3pq.jgrapht.Graph#edgesOf(Object)
*/
public List edgesOf( Object vertex ) {
assertVertexExist( vertex );
ArrayList edges = new ArrayList( );
List baseEdges = m_base.edgesOf( vertex );
for( Iterator iter = baseEdges.iterator( ); iter.hasNext( ); ) {
Edge e = (Edge) iter.next( );
if( containsEdge( e ) ) {
edges.add( e );
}
}
return edges;
}
/**
* @see DirectedGraph#inDegreeOf(Object)
*/
public int inDegreeOf( Object vertex ) {
return ( (DirectedGraph) m_base ).inDegreeOf( vertex );
}
/**
* @see DirectedGraph#incomingEdgesOf(Object)
*/
public List incomingEdgesOf( Object vertex ) {
return ( (DirectedGraph) m_base ).incomingEdgesOf( vertex );
}
/**
* @see DirectedGraph#outDegreeOf(Object)
*/
public int outDegreeOf( Object vertex ) {
return ( (DirectedGraph) m_base ).outDegreeOf( vertex );
}
/**
* @see DirectedGraph#outgoingEdgesOf(Object)
*/
public List outgoingEdgesOf( Object vertex ) {
return ( (DirectedGraph) m_base ).outgoingEdgesOf( vertex );
}
/**
* NOTE: We allow to remove an edge by the specified "value-equal" edge
* that denotes it, which is not necessarily "reference-equal" to the edge
* to be removed.
*
* @see org._3pq.jgrapht.Graph#removeEdge(Edge)
*/
public boolean removeEdge( Edge e ) {
return m_edgeSet.remove( e );
}
/**
* @see org._3pq.jgrapht.Graph#removeEdge(Object, Object)
*/
public Edge removeEdge( Object sourceVertex, Object targetVertex ) {
Edge e = getEdge( sourceVertex, targetVertex );
return m_edgeSet.remove( e ) ? e : null;
}
/**
* NOTE: We allow to remove a vertex by the specified "value-equal" vertex
* that denotes it, which is not necessarily "reference-equal" to the
* vertex to be removed.
*
* @see org._3pq.jgrapht.Graph#removeVertex(Object)
*/
public boolean removeVertex( Object v ) {
// If the base graph does NOT contain v it means we are here in
// response to removal of v from the base. In such case we don't need
// to remove all the edges of v as they were already removed.
if( containsVertex( v ) && m_base.containsVertex( v ) ) {
removeAllEdges( edgesOf( v ) );
}
return m_vertexSet.remove( v );
}
/**
* @see org._3pq.jgrapht.Graph#vertexSet()
*/
public Set vertexSet( ) {
if( m_unmodifiableVertexSet == null ) {
m_unmodifiableVertexSet =
Collections.unmodifiableSet( m_vertexSet );
}
return m_unmodifiableVertexSet;
}
private void addEdgesUsingFilter( Set edgeSet, Set filter ) {
Edge e;
boolean containsVertices;
boolean edgeIncluded;
for( Iterator iter = edgeSet.iterator( ); iter.hasNext( ); ) {
e = (Edge) iter.next( );
containsVertices =
containsVertex( e.getSource( ) )
&& containsVertex( e.getTarget( ) );
// note the use of short circuit evaluation
edgeIncluded = ( filter == null ) || filter.contains( e );
if( containsVertices && edgeIncluded ) {
addEdge( e );
}
}
}
private void addVerticesUsingFilter( Set vertexSet, Set filter ) {
Object v;
for( Iterator iter = vertexSet.iterator( ); iter.hasNext( ); ) {
v = iter.next( );
// note the use of short circuit evaluation
if( filter == null || filter.contains( v ) ) {
addVertex( v );
}
}
}
private void assertBaseContainsEdgeInstance( Edge e ) {
if( !m_verifyIntegrity ) {
return;
}
List baseEdges = m_base.getAllEdges( e.getSource( ), e.getTarget( ) );
for( Iterator i = baseEdges.iterator( ); i.hasNext( ); ) {
Edge baseEdge = (Edge) i.next( );
if( e.equals( baseEdge ) ) {
if( e != baseEdge ) {
throw new IllegalArgumentException( REF_NOT_EQUAL_TO_BASE );
}
return;
}
}
}
private void assertBaseContainsVertexInstance( Object v ) {
if( !m_verifyIntegrity ) {
return;
}
for( Iterator iter = m_base.vertexSet( ).iterator( );
iter.hasNext( ); ) {
Object baseVertex = iter.next( );
if( v.equals( baseVertex ) ) {
if( v != baseVertex ) {
throw new IllegalArgumentException( REF_NOT_EQUAL_TO_BASE );
}
return;
}
}
}
/**
* An internal listener on the base graph.
*
* @author Barak Naveh
*
* @since Jul 20, 2003
*/
private class BaseGraphListener implements GraphListener {
/**
* @see GraphListener#edgeAdded(GraphEdgeChangeEvent)
*/
public void edgeAdded( GraphEdgeChangeEvent e ) {
// we don't care
}
/**
* @see GraphListener#edgeRemoved(GraphEdgeChangeEvent)
*/
public void edgeRemoved( GraphEdgeChangeEvent e ) {
Edge edge = e.getEdge( );
removeEdge( edge );
}
/**
* @see VertexSetListener#vertexAdded(GraphVertexChangeEvent)
*/
public void vertexAdded( GraphVertexChangeEvent e ) {
// we don't care
}
/**
* @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent)
*/
public void vertexRemoved( GraphVertexChangeEvent e ) {
Object vertex = e.getVertex( );
removeVertex( vertex );
}
}
}
|
package org.treeleafj.xmax.safe;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import java.util.Collection;
import java.util.Map;
/**
*
* @author leaf
*/
public class Assert {
/**
* true
*
* @param v
* @param msg
*/
public static void isTrue(boolean v, String msg, Object... t2) {
if (!v) {
throw createException(msg, t2);
}
}
/**
* null
*
* @param v
* @param msg
*/
public static void isNull(Object v, String msg, Object... t2) {
if (v != null) {
throw createException(msg, t2);
}
}
/**
* null
*
* @param v
* @param msg
*/
public static void notNull(Object v, String msg, Object... t2) {
if (v == null) {
throw createException(msg, t2);
}
}
/**
*
*
* @param v
* @param msg
*/
public static void hasText(String v, String msg, Object... t2) {
if (StringUtils.isBlank(v)) {
throw createException(msg, t2);
}
}
/**
*
*
* @param v
* @param msg
*/
public static void notBlank(String v, String msg, Object... t2) {
if (StringUtils.isBlank(v)) {
throw createException(msg, t2);
}
}
/**
* array
*
* @param s
* @param arrays
* @param msg
* @param t2
*/
public static void isOf(String s, String[] arrays, String msg, Object... t2) {
if (arrays != null) {
for (String item : arrays) {
if (StringUtils.equals(s, item)) {
return;
}
}
}
throw createException(msg, t2);
}
/**
*
*
* @param str
* @param s
* @param msg
*/
public static void notContains(String str, String s, String msg, Object... t2) {
if (StringUtils.isNotEmpty(str) && StringUtils.isNotEmpty(s) && str.contains(s)) {
throw createException(msg, t2);
}
}
/**
* //
*
* @param v
* @param msg
*/
public static void notEmpty(Object v, String msg, Object... t2) {
if (v == null) {
throw createException(msg, 52);
}
if (v instanceof String) {
if (((String) v).isEmpty()) {
throw createException(msg, t2);
}
} else if (v instanceof Collection) {
Collection c = (Collection) v;
if (c.size() <= 0) {
throw createException(msg, t2);
}
} else if (v instanceof Map) {
if (((Map) v).size() <= 0) {
throw createException(msg, t2);
}
} else if (v.getClass().isArray()) {
if (ArrayUtils.isEmpty((Object[]) v)) {
throw createException(msg, t2);
}
}
}
/**
* minmax,maxmin
*
* @param s
* @param max
* @param min
* @param message
*/
public static void isLengthBetween(String s, int max, int min, String message, Object... t2) {
if (s == null || (s.length() > max || s.length() < min)) {
throw createException(message, t2);
}
}
/**
*
*
* @param s
* @param message
*/
public static void isNumber(String s, String message, Object... t2) {
if (!NumberUtils.isCreatable(s)) {
throw createException(message, t2);
}
}
/**
*
*
* @param t1 t2,,
* @param t2 ,,t1, ,, , sl4j,
*/
private static AssertException createException(String t1, Object... t2) {
if (t2.length == 0) {
return new AssertException(t1);
} else if (t2.length == 1) {
return new AssertException(t1, t2[0].toString());
} else {
Object[] params = new Object[t2.length - 1];
System.arraycopy(t2, 1, params, 0, params.length);
FormattingTuple ft = MessageFormatter.arrayFormat(t2[0].toString(), params);
return new AssertException(t1, ft.getMessage());
}
}
}
|
package org.voltdb.iv2;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import junit.framework.TestCase;
public class Iv2TestInitiatorMailbox extends TestCase {
public void testWhereAreMyPants()
{
boolean pants = false;
assertFalse(pants);
}
// @BeforeClass
// public static void setUpBeforeClass() {
// mockVolt = mock(VoltDBInterface.class);
// VoltDB.replaceVoltDBInstanceForTest(mockVolt);
// @Before
// public void setUp() throws Exception {
// // trick to get around the real crash. This will throw a runtime exception
// // doThrow(new RuntimeException("Crash VoltDB")).when(mockVolt).ignoreCrash();
// setUpZK(1);
// zk = getClient(0);
// VoltZK.createPersistentZKNodes(zk);
// doReturn(zk).when(hm).getZK();
// // TODO: need to replace null here with PartitionClerk implementation.
// mb = new InitiatorMailbox(null, hm, 0, null);
// mb.setHSId(100);
// @After
// public void tearDown() throws Exception {
// mb.shutdown();
// tearDownZK();
// reset(hm);
// reset(mockVolt);
// private void createElectionNodes(int count, boolean isPrimary) throws Exception {
// String path = VoltZK.electionDirForPartition(0);
// try {
// hm.getZK().create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// } catch (Exception e) {}
// int sequence = 0;
// if (isPrimary) {
// sequence = 1;
// for (int i = 0; i < count - 1; i++) {
// String file = ZKUtil.joinZKPath(path, String.format("%d_%010d", i, sequence++));
// String create = hm.getZK().create(file, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// System.err.println(create);
// /**
// * @throws InterruptedException
// */
// private void generateTasks(final boolean isPrimary) throws InterruptedException {
// final CountDownLatch latch = new CountDownLatch(3);
// final Object lock = new Object();
// final AtomicLong txnId = new AtomicLong();
// Runnable r = new Runnable() {
// @Override
// public void run() {
//// latch.countDown();
//// synchronized (lock) {
//// try {
//// lock.wait();
//// } catch (InterruptedException e) {}
//// StoredProcedureInvocation procedure = new StoredProcedureInvocation();
//// procedure.setProcName("TestProc");
//// for (int i = 0; i < 1000; i++) {
//// InitiateTaskMessage message;
//// if (isPrimary) {
//// message = new InitiateTaskMessage(100, 100, -1, 0, 0, false, true, procedure);
//// } else {
//// message = new InitiateTaskMessage(100, 100, txnId.getAndIncrement(),
//// 0, 0, false, true, procedure);
//// mb.deliver(message);
// Thread thread1 = new Thread(r);
// Thread thread2 = new Thread(r);
// Thread thread3 = new Thread(r);
// thread1.start();
// thread2.start();
// thread3.start();
// // start all threads together
// latch.await();
// synchronized (lock) {
// lock.notifyAll();
// thread1.join();
// thread2.join();
// thread3.join();
// /**
// * Test 3 threads concurrently deliver 3000 initiate task messages to the
// * mailbox.
// *
// * @throws Exception
// */
// @Test
// public void testConcurrentDelivery() throws Exception {
//// createElectionNodes(2, true);
//// mb.start(2);
//// generateTasks(true);
//// /*
//// * check if the transactions are replicated to the replicas in the
//// * correct order
//// */
//// ArgumentCaptor<InitiateTaskMessage> captor = ArgumentCaptor.forClass(InitiateTaskMessage.class);
//// verify(hm, times(3000)).send(any(long[].class), captor.capture());
//// List<InitiateTaskMessage> messages = captor.getAllValues();
//// long txnId = 0;
//// for (InitiateTaskMessage task : messages) {
//// assertEquals(txnId++, task.getTransactionId());
// @Test
// public void testRespondAndTruncationPoint() throws Exception {
//// createElectionNodes(2, true);
//// mb.start(2);
//// generateTasks(true);
//// VoltTable[] results =
//// new VoltTable[] {new VoltTable(new ColumnInfo("T", VoltType.BIGINT))};
//// /*
//// * sometimes responses may come before local execution site has polled
//// * the tasks. Return responses for the first 1000 transactions from the
//// * replica
//// */
//// for (int i = 0; i < 1000; i++) {
//// InitiateTaskMessage task =
//// new InitiateTaskMessage(100, 100, i, 0, 0, false, true, null);
//// InitiateResponseMessage remoteResponse =
//// new InitiateResponseMessage(task);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// remoteResponse.setResults(resp);
//// mb.deliver(remoteResponse);
//// assertEquals(-1, ((PrimaryRole) mb.role).lastRespondedTxnId);
//// // return all responses from local execution site
//// InitiateTaskMessage localTask;
//// while ((localTask = (InitiateTaskMessage) mb.recv()) != null) {
//// InitiateResponseMessage localResponse =
//// new InitiateResponseMessage(localTask);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// localResponse.setResults(resp);
//// mb.deliver(localResponse);
//// // the first 1000 tasks should be returned to the client interface
//// ArgumentCaptor<InitiateResponseMessage> responseCaptor1 =
//// ArgumentCaptor.forClass(InitiateResponseMessage.class);
//// verify(hm, times(1000)).send(anyLong(), responseCaptor1.capture());
//// List<InitiateResponseMessage> allValues = responseCaptor1.getAllValues();
//// for (InitiateResponseMessage resp : allValues) {
//// assertTrue(resp.getTxnId() < 1000);
//// assertEquals(999, ((PrimaryRole) mb.role).lastRespondedTxnId);
//// // reset HostMessenger mock here so that we don't get previous stats
//// reset(hm);
//// /*
//// * return the rest of the responses from the replica
//// */
//// for (int i = 1000; i < 3000; i++) {
//// InitiateTaskMessage task =
//// new InitiateTaskMessage(100, 100, i, 0, 0, false, true, null);
//// InitiateResponseMessage remoteResponse =
//// new InitiateResponseMessage(task);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// remoteResponse.setResults(resp);
//// mb.deliver(remoteResponse);
//// // the remaining 2000 tasks should be returned to the client interface
//// ArgumentCaptor<InitiateResponseMessage> responseCaptor2 =
//// ArgumentCaptor.forClass(InitiateResponseMessage.class);
//// verify(hm, times(2000)).send(anyLong(), responseCaptor2.capture());
//// List<InitiateResponseMessage> remainingResponses = responseCaptor2.getAllValues();
//// for (InitiateResponseMessage resp : remainingResponses) {
//// assertTrue(Long.toString(resp.getTxnId()), resp.getTxnId() >= 1000);
//// assertTrue(resp.getTxnId() < 3000);
//// assertEquals(2999, ((PrimaryRole) mb.role).lastRespondedTxnId);
// @Test
// public void testResultLengthMismatch() throws Exception {
//// createElectionNodes(2, true);
//// mb.start(2);
//// generateTasks(true);
//// VoltTable[] results =
//// new VoltTable[] {new VoltTable(new ColumnInfo("T", VoltType.BIGINT))};
//// VoltTable[] emptyResults = new VoltTable[0];
//// // replica response
//// StoredProcedureInvocation procedure = new StoredProcedureInvocation();
//// procedure.setProcName("TestProc");
//// InitiateTaskMessage task =
//// new InitiateTaskMessage(100, 100, 0, 0, 0, false, true, procedure);
//// InitiateResponseMessage remoteResponse =
//// new InitiateResponseMessage(task);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// remoteResponse.setResults(resp);
//// mb.deliver(remoteResponse);
//// // local response
//// InitiateResponseMessage localResponse = new InitiateResponseMessage(task);
//// ClientResponseImpl resp2 = new ClientResponseImpl(ClientResponse.SUCCESS, emptyResults, "");
//// localResponse.setResults(resp2);
//// try {
//// mb.deliver(localResponse);
//// } catch (RuntimeException e) {
//// return;
//// fail("Should throw an exception earlier");
// @Test
// public void testResultMismatch() throws Exception {
//// createElectionNodes(2, true);
//// mb.start(2);
//// generateTasks(true);
//// VoltTable[] results =
//// new VoltTable[] {new VoltTable(new ColumnInfo("T", VoltType.BIGINT))};
//// VoltTable[] results2 = new VoltTable[] {new VoltTable(new ColumnInfo("A", VoltType.STRING))};
//// // replica response
//// StoredProcedureInvocation procedure = new StoredProcedureInvocation();
//// procedure.setProcName("TestProc");
//// InitiateTaskMessage task =
//// new InitiateTaskMessage(100, 100, 0, 0, 0, false, true, procedure);
//// InitiateResponseMessage remoteResponse =
//// new InitiateResponseMessage(task);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// remoteResponse.setResults(resp);
//// mb.deliver(remoteResponse);
//// // local response
//// InitiateResponseMessage localResponse = new InitiateResponseMessage(task);
//// ClientResponseImpl resp2 = new ClientResponseImpl(ClientResponse.SUCCESS, results2, "");
//// localResponse.setResults(resp2);
//// try {
//// mb.deliver(localResponse);
//// } catch (RuntimeException e) {
//// return;
//// fail("Should throw an exception earlier");
// @Test
// public void testReplicaTruncation() throws Exception {
//// createElectionNodes(2, false);
//// mb.start(2);
//// generateTasks(false);
//// // execute all transactions
//// VoltTable[] results =
//// new VoltTable[] {new VoltTable(new ColumnInfo("T", VoltType.BIGINT))};
//// InitiateTaskMessage localTask;
//// while ((localTask = (InitiateTaskMessage) mb.recv()) != null) {
//// InitiateResponseMessage localResponse =
//// new InitiateResponseMessage(localTask);
//// ClientResponseImpl resp = new ClientResponseImpl(ClientResponse.SUCCESS, results, "");
//// localResponse.setResults(resp);
//// mb.deliver(localResponse);
//// // nothing should be truncated
//// ReplicatedRole role = (ReplicatedRole) mb.role;
//// assertEquals(0, role.getOldestInFlightTxnId());
//// InitiateTaskMessage message =
//// new InitiateTaskMessage(100, 100, 3000, 0, 0, false, true, null);
//// message.setTruncationTxnId(1000);
//// mb.deliver(message);
//// // anything before transaction 1001 should be removed
//// assertEquals(1001, role.getOldestInFlightTxnId());
}
|
package org.basex.api.xmldb;
import static org.basex.Text.*;
interface BXXMLDBText {
/** DB URI. */
String DBURI = NAMESPACE + ":
/** XMLDB URI. */
String XMLDB = "xmldb:";
/** XMLDB URI. */
String XMLDBURI = XMLDB + DBURI;
/** Localhost Name. */
String LOCALHOST = "localhost:1984/";
/** Conformance Level of the implementation. */
String CONFORMANCE_LEVEL = "0";
/** Error Message. */
String ERR_URI = "Invalid URI: ";
/** Error Message. */
String ERR_PROP = "Property could not be set: ";
/** Error Message. */
String ERR_BINARY = "Binary resources not supported.";
/** Error Message. */
String ERR_TYPE = "Resource type is unknown: ";
/** Error Message. */
String ERR_EMPTY = "Resource has no contents.";
/** Error Message. */
String ERR_ID = "Resource has no ID.";
/** Error Message. */
String ERR_UNKNOWN = "Unknown Resource: ";
/** Error Message. */
String ERR_CONT = "Invalid content; string expected.";
/** Error Message. */
String ERR_NSURI = "Namespace URI is empty: ";
/** Error Message. */
String ERR_RES = "Resource not found: ";
/** Error Message. */
String ERR_ITER = "Resource pointer out of range.";
/** Error Message. */
String ERR_DOC = "Document ID cannot be retrieved from query result.";
}
|
package org.concord.energy3d.model;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import org.poly2tri.Poly2Tri;
import org.poly2tri.polygon.Polygon;
import org.poly2tri.polygon.PolygonPoint;
import org.poly2tri.position.AnyToXYTransform;
import org.poly2tri.position.XYToAnyTransform;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import com.ardor3d.bounding.CollisionTreeManager;
import com.ardor3d.image.Texture;
import com.ardor3d.image.Image.Format;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.MaterialState.ColorMaterial;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.geom.BufferUtils;
public class Wall extends HousePart {
private double wallHeight = 0.8f;
private double wallThickness = 0.1;
private ArrayList<HousePart> children = new ArrayList<HousePart>();
private Mesh mesh = new Mesh("Wall");
private Mesh backMesh = new Mesh("Wall (Back)");
private Mesh surroundMesh = new Mesh("Wall (Surround)");
private FloatBuffer vertexBuffer = BufferUtils.createVector3Buffer(4);
private FloatBuffer textureBuffer = BufferUtils.createVector2Buffer(4);
private Snap[] neighbor = new Snap[2];
public Wall() {
super(2, 4);
root.attachChild(mesh);
mesh.getMeshData().setIndexMode(IndexMode.TriangleStrip);
// mesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(4));
mesh.getMeshData().setVertexBuffer(vertexBuffer);
mesh.getMeshData().setTextureBuffer(textureBuffer, 0);
root.attachChild(backMesh);
backMesh.getMeshData().setIndexMode(IndexMode.TriangleStrip);
backMesh.getMeshData().setVertexBuffer(vertexBuffer);
backMesh.getMeshData().setTextureBuffer(textureBuffer, 0);
root.attachChild(surroundMesh);
surroundMesh.getMeshData().setIndexMode(IndexMode.TriangleStrip);
surroundMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(8));
surroundMesh.getMeshData().setNormalBuffer(BufferUtils.createVector3Buffer(8));
// surroundMesh.getMeshData().setTextureBuffer(textureBuffer, 0);
// Add a material to the box, to show both vertex color and lighting/shading.
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
mesh.setRenderState(ms);
// Add a texture to the box.
final TextureState ts = new TextureState();
ts.setTexture(TextureManager.load("brick_wall.jpg", Texture.MinificationFilter.Trilinear, Format.GuessNoCompression, true));
mesh.setRenderState(ts);
// backMesh.setRenderState(ts);
UserData userData = new UserData(this);
mesh.setUserData(userData);
backMesh.setUserData(userData);
surroundMesh.setUserData(userData);
allocateNewPoint();
}
public void addChild(HousePart housePart) {
children.add(housePart);
}
public boolean removeChild(HousePart housePart) {
return children.remove(housePart);
}
public void addPoint(int x, int y) {
if (drawCompleted)
throw new RuntimeException("Drawing of this object is already completed");
if (points.size() >= numOfEditPoints)
drawCompleted = true;
else {
allocateNewPoint();
setPreviewPoint(x, y);
}
}
private void allocateNewPoint() {
Vector3 p = new Vector3();
points.add(p);
points.add(p);
}
private Vector3 getUpperPoint(Vector3 p) {
return new Vector3(p.getX(), p.getY(), wallHeight);
}
public void setPreviewPoint(int x, int y) {
if (editPointIndex == -1 || editPointIndex == 0 || editPointIndex == 2) {
Vector3 p = SceneManager.getInstance().findMousePoint(x, y);
if (p != null) {
int index = (editPointIndex == -1) ? points.size() - 2 : editPointIndex;
Snap snap = snap(p, index);
setNeighbor(index, snap, true);
points.set(index, p);
points.set(index + 1, getUpperPoint(p));
}
} else if (editPointIndex == 1 || editPointIndex == 3) {
int lower = (editPointIndex == 1) ? 0 : 2;
Vector3 base = points.get(lower);
Vector3 closestPoint = closestPoint(base, base.add(0, 0, 1, null), x, y);
// neighbor[1] = snap(closestPoint);
wallHeight = findHeight(base, closestPoint);
points.set(1, getUpperPoint(points.get(1)));
points.set(3, getUpperPoint(points.get(3)));
}
draw();
for (Snap neighbor : this.neighbor)
if (neighbor != null)
neighbor.getNeighbor().draw();
}
@Override
protected void draw() {
boolean drawable = points.size() >= 4;
vertexBuffer.position(0);
for (int i = 0; i < points.size(); i++) {
Vector3 p = points.get(i);
// update location of point spheres
pointsRoot.getChild(i).setTranslation(p);
pointsRoot.setVisible(i, true);
}
if (drawable) {
final float TEXTURE_SCALE_X = (float) points.get(2).subtract(points.get(0), null).length();
final float TEXTURE_SCALE_Y = (float) points.get(3).subtract(points.get(2), null).length();
// Vector3 normal = points.get(3).subtract(points.get(1), null).cross(points.get(2).subtract(points.get(1), null), null).normalize(null);
Vector3 normal = points.get(2).subtract(points.get(0), null).cross(points.get(1).subtract(points.get(0), null), null).normalize(null);
ArrayList<PolygonPoint> polyPoints = new ArrayList<PolygonPoint>();
Vector3 p;
p = points.get(0);
polyPoints.add(new PolygonPoint(p.getX(), p.getY(), p.getZ()));
p = points.get(2);
polyPoints.add(new PolygonPoint(p.getX(), p.getY(), p.getZ()));
p = points.get(3);
polyPoints.add(new PolygonPoint(p.getX(), p.getY(), p.getZ()));
p = points.get(1);
polyPoints.add(new PolygonPoint(p.getX(), p.getY(), p.getZ()));
try {
AnyToXYTransform toXY = new AnyToXYTransform(normal.getX(), normal.getY(), normal.getZ());
XYToAnyTransform fromXY = new XYToAnyTransform(normal.getX(), normal.getY(), normal.getZ());
for (TriangulationPoint tp : polyPoints)
toXY.transform(tp);
Polygon polygon = new Polygon(polyPoints);
for (HousePart child : children) {
Window win = (Window) child;
PolygonPoint pp;
ArrayList<PolygonPoint> holePoints = new ArrayList<PolygonPoint>();
ArrayList<Vector3> points = child.getPoints();
p = win.convertFromWallRelativeToAbsolute(points.get(0));
pp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(pp);
holePoints.add(pp);
p = win.convertFromWallRelativeToAbsolute(points.get(2));
pp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(pp);
holePoints.add(pp);
p = win.convertFromWallRelativeToAbsolute(points.get(3));
pp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(pp);
holePoints.add(pp);
p = win.convertFromWallRelativeToAbsolute(points.get(1));
pp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(pp);
holePoints.add(pp);
polygon.addHole(new Polygon(holePoints));
}
Vector3 p01 = points.get(1).subtract(points.get(0), null);
Vector3 p02 = points.get(2).subtract(points.get(0), null);
TPoint o = new TPoint(points.get(0).getX(), points.get(0).getY(), points.get(0).getZ());
TPoint u = new TPoint(p01.getX(), p01.getY(), p01.getZ());
TPoint v = new TPoint(p02.getX(), p02.getY(), p02.getZ());
toXY.transform(o);
toXY.transform(u);
toXY.transform(v);
Poly2Tri.triangulate(polygon);
ArdorMeshMapper.updateTriangleMesh(mesh, polygon, fromXY);
// ArdorMeshMapper.updateVertexNormals(mesh, polygon.getTriangles(), fromXY);
ArdorMeshMapper.updateFaceNormals(mesh, polygon.getTriangles(), fromXY);
ArdorMeshMapper.updateTextureCoordinates(mesh, polygon.getTriangles(), 1, o, u, v);
Poly2Tri.triangulate(polygon);
ArdorMeshMapper.updateTriangleMesh(backMesh, polygon, fromXY);
ArdorMeshMapper.updateFaceNormals(backMesh, polygon.getTriangles(), fromXY);
Vector3 n = decideThicknessNormal();
backMesh.setTranslation(n);
drawSurroundMesh(n);
} catch (Exception e) {
e.printStackTrace();
}
// force bound update
root.updateGeometricState(0);
CollisionTreeManager.INSTANCE.removeCollisionTree(mesh);
for (HousePart child : children)
child.draw();
}
}
private Vector3 decideThicknessNormal() {
FloatBuffer normalBuffer = mesh.getMeshData().getNormalBuffer();
normalBuffer.position(0);
// Vector3 n = new Vector3(normalBuffer.get(), normalBuffer.get(), normalBuffer.get());
Vector3 p02 = points.get(2).subtract(points.get(0), null).normalizeLocal();
Vector3 p01 = points.get(1).subtract(points.get(0), null).normalizeLocal();
Vector3 n = p02.crossLocal(p01).normalizeLocal();
n.multiplyLocal(wallThickness);
Snap neighbor = this.neighbor[0];
if (neighbor == null)
neighbor = this.neighbor[1];
if (neighbor != null && neighbor.getNeighbor().getPoints().size() >= 4) {
Wall otherWall = (Wall) neighbor.getNeighbor();
ArrayList<Vector3> otherPoints = otherWall.getPoints();
int otherPointIndex = neighbor.getNeighborPointIndex();
Vector3 a = otherPoints.get(otherPointIndex);
Vector3 b = otherPoints.get(otherPointIndex == 0 ? 2 : 0);
Vector3 ab = b.subtract(a, null).normalizeLocal();
if (n.dot(ab) < 0) {
n.negateLocal();
}
} else {
ReadOnlyVector3 camera = SceneManager.getInstance().getCanvas().getCanvasRenderer().getCamera().getDirection();
if (camera.dot(n) < 0)
n.negateLocal();
}
return n;
}
private void drawSurroundMesh(ReadOnlyVector3 thickness) {
FloatBuffer vertexBuffer = surroundMesh.getMeshData().getVertexBuffer();
vertexBuffer.position(0);
Vector3 p2 = Vector3.fetchTempInstance();
int[] order = { 0, 1, 3, 2 };
for (int i : order) {
ReadOnlyVector3 p = points.get(i);
vertexBuffer.put(p.getXf()).put(p.getYf()).put(p.getZf());
p2.set(p).addLocal(thickness);
vertexBuffer.put(p2.getXf()).put(p2.getYf()).put(p2.getZf());
}
Vector3.releaseTempInstance(p2);
}
public Snap next(Wall previous) {
for (Snap s : neighbor)
if (s != null && s.getNeighbor() != previous)
return s;
return null;
}
private void setNeighbor(int pointIndex, Snap newNeighbor, boolean updateNeighbors) {
int i = pointIndex < 2 ? 0 : 1;
Snap oldNeighbor = neighbor[i];
if (updateNeighbors || oldNeighbor == null) // do not update if already has neighbor, unless this update was initiated by this wall
neighbor[i] = newNeighbor;
if (!updateNeighbors || oldNeighbor == newNeighbor || (oldNeighbor != null && oldNeighbor.equals(newNeighbor)))
return;
if (oldNeighbor != null)
((Wall)oldNeighbor.getNeighbor()).removeNeighbor(oldNeighbor.getNeighborPointIndex(), pointIndex, this);
if (newNeighbor != null)
((Wall) newNeighbor.getNeighbor()).setNeighbor(newNeighbor.getNeighborPointIndex(), new Snap(this, newNeighbor.getNeighborPointIndex(), newNeighbor.getThisPointIndex()), false);
}
private void removeNeighbor(int pointIndex, int requestingPointIndex, Wall wall) {
int i = pointIndex < 2 ? 0 : 1;
if (neighbor[i] != null && neighbor[i].getNeighbor() == wall && neighbor[i].getNeighborPointIndex() == requestingPointIndex)
neighbor[i] = null;
draw();
}
public void destroy() {
for (int i = 0; i < neighbor.length; i++)
if (neighbor[i] != null)
((Wall) neighbor[i].getNeighbor()).setNeighbor(neighbor[i].getNeighborPointIndex(), null, false); //.removeNeighbor(this);
}
}
|
package org.ensembl.healthcheck;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.EnumMap;
public enum Species
{
//defined new Species and properties: taxonomy_id, assemblyprefix, stableIDprefix, alias
CHOLOEPUS_HOFFMANNI(9358,"choHof","ENSCHO","Sloth,Two-toed_sloth,Hoffmans_two-fingered_sloth,choloepus_hoffmanni"),
GORILLA_GORILLA(9593,"gorGor","ENSGGO","gorilla,gorilla_gorilla,ggor"),
TAENIOPYGIA_GUTTATA(59729,"taeGut","ENSTGU","zebrafinch,zebra_finch,taeniopygia_guttata,taeniopygiaguttata,tguttata,poephila_guttata,taenopygia_guttata"),
ORYCTOLAGUS_CUNICULUS(9986,"RABBIT","ENSOCU","rabbit,oryctolagus,domestic_rabbit,bunny,japanese_white_rabbit,european_rabbit,oryctolagus_cuniculus"),
GALLUS_GALLUS(9031,"WASHUC","ENSGAL","chicken,chick,ggallus,gallusgallus,gallus_gallus"),
DANIO_RERIO(7955,"ZFISH","ENSDAR","zebrafish,danio,drerio,daniorerio,danio_rerio"),
CULEX_PIPIENS(7175,"CpiJ","CPIJ","culex,culexpipiens,culex_pipiens"),
TAKIFUGU_RUBRIPES(31033,"FUGU","ENSTRU","pufferfish,fugu,frubripes,fugurubripes,fugu_rubripes,takifugu,trubripes,takifugurubripes,takifugu_rubripes"),
CAENORHABDITIS_BRIGGSAE(6238,"CBR","","briggsae,cbriggsae,caenorhabditisbriggsae,caenorhabditis_briggsae"),
FELIS_CATUS(9685,"CAT","ENSFCA","cat,fcatus,felis,domestic_cat,felis_catus"),
MUS_MUSCULUS(10090,"NCBIM","ENSMUS","mouse,mmusculus,musmusculus,mus_musculus"),
SPERMOPHILUS_TRIDECEMLINEATUS(43179,"SQUIRREL","ENSSTO","squirrel,stridecemlineatus,thirteen-lined_ground_squirrel,spermophilus_tridecemlineatus_arenicola,spermophilus_tridecemlineatus"),
SUS_SCROFA(9823,"PIG","","pig,boar,wildboar,wild_boar,susscrofa,sus_scrofa"),
ERINACEUS_EUROPAEUS(9365,"HEDGEHOG","ENSEEU","hedgehog,european_hedgehog,eeuropaeus,erinaceus_europaeus"),
MONODELPHIS_DOMESTICA(13616,"BROADO","ENSMOD","opossum,monodelphis,mdomestica,mdomesticus,monodelphisdomestica,monodelphisdomesticus,monodelphis_domesticus,monodelphis_domestica"),
RATTUS_NORVEGICUS(10116,"RGSC","ENSRNO","rat,rnovegicus,rattusnorvegicus,rattus_norvegicus"),
TETRAODON_NIGROVIRIDIS(99883,"TETRAODON","IGNORE","tetraodon,tnigroviridis,tetraodonnigroviridis,tetraodon_nigroviridis"),
PONGO_PYGMAEUS(9600,"PPYG","ENSPPY","orangutan,orang-utan,ppygmaeus,pongo_pygmaeus"),
HEALTHCHECK(0,"","",""),
EQUUS_CABALLUS(9796,"EquCab","ENSECA","horse,equus,mr_ed,ecaballus,equus_caballus"),
XENOPUS_TROPICALIS(8364,"JGI","ENSXET","pipid,pipidfrog,xenopus,xtropicalis,xenopustropicalis,xenopus_tropicalis"),
SACCHAROMYCES_CEREVISIAE(4932,"SGD","IGNORE","yeast,saccharomyces,scerevisiae,saccharomycescerevisiae,saccharomyces_cerevisiae"),
MACACA_MULATTA(9544,"MM","ENSMMU","macacamulatta,rhesusmacaque,rhesus_macaque,macaque,macaca_mulatta"),
CAENORHABDITIS_ELEGANS(6239,"WS","IGNORE","elegans,celegans,caenorhabditiselegans,caenorhabditis_elegans"),
SOREX_ARANEUS(42254,"COMMON_SHREW","ENSSAR","shrew,common_shrew,commonShrew,european_shrew,saraneus,sorex,sorex_araneus"),
HOMO_SAPIENS(9606,"NCBI","ENS","human,hsapiens,homosapiens,homo_sapiens"),
ORYZIAS_LATIPES(8090,"MEDAKA","ENSORL","medaka,oryzias,japanese_medaka,japanese_rice_fish,japanese_ricefish,japanese_killifish,oryzias_latipes"),
AEDES_AEGYPTI(7159,"","IGNORE","aedes,aedesaegypti,aedes_aegypti"),
APIS_MELLIFERA(7460,"AMEL","","honeybee,honey_bee,apis,amellifera,apismellifera,apis_mellifera"),
PETROMYZON_MARINUS(7757,"PMAR","ENSPMA","lamprey,sea_laprey,pmarinus,petromyzon,petromyzon_marinus"),
CIONA_INTESTINALIS(7719,"JGI","ENSCIN","cionaintestinalis,ciona_int,ciona_intestinalis"),
OTOLEMUR_GARNETTII(30611,"BUSHBABY","ENSOGA","bushbaby,bush_baby,galago,small_eared_galago,ogarnettii,otolemur,otolemur_garnettii"),
CANIS_FAMILIARIS(9615,"BROADD","ENSCAF","dog,doggy,cfamiliaris,canisfamiliaris,canis_familiaris"),
HELP(0,"","",""),
ANOPHELES_GAMBIAE(7165,"AgamP","IGNORE","mosquito,anopheles,agambiae,anophelesgambiae,anopheles_gambiae"),
DROSOPHILA_MELANOGASTER(7227,"BDGP","IGNORE","drosophila,dmelongaster,drosophilamelanogaster,drosophila_melanogaster"),
DROSOPHILA_PSEUDOOBSCURA(7237, "BCM-HGSC", "IGNORE", "drosophila,pseudoobscura,drosophilapseudoobscura,drosophila_pseudoobscura,dpse"),
DROSOPHILA_ANANASSAE(7217, "dana", "IGNORE", "drosophila,ananassae,drosophilaananassae,drosophila_ananassae,dana"),
DROSOPHILA_YAKUBA(7245, "dyak", "IGNORE", "drosophila,yakuba,drosophilayakuba,drosophila_yakuba,dyak"),
DROSOPHILA_GRIMSHAWI(7222, "dgri", "IGNORE", "drosophila,grimshawi,drosophilagrimshawi,drosophila_grimshawi,dgri"),
DROSOPHILA_WILLISTONI(7260, "dwil", "IGNORE", "drosophila,willistoni,drosophilawillistonii,drosophila_willistoni,dwil"),
MYOTIS_LUCIFUGUS(59463,"MICROBAT","ENSMLU","microbat,little_brown_bat,mlucifugus,myotis,myotis_lucifugus"),
NCBI_TAXONOMY(0,"","",""),
SYSTEM(0,"","",""),
CIONA_SAVIGNYI(51511,"CSAV","ENSCSAV","savignyi,cionasavignyi,csavignyi,ciona_savignyi"),
TUPAIA_BELANGERI(37347,"TREESHREW","ENSTBE","treeshrew,tbelangeri,northern_tree_shrew,common_tree_shrew,tupaia_belangeri"),
PAN_TROGLODYTES(9598,"CHIMP","ENSPTR","chimp,chimpanzee,ptroglodytes,pantroglodytes,pan_troglodytes"),
GASTEROSTEUS_ACULEATUS(69293,"BROADS","ENSGAC","stickleback,gas_aculeatus,gasaculeatus,gasterosteusaculeatus,gasterosteus_aculeatus"),
ENSEMBL_WEBSITE(0,"","",""),
ECHINOPS_TELFAIRI(9371,"TENREC","ENSETE","tenrec,echinops,small_madagascar_hedgehog,lesser_hedgehog_tenrec,echinops_telfairi"),
CAVIA_PORCELLUS(10141,"CAVPOR","ENSCPO","guineapig,guinea_pig,cporcellus,cavia_porcellus"),
LOXODONTA_AFRICANA(9785,"LoxAfr","ENSLAF","elephant,nelly,loxodonta,african_elephant,african_savannah_elephant,african_bush_elephant,loxodonta_africana"),
ANOLIS_CAROLINENSIS(28377,"AnoCar","ENSACA","lizard,anole,anolis_lizard,anolis,anolis_carolinensis"),
ORNITHORHYNCHUS_ANATINUS(9258,"OANA","ENSOAN","platypus,oanatius,ornithorhynchus_anatinus"),
DASYPUS_NOVEMCINCTUS(9361,"DasNov","ENSDNO","armadillo,daisy,dasypus,nine_banded_armadillo,nine-banded_armadillo,texas_armadillo,dasypus_novemcinctus"),
OCHOTONA_PRINCEPS(9978,"PIKA","ENSOPR","pika,Americanpika,American_pika,oprinceps,ochotona,ochotona_princeps"),
UNKNOWN(0,"","",""),
MICROCEBUS_MURINUS(30608,"micMur","ENSMIC","mouse_lemur,mouselemur,microcebus,microcebus_murinus"),
BOS_TAURUS(9913,"BTAU","ENSBTA","cow,btaurus,bostaurus,bos_taurus"),
PROCAVIA_CAPENSIS(9813,"PROCAP","ENSPCA","cape_rock_hyrax,caperockhyrax,procaviacapensis,procavia_capensis"),
PTEROPUS_VAMPYRUS(132908,"PTEVAM","ENSPVA","large_flying_fox,largeflyingfox,pteropusvampyrus,pteropus_vampyrus"),
TARSIUS_SYRICHTA(9478,"TARSYR","ENSTSY","philippine_tarsier,philippinetarsier,tarsiussyrichta,tarsius_syrichta"),
TURSIOPS_TRUNCATUS(9739,"TURTRU","ENSTTR","bottlenosed_dolphin,dolphin,tursiopstruncatus,tursiops_truncatus"),
VICUGNA_PACOS(30538,"VICPAC","ENSVPA","alpaca,vicugnapacos,vicugna_pacos"),
DIPODOMYS_ORDII(10020,"DIPORD","ENSDOR","ords_kangaroo_rat,ordskangaroorat,kangaroo_rat, kangaroorat , dipodomys_ordii");
// Taxonomy IDs - see ensembl-compara/sql/taxon.txt
private static Map<Integer,Species> taxonIDToSpecies = new HashMap<Integer,Species>();
private static Map<String,Species> assemblyPrefixToSpecies = new HashMap<String,Species>();
private static Map<Species,String> vegaStableIDPrefix = new EnumMap<Species,String>(Species.class);
private static Logger logger = Logger.getLogger("HealthCheckLogger");
//populate the hash tables
static{
for(Species s : values()){
taxonIDToSpecies.put(s.getTaxonID(), s);
assemblyPrefixToSpecies.put(s.getAssemblyPrefix(),s);
//we have to add to the Vega hash the 4 species with Vega annotation
switch(s){
case HOMO_SAPIENS : vegaStableIDPrefix.put(s.HOMO_SAPIENS, "OTTHUM");
break;
case MUS_MUSCULUS: vegaStableIDPrefix.put(s.MUS_MUSCULUS, "OTTMUS");
break;
case CANIS_FAMILIARIS: vegaStableIDPrefix.put(s.CANIS_FAMILIARIS, "OTTCAN");
break;
case DANIO_RERIO: vegaStableIDPrefix.put(s.DANIO_RERIO, "OTTDAR");
break;
}
}
}
private final int taxonID;
private final String assemblyPrefix;
private final String stableIDPrefix;
private final String alias;
private Species(int tax_id, String assembly, String stableID, String alias){
this.taxonID = tax_id;
this.assemblyPrefix = assembly;
this.stableIDPrefix = stableID;
this.alias = alias;
}
//getters for the properties
public int getTaxonID(){return taxonID;};
public String getAssemblyPrefix(){return assemblyPrefix;};
public String getStableIDPrefix(){return stableIDPrefix;};
public String getAlias(){return alias;};
//methods to mantain backwards compatibility
/**
* Resolve an alias to a Species object.
*
* @param speciesAlias
* The alias (e.g. human, homosapiens, hsapiens)
* @return The species object corresponding to alias, or Species.UNKNOWN if it
* cannot be resolved.
*/
public static Species resolveAlias(String speciesAlias) {
String alias = speciesAlias.toLowerCase();
for(Species s : values()){
if (in (alias,s.getAlias())){
return s;
}
}
return Species.UNKNOWN;
}
/**
* Get the taxonomy ID associated with a particular species.
*
* @param s
* The species to look up.
* @return The taxonomy ID associated with s, or "" if none is found.
*/
public static String getTaxonomyID(Species s) {
String result = "";
result = Integer.toString(s.getTaxonID());
return result;
}
/**
* Get the species associated with a particular taxonomy ID.
*
* @param t
* The taxonomy ID to look up.
* @return The species associated with t, or Species.UNKNOWN if none is found.
*/
public static Species getSpeciesFromTaxonomyID(String t) {
Species result = UNKNOWN;
if (taxonIDToSpecies.containsKey(t)) {
result = (Species) taxonIDToSpecies.get(t);
} else {
logger.warning("Cannot get species for taxonomy ID " + t + " returning Species.UNKNOWN");
}
return result;
}
/**
* Return true if alias appears somewhere in a string.
*/
private static boolean in(String alias, String list) {
String[] aliases = list.split(",");
for (int i = 0; i < aliases.length; i++) {
if (alias.equals(aliases[i].trim())) {
return true;
}
}
return false;
}
/**
* Return a Species object corresponding to a particular assembly prefix.
*
* @param prefix
* The assembly prefix.
*
* @return The Species corresponding to prefix, or Species.UNKNOWN.
*/
public static Species getSpeciesForAssemblyPrefix(String prefix) {
Species result = Species.UNKNOWN;
if (assemblyPrefixToSpecies.containsKey(prefix)) {
result = (Species) assemblyPrefixToSpecies.get(prefix);
} else {
result = Species.UNKNOWN;
}
return result;
}
/**
* Get the assembly prefix for a species.
*
* @param s
* The species.
* @return The assembly prefix for s.
*/
public static String getAssemblyPrefixForSpecies(Species s) {
return (String) s.getAssemblyPrefix();
}
/**
* Get the stable ID prefix for a species.
*
* @param s
* The species.
* @param t The type of database.
* @return The stable ID prefix for s. Note "IGNORE" is used for imported species.
*/
public static String getStableIDPrefixForSpecies(Species s, DatabaseType t) {
String result = "";
if (t.equals(DatabaseType.CORE)) {
result = (String) s.getStableIDPrefix();
} else if (t.equals(DatabaseType.VEGA)) {
result = (String) vegaStableIDPrefix.get(s);
}
if (result == null || result.equals("")) {
logger.warning("Can't get stable ID prefix for " +s.toString() + " " + t.toString() + " database");
}
return result;
}
public String toString() {
return this.name().toLowerCase();
}
}
|
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import java.util.*;
/**
* The Discovery protocol layer retrieves the initial membership (used by the GMS when started
* by sending event FIND_INITIAL_MBRS down the stack). We do this by specific subclasses, e.g. by mcasting PING
* requests to an IP MCAST address or, if gossiping is enabled, by contacting the GossipServer.
* The responses should allow us to determine the coordinator whom we have to
* contact, e.g. in case we want to join the group. When we are a server (after having
* received the BECOME_SERVER event), we'll respond to PING requests with a PING
* response.<p> The FIND_INITIAL_MBRS event will eventually be answered with a
* FIND_INITIAL_MBRS_OK event up the stack.
* The following properties are available
* <ul>
* <li>timeout - the timeout (ms) to wait for the initial members, default is 3000=3 secs
* <li>num_initial_members - the minimum number of initial members for a FIND_INITAL_MBRS, default is 2
* <li>num_ping_requests - the number of GET_MBRS_REQ messages to be sent (min=1), distributed over timeout ms
* </ul>
* @author Bela Ban
* @version $Id: Discovery.java,v 1.5 2005/03/23 09:26:44 belaban Exp $
*/
public abstract class Discovery extends Protocol {
final Vector members=new Vector(11);
final Set members_set=new HashSet(11); // copy of the members vector for fast random access
Address local_addr=null;
String group_addr=null;
long timeout=3000;
int num_initial_members=2;
boolean is_server=false;
PingWaiter ping_waiter;
/** Number of GET_MBRS_REQ messages to be sent (min=1), distributed over timeout ms */
int num_ping_requests=2;
public abstract String getName();
/** Called after local_addr was set */
public void localAddressSet(Address addr) {
;
}
public abstract void sendGetMembersRequest();
/** Called when CONNECT_OK has been received */
public void handleConnectOK() {
;
}
public void handleDisconnect() {
;
}
public void handleConnect() {
;
}
public Vector providedUpServices() {
Vector ret=new Vector(1);
ret.addElement(new Integer(Event.FIND_INITIAL_MBRS));
return ret;
}
/**
* sets the properties of the PING protocol.
* The following properties are available
* property: timeout - the timeout (ms) to wait for the initial members, default is 3000=3 secs
* property: num_initial_members - the minimum number of initial members for a FIND_INITAL_MBRS, default is 2
* @param props - a property set
* @return returns true if all properties were parsed properly
* returns false if there are unrecnogized properties in the property set
*/
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("timeout"); // max time to wait for initial members
if(str != null) {
timeout=Long.parseLong(str);
if(timeout <= 0) {
if(log.isErrorEnabled()) log.error("timeout must be > 0");
return false;
}
props.remove("timeout");
}
str=props.getProperty("num_initial_members"); // wait for at most n members
if(str != null) {
num_initial_members=Integer.parseInt(str);
props.remove("num_initial_members");
}
str=props.getProperty("num_ping_requests"); // number of GET_MBRS_REQ messages
if(str != null) {
num_ping_requests=Integer.parseInt(str);
props.remove("num_ping_requests");
if(num_ping_requests < 1)
num_ping_requests=1;
}
if(props.size() > 0) {
StringBuffer sb=new StringBuffer();
for(Enumeration e=props.propertyNames(); e.hasMoreElements();) {
sb.append(e.nextElement().toString());
if(e.hasMoreElements()) {
sb.append(", ");
}
}
if(log.isErrorEnabled()) log.error("The following properties are not recognized: " + sb);
return false;
}
return true;
}
public void start() throws Exception {
super.start();
PingSender ping_sender=new PingSender(timeout, num_ping_requests, this);
if(ping_waiter == null)
ping_waiter=new PingWaiter(timeout, num_initial_members, this, ping_sender);
}
public void stop() {
is_server=false;
if(ping_waiter != null)
ping_waiter.stop();
}
/**
* An event was received from the layer below. Usually the current layer will want to examine
* the event type and - depending on its type - perform some computation
* (e.g. removing headers from a MSG event type, or updating the internal membership list
* when receiving a VIEW_CHANGE event).
* Finally the event is either a) discarded, or b) an event is sent down
* the stack using <code>PassDown</code> or c) the event (or another event) is sent up
* the stack using <code>PassUp</code>.
* <p/>
* For the PING protocol, the Up operation does the following things.
* 1. If the event is a Event.MSG then PING will inspect the message header.
* If the header is null, PING simply passes up the event
* If the header is PingHeader.GET_MBRS_REQ then the PING protocol
* will PassDown a PingRequest message
* If the header is PingHeader.GET_MBRS_RSP we will add the message to the initial members
* vector and wake up any waiting threads.
* 2. If the event is Event.SET_LOCAL_ADDR we will simple set the local address of this protocol
* 3. For all other messages we simple pass it up to the protocol above
*
* @param evt - the event that has been sent from the layer below
*/
public void up(Event evt) {
Message msg, rsp_msg;
Object obj;
PingHeader hdr, rsp_hdr;
PingRsp rsp;
Address coord;
switch(evt.getType()) {
case Event.MSG:
msg=(Message)evt.getArg();
obj=msg.getHeader(getName());
if(obj == null || !(obj instanceof PingHeader)) {
passUp(evt);
return;
}
hdr=(PingHeader)msg.removeHeader(getName());
switch(hdr.type) {
case PingHeader.GET_MBRS_REQ: // return Rsp(local_addr, coord)
synchronized(members) {
coord=members.size() > 0 ? (Address)members.firstElement() : local_addr;
}
PingRsp ping_rsp=new PingRsp(local_addr, coord, is_server);
rsp_msg=new Message(msg.getSrc(), null, null);
rsp_hdr=new PingHeader(PingHeader.GET_MBRS_RSP, ping_rsp);
rsp_msg.putHeader(getName(), rsp_hdr);
if(log.isTraceEnabled())
log.trace("received GET_MBRS_REQ from " + msg.getSrc() + ", sending response " + rsp_hdr);
passDown(new Event(Event.MSG, rsp_msg));
return;
case PingHeader.GET_MBRS_RSP: // add response to vector and notify waiting thread
rsp=hdr.arg;
if(log.isTraceEnabled())
log.trace("received GET_MBRS_RSP, rsp=" + rsp);
ping_waiter.addResponse(rsp);
return;
default:
if(log.isWarnEnabled()) log.warn("got PING header with unknown type (" + hdr.type + ')');
return;
}
case Event.SET_LOCAL_ADDRESS:
passUp(evt);
local_addr=(Address)evt.getArg();
localAddressSet(local_addr);
break;
case Event.CONNECT_OK:
handleConnectOK();
break;
default:
passUp(evt); // Pass up to the layer above us
break;
}
}
/**
* An event is to be sent down the stack. The layer may want to examine its type and perform
* some action on it, depending on the event's type. If the event is a message MSG, then
* the layer may need to add a header to it (or do nothing at all) before sending it down
* the stack using <code>PassDown</code>. In case of a GET_ADDRESS event (which tries to
* retrieve the stack's address from one of the bottom layers), the layer may need to send
* a new response event back up the stack using <code>passUp()</code>.
* The PING protocol is interested in several different down events,
* Event.FIND_INITIAL_MBRS - sent by the GMS layer and expecting a GET_MBRS_OK
* Event.TMP_VIEW and Event.VIEW_CHANGE - a view change event
* Event.BECOME_SERVER - called after client has joined and is fully working group member
* Event.CONNECT, Event.DISCONNECT.
*/
public void down(Event evt) {
switch(evt.getType()) {
case Event.FIND_INITIAL_MBRS: // sent by GMS layer, pass up a GET_MBRS_OK event
// sends the GET_MBRS_REQ to all members, waits 'timeout' ms or until 'num_initial_members' have been retrieved
ping_waiter.start();
break;
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
Vector tmp;
if((tmp=((View)evt.getArg()).getMembers()) != null) {
synchronized(members) {
members.clear();
members.addAll(tmp);
members_set.clear();
members_set.addAll(tmp);
}
}
passDown(evt);
break;
case Event.BECOME_SERVER: // called after client has joined and is fully working group member
passDown(evt);
is_server=true;
break;
case Event.CONNECT:
group_addr=(String)evt.getArg();
passDown(evt);
handleConnect();
break;
case Event.DISCONNECT:
handleDisconnect();
passDown(evt);
break;
default:
passDown(evt); // Pass on to the layer below us
break;
}
}
protected View makeView(Vector mbrs) {
Address coord=null;
long id=0;
ViewId view_id=new ViewId(local_addr);
coord=view_id.getCoordAddress();
id=view_id.getId();
return new View(coord, id, mbrs);
}
}
|
package org.kered.dko.util;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import org.kered.dko.ant.SchemaExtractor;
public class DumpDatabase {
private static final String CARD_1 = "CARD_1";
private static final String CARD_2 = "CARD_2";
private static final String CARD_3 = "CARD_3";
private static JButton next;
private static JButton prev;
private static JPanel cards;
private static CardLayout cl;
private static Map<String,NextListener> nexters = new HashMap<String,NextListener>();
private static JTextField server = null;
private static JTextField username = null;
private static JPasswordField password = null;
private static JButton finish;
private static JFrame frame;
private static final Stack<String> cardStack = new Stack<String>();
static Map<String,Map<String,Map<String,String>>> schemas = null;
private static class SchemaGetter implements Runnable {
@Override
public void run() {
schemas = null;
SchemaExtractor se = new SchemaExtractor();
se.setUsername(username.getText());
se.setPassword(new String(password.getPassword()));
try {
se.setURL(server.getText());
schemas = se.getDatabaseTableColumnTypes();
} catch (Exception e) {
e.printStackTrace();
}
if (CARD_3.equals(cardStack.peek())) nexters.get(CARD_3).show();
}
}
private static void createAndShowGUI() {
frame = new JFrame("DKO Dump Database");
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cards = new JPanel(new CardLayout());
cl = (CardLayout)(cards.getLayout());
frame.getContentPane().add(cards);
buildCard1();
buildCard2();
buildCard3();
buildButtonBar();
cardStack.add(CARD_1);
nexters.get(CARD_1).show();
frame.pack();
frame.setVisible(true);
}
public static void buildCard1() {
JPanel card = new JPanel();
card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
JLabel title = new JLabel("Welcome to the DKO Database Dumper!");
title.setAlignmentX(Component.CENTER_ALIGNMENT);
title.setBorder(new EmptyBorder(15, 20, 15, 20));
card.add(title);
JLabel question = new JLabel("What kind of database are you pulling from?");
question.setAlignmentX(Component.CENTER_ALIGNMENT);
question.setBorder(new EmptyBorder(5, 10, 5, 10));
card.add(question);
String[] databaseTypes = {"SQL Server"};
final JComboBox dbTypeSelectBox = new JComboBox(databaseTypes);
dbTypeSelectBox.setBorder(new EmptyBorder(5, 10, 5, 10));
card.add(dbTypeSelectBox);
server = new JTextField("jdbc:sqlserver://server:1433");
server.setBorder(new EmptyBorder(2, 10, 2, 10));
username = new JTextField("sa");
username.setBorder(new EmptyBorder(2, 10, 2, 10));
password = new JPasswordField("password");
password.setBorder(new EmptyBorder(2, 10, 2, 10));
card.add(server);
card.add(username);
card.add(password);
cards.add(card, CARD_1);
final NextListener nexter = new NextListener() {
@Override
public void goNext() {
new Thread(new SchemaGetter()).start();
cardStack.add(CARD_2);
cl.show(cards, CARD_2);
}
@Override
public void show() {
next.setVisible(true);
finish.setVisible(false);
Object selectedItem = dbTypeSelectBox.getModel().getSelectedItem();
next.setEnabled(!"".equals(selectedItem) && !server.getText().isEmpty());
}
};
dbTypeSelectBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nexter.show();
}
});
nexters.put(CARD_1, nexter);
}
protected static File file = null;
public static void buildCard2() {
JPanel card = new JPanel();
card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
JLabel title = new JLabel("Where would you like to dump to?");
title.setAlignmentX(Component.CENTER_ALIGNMENT);
title.setBorder(new EmptyBorder(15, 20, 15, 20));
card.add(title);
final JFileChooser fc = new JFileChooser();
fc.setSelectedFile(new File("test2.db"));
final JButton open = new JButton("Select a SQLite3 File...");
open.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(open);
final JLabel fnLabel = new JLabel();
fnLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
fnLabel.setBorder(new EmptyBorder(15, 20, 15, 20));
card.add(fnLabel);
final NextListener nexter = new NextListener() {
@Override
public void goNext() {
cardStack.add(CARD_3);
cl.show(cards, CARD_3);
}
@Override
public void show() {
next.setVisible(true);
finish.setVisible(false);
next.setEnabled(fc.getSelectedFile() != null);
file = fc.getSelectedFile();
if (file == null) {
fnLabel.setText("");
} else {
fnLabel.setText(file.getName() + (file.exists() ? "" : " (new)"));
}
}
};
open.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(open);
if (returnVal == JFileChooser.APPROVE_OPTION) {
}
nexter.show();
}
});
cards.add(card, CARD_2);
nexters.put(CARD_2, nexter);
}
public static void buildCard3() {
JPanel card = new JPanel();
card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
JLabel title = new JLabel("What table do you want to dump?");
title.setAlignmentX(Component.CENTER_ALIGNMENT);
title.setBorder(new EmptyBorder(15, 20, 15, 20));
card.add(title);
final JComboBox schemaSelectBox = new JComboBox();
schemaSelectBox.setBorder(new EmptyBorder(5, 10, 5, 10));
schemaSelectBox.setMaximumSize(new Dimension(schemaSelectBox.getMaximumSize().width,
schemaSelectBox.getPreferredSize().height));
card.add(schemaSelectBox);
final JComboBox tableSelectBox = new JComboBox();
tableSelectBox.setBorder(new EmptyBorder(5, 10, 5, 10));
tableSelectBox.setMaximumSize(new Dimension(tableSelectBox.getMaximumSize().width,
tableSelectBox.getPreferredSize().height));
card.add(tableSelectBox);
schemaSelectBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object schema = schemaSelectBox.getSelectedItem();
Map<String, Map<String, String>> tableData = schemas==null ? null : schemas.get(schema);
Set<String> tables = tableData==null ? new HashSet<String>() : tableData.keySet();
tableSelectBox.setModel(new DefaultComboBoxModel(tables.toArray(new String[0])));
tableSelectBox.setSelectedIndex(tableSelectBox.getSelectedIndex());
}
});
final JTextArea query = new JTextArea(6, 6);
final JRadioButton top1000 = new JRadioButton("Select first 1000 rows");
final JRadioButton all = new JRadioButton("Select all rows ");
final JRadioButton custom = new JRadioButton("Select custom query ");
final ActionListener genSQL = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object schema = schemaSelectBox.getSelectedItem();
Object table = tableSelectBox.getSelectedItem();
if (schema==null || table==null) {
query.setText("Loading database schema, please wait...");
query.setEditable(false);
return;
}
Set<String> columns = schemas.get(schema).get(table).keySet();
StringBuffer sb = new StringBuffer();
for (String column : columns) {
sb.append(column).append(", ");
}
sb.delete(sb.length()-2, sb.length());
String colString = sb.toString();
if (top1000.isSelected()) {
query.setText("select top 1000 "+ colString +"\nfrom "+ schema +".."+ table +";");
query.setEditable(false);
}
if (all.isSelected()) {
query.setText("select "+ colString +"\nfrom "+ schema +".."+ table +";");
query.setEditable(false);
}
if (custom.isSelected()) {
query.setText("select "+ colString +"\nfrom "+ schema +".."+ table +"\nwhere ???;");
query.setEditable(true);
}
}
};
tableSelectBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
genSQL.actionPerformed(null);
}
});
schemaSelectBox.setSelectedIndex(schemaSelectBox.getSelectedIndex());
top1000.setAlignmentX(Component.CENTER_ALIGNMENT);
top1000.setSelected(true);
top1000.addActionListener(genSQL);
all.setAlignmentX(Component.CENTER_ALIGNMENT);
all.addActionListener(genSQL);
custom.setAlignmentX(Component.CENTER_ALIGNMENT);
custom.addActionListener(genSQL);
final ButtonGroup group = new ButtonGroup();
group.add(top1000);
group.add(all);
group.add(custom);
card.add(top1000);
card.add(all);
card.add(custom);
query.setLineWrap(true);
query.setEditable(true);
query.setVisible(true);
JScrollPane scroll = new JScrollPane(query);
card.add(scroll);
card.add(Box.createRigidArea(new Dimension(0,10)));
final JButton dump = new JButton("Dump");
dump.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
Connection srcConn = null;
Connection destConn = null;
Statement srcStmt = null;
try {
destConn = DriverManager.getConnection("jdbc:sqlite:"+ file.getAbsolutePath());
srcConn = DriverManager.getConnection(server.getText(), username.getText(),
new String(password.getPassword()));
srcStmt = srcConn.createStatement();
ResultSet rs = srcStmt.executeQuery(query.getText());
ResultSetMetaData metaData = rs.getMetaData();
for (int i=0; i<metaData.getColumnCount(); ++i) {
System.out.println(metaData.getColumnName(i+1));
}
while (rs.next()) {
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (srcStmt!=null) {
try {
srcStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (srcConn!=null) {
try {
srcConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (destConn!=null) {
try {
destConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
});
dump.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(dump);
card.add(Box.createRigidArea(new Dimension(0,5)));
final NextListener nexter = new NextListener() {
@Override
public void goNext() {}
@Override
public void show() {
List<String> schemaList = new ArrayList<String>();
if (schemas != null) {
for (String schema : schemas.keySet()) {
if ("msdb".equals(schema) || "master".equals(schema)) continue;
schemaList.add(schema);
}
}
schemaSelectBox.setModel(new DefaultComboBoxModel(schemaList.toArray(new String[0])));
schemaSelectBox.setSelectedIndex(schemaSelectBox.getSelectedIndex());
next.setVisible(false);
finish.setVisible(true);
}
};
cards.add(card, CARD_3);
nexters.put(CARD_3, nexter);
}
public static void buildButtonBar() {
JPanel buttonBar = new JPanel();
buttonBar.setLayout(new FlowLayout());
buttonBar.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
buttonBar.setAlignmentX(Component.LEFT_ALIGNMENT);
prev = new JButton("Previous");
next = new JButton("Next");
finish = new JButton("Finish");
prev.setEnabled(false);
next.setEnabled(false);
finish.setVisible(false);
prev.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardStack.pop();
String cardId = cardStack.peek();
cl.show(cards, cardId);
nexters.get(cardId).show();
//prev.setEnabled(cardStack.size() > 1);
}
});
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NextListener nextListener = nexters.get(cardStack.peek());
nextListener.goNext();
prev.setEnabled(!cardStack.isEmpty());
next.setEnabled(false);
nexters.get(cardStack.peek()).show();
}
});
finish.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
}
});
buttonBar.add(finish);
buttonBar.add(next);
buttonBar.add(prev);
frame.getContentPane().add(buttonBar);
}
private interface NextListener {
void show();
void goNext();
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
|
package net.winstone.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* String utility<br />
*
* @author Jerome Guibert
*/
public class StringUtils {
/**
* Load a File argument.
*
* @param args
* @param name
* @return a file instance for specified name argument, null if none is
* found.
*/
public static File fileArg(final Map<String, String> args, final String name) {
final String value = args.get(name);
return value != null ? new File(value) : null;
}
/**
* Load a boolean argument.
*
* @param args
* @param name
* @param defaultTrue
* @return
*/
public static boolean booleanArg(final Map<String, String> args, final String name, final boolean defaultTrue) {
final String value = args.get(name);
if (defaultTrue) {
return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"));
} else {
return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"));
}
}
/**
* Load a String argument.
*
* @param args
* @param name
* @param defaultValue
* @return
*/
public static String stringArg(final Map<String, String> args, final String name, final String defaultValue) {
return (args.get(name) == null ? defaultValue : args.get(name));
}
/**
* Load a int argument.
*
* @param args
* @param name
* @param defaultValue
* @return
*/
public static int intArg(final Map<String, String> args, final String name, final int defaultValue) {
return Integer.parseInt(StringUtils.stringArg(args, name, Integer.toString(defaultValue)));
}
public static String get(final String value, final String defaultValue) {
if ((value == null) || "".equals(value)) {
return defaultValue;
}
return value;
}
/**
* This function extract meaningful path or query
*
* @param path
* path to extract from
* @param query
* true if extract query
* @return extraction or null
*/
public static String extractQueryAnchor(final String path, final boolean query) {
final int qp = path.indexOf('?');
if (query) {
if (qp >= 0) {
return path.substring(qp + 1);
}
return null;
}
final int hp = path.indexOf('
if (qp >= 0) {
if ((hp >= 0) && (hp < qp)) {
return path.substring(0, hp);
}
return path.substring(0, qp);
} else if (hp >= 0) {
return path.substring(0, hp);
}
return path;
}
/**
* Just does a string swap, replacing occurrences of from with to.
*/
@Deprecated
public static String globalReplace(final String input, final String fromMarker, final String toValue) {
final StringBuilder out = new StringBuilder(input);
StringUtils.globalReplace(out, fromMarker, toValue);
return out.toString();
}
@Deprecated
public static String globalReplace(final String input, final String parameters[][]) {
if (parameters != null) {
final StringBuilder out = new StringBuilder(input);
for (int n = 0; n < parameters.length; n++) {
StringUtils.globalReplace(out, parameters[n][0], parameters[n][1]);
}
return out.toString();
} else {
return input;
}
}
@Deprecated
public static void globalReplace(final StringBuilder input, final String fromMarker, final String toValue) {
if (input == null) {
return;
} else if (fromMarker == null) {
return;
}
final String value = toValue == null ? "(null)" : toValue;
int index = 0;
int foundAt = input.indexOf(fromMarker, index);
while (foundAt != -1) {
input.replace(foundAt, foundAt + fromMarker.length(), value);
index = foundAt + toValue.length();
foundAt = input.indexOf(fromMarker, index);
}
}
/**
* replace substrings within string.
*
* @param input
* @param sub
* @param with
* @return
*/
public static String replace(final String input, final String sub, final String with) {
int fromIndex = 0;
int index = input.indexOf(sub, fromIndex);
if (index == -1) {
return input;
}
final StringBuilder buf = new StringBuilder(input.length() + with.length());
do {
buf.append(input.substring(fromIndex, index));
buf.append(with);
fromIndex = index + sub.length();
} while ((index = input.indexOf(sub, fromIndex)) != -1);
if (fromIndex < input.length()) {
buf.append(input.substring(fromIndex, input.length()));
}
return buf.toString();
}
public static String replace(final String input, final String[][] tokens) {
if ((tokens != null) && (input != null)) {
String out = input;
for (int n = 0; n < tokens.length; n++) {
out = StringUtils.replace(out, tokens[n][0], tokens[n][1]);
}
return out;
} else {
return input;
}
}
public static String replaceToken(final String input, final String... parameters) {
if ((input != null) && (parameters != null)) {
final String tokens[][] = new String[parameters.length][2];
for (int n = 0; n < parameters.length; n++) {
tokens[n] = new String[] { "[#" + n + "]", parameters[n] };
}
return StringUtils.replace(input, tokens);
}
return input;
}
/**
* Performs necessary escaping to render arbitrary plain text as plain text
* without any markup.
*/
public static String htmlEscapeBasicMarkup(final String text) {
final StringBuilder buf = new StringBuilder(text.length() + 64);
for (int i = 0; i < text.length(); i++) {
final char ch = text.charAt(i);
switch (ch) {
case '<':
buf.append("<");
break;
case '&':
buf.append("&");
break;
case '>':
buf.append(">");
break;
default:
buf.append(ch);
break;
}
}
return buf.toString();
}
/**
* Eliminates "." and ".." in the path. So that this method can be used for
* any string that looks like an URI, this method preserves the leading and
* trailing '/'.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String canonicalPath(final String path) {
final List r = new ArrayList(Arrays.asList(path.split("/+")));
for (int i = 0; i < r.size();) {
final String cur = (String) r.get(i);
if ((cur.length() == 0) || cur.equals(".")) {
// empty token occurs for example, "".split("/+") is [""]
r.remove(i);
} else if (cur.equals("..")) {
// i==0 means this is a broken URI.
r.remove(i);
if (i > 0) {
r.remove(i - 1);
i
}
} else {
i++;
}
}
final StringBuilder buf = new StringBuilder();
if (path.startsWith("/")) {
buf.append('/');
}
boolean first = true;
for (final Object aR : r) {
final String token = (String) aR;
if (!first) {
buf.append('/');
} else {
first = false;
}
buf.append(token);
}
// translation: if (path.endsWith("/") && !buf.endsWith("/"))
if (path.endsWith("/") && ((buf.length() == 0) || (buf.charAt(buf.length() - 1) != '/'))) {
buf.append('/');
}
return buf.toString();
}
}
|
package com.xpn.xwiki.doc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.filter.CharacterFilter;
import org.apache.velocity.VelocityContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.suigeneris.jrcs.diff.Diff;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.Revision;
import org.suigeneris.jrcs.diff.delta.Delta;
import org.suigeneris.jrcs.rcs.Version;
import org.suigeneris.jrcs.util.ToString;
import org.xwiki.bridge.DocumentModelBridge;
import org.xwiki.bridge.DocumentName;
import org.xwiki.bridge.DocumentNameFactory;
import org.xwiki.bridge.DocumentNameSerializer;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.HeaderBlock;
import org.xwiki.rendering.block.LinkBlock;
import org.xwiki.rendering.block.MacroBlock;
import org.xwiki.rendering.block.SectionBlock;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.listener.HeaderLevel;
import org.xwiki.rendering.listener.LinkType;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Parser;
import org.xwiki.rendering.parser.SyntaxFactory;
import org.xwiki.rendering.renderer.PrintRendererFactory;
import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter;
import org.xwiki.rendering.renderer.printer.WikiPrinter;
import org.xwiki.rendering.transformation.TransformationManager;
import org.xwiki.velocity.VelocityManager;
import com.xpn.xwiki.CoreConfiguration;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.content.Link;
import com.xpn.xwiki.content.parsers.DocumentParser;
import com.xpn.xwiki.content.parsers.LinkParser;
import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler;
import com.xpn.xwiki.content.parsers.ReplacementResultCollection;
import com.xpn.xwiki.criteria.impl.RevisionCriteria;
import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo;
import com.xpn.xwiki.notify.XWikiNotificationRule;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.LargeStringProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.ObjectDiff;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.ListClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StaticListClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.plugin.query.XWikiCriteria;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.validation.XWikiValidationInterface;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.web.EditForm;
import com.xpn.xwiki.web.ObjectAddForm;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
public class XWikiDocument implements DocumentModelBridge
{
private static final Log LOG = LogFactory.getLog(XWikiDocument.class);
/** The default wiki name to use when one isn't specified. */
private static final String DEFAULT_WIKI_NAME = "xwiki";
/**
* Regex Pattern to recognize if there's HTML code in a XWiki page.
*/
private static final Pattern HTML_TAG_PATTERN =
Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|"
+ "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>");
public static final String XWIKI10_SYNTAXID = "xwiki/1.0";
public static final String XWIKI20_SYNTAXID = "xwiki/2.0";
private String title;
private String parent;
private String space;
private String name;
private String content;
private String meta;
private String format;
private String creator;
private String author;
private String contentAuthor;
private String customClass;
private Date contentUpdateDate;
private Date updateDate;
private Date creationDate;
private Version version;
private long id = 0;
private boolean mostRecent = true;
private boolean isNew = true;
private String template;
private String language;
private String defaultLanguage;
private int translation;
private String database;
private BaseObject tags;
/**
* Indicates whether the document is 'hidden', meaning that it should not be returned in public search results.
* WARNING: this is a temporary hack until the new data model is designed and implemented. No code should rely on or
* use this property, since it will be replaced with a generic metadata.
*/
private boolean hidden = false;
/**
* Comment on the latest modification.
*/
private String comment;
/**
* Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For
* example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our
* first need is to support the new rendering component. To use the old rendering implementation specify a
* "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component.
*/
private String syntaxId;
/**
* Is latest modification a minor edit
*/
private boolean isMinorEdit = false;
/**
* Used to make sure the MetaData String is regenerated.
*/
private boolean isContentDirty = true;
/**
* Used to make sure the MetaData String is regenerated
*/
private boolean isMetaDataDirty = true;
public static final int HAS_ATTACHMENTS = 1;
public static final int HAS_OBJECTS = 2;
public static final int HAS_CLASS = 4;
private int elements = HAS_OBJECTS | HAS_ATTACHMENTS;
/**
* Separator string between database name and space name.
*/
public static final String DB_SPACE_SEP = ":";
/**
* Separator string between space name and page name.
*/
public static final String SPACE_NAME_SEP = ".";
// Meta Data
private BaseClass xWikiClass;
private String xWikiClassXML;
/**
* Map holding document objects grouped by classname (className -> Vector of objects). The map is not synchronized,
* and uses a TreeMap implementation to preserve className ordering (consistent sorted order for output to XML,
* rendering in velocity, etc.)
*/
private Map<String, Vector<BaseObject>> xWikiObjects = new TreeMap<String, Vector<BaseObject>>();
private List<XWikiAttachment> attachmentList;
// Caching
private boolean fromCache = false;
private ArrayList<BaseObject> objectsToRemove = new ArrayList<BaseObject>();
/**
* The view template (vm file) to use. When not set the default view template is used.
*
* @see com.xpn.xwiki.web.ViewAction#render(XWikiContext)
*/
private String defaultTemplate;
private String validationScript;
private Object wikiNode;
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the
// request)
private SoftReference<XWikiDocumentArchive> archive;
private XWikiStoreInterface store;
/**
* This is a copy of this XWikiDocument before any modification was made to it. It is reset to the actual values
* when the document is saved in the database. This copy is used for finding out differences made to this document
* (useful for example to send the correct notifications to document change listeners).
*/
private XWikiDocument originalDocument;
/**
* The document structure expressed as a tree of Block objects. We store it for performance reasons since parsing is
* a costly operation that we don't want to repeat whenever some code ask for the XDOM information.
*/
private XDOM xdom;
/**
* Used to convert a string into a proper Document Name.
*/
private DocumentNameFactory documentNameFactory =
(DocumentNameFactory) Utils.getComponent(DocumentNameFactory.class);
/**
* Used to convert a proper Document Name to string.
*/
private DocumentNameSerializer compactDocumentNameSerializer =
(DocumentNameSerializer) Utils.getComponent(DocumentNameSerializer.class, "compact");
public XWikiStoreInterface getStore(XWikiContext context)
{
return context.getWiki().getStore();
}
public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context)
{
return context.getWiki().getAttachmentStore();
}
public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context)
{
return context.getWiki().getVersioningStore();
}
public XWikiStoreInterface getStore()
{
return this.store;
}
public void setStore(XWikiStoreInterface store)
{
this.store = store;
}
public long getId()
{
if ((this.language == null) || this.language.trim().equals("")) {
this.id = getFullName().hashCode();
} else {
this.id = (getFullName() + ":" + this.language).hashCode();
}
// if (log.isDebugEnabled())
// log.debug("ID: " + getFullName() + " " + language + ": " + id);
return this.id;
}
public void setId(long id)
{
this.id = id;
}
/**
* @return the name of the space of the document
*/
public String getSpace()
{
return this.space;
}
public void setSpace(String space)
{
this.space = space;
}
public String getVersion()
{
return getRCSVersion().toString();
}
public void setVersion(String version)
{
if (version != null && !"".equals(version)) {
this.version = new Version(version);
}
}
public Version getRCSVersion()
{
if (this.version == null) {
return new Version("1.1");
}
return this.version;
}
public void setRCSVersion(Version version)
{
this.version = version;
}
public XWikiDocument()
{
this("Main", "WebHome");
}
/**
* Constructor that specifies the local document identifier: space name, document name. {@link #setDatabase(String)}
* must be called afterwards to specify the wiki name.
*
* @param web The space this document belongs to.
* @param name The name of the document.
*/
public XWikiDocument(String space, String name)
{
this(null, space, name);
}
/**
* Constructor that specifies the full document identifier: wiki name, space name, document name.
*
* @param wiki The wiki this document belongs to.
* @param web The space this document belongs to.
* @param name The name of the document.
*/
public XWikiDocument(String wiki, String web, String name)
{
setDatabase(wiki);
setSpace(web);
int i1 = name.indexOf(".");
if (i1 == -1) {
setName(name);
} else {
setSpace(name.substring(0, i1));
setName(name.substring(i1 + 1));
}
this.updateDate = new Date();
this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000);
this.contentUpdateDate = new Date();
this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000);
this.creationDate = new Date();
this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000);
this.parent = "";
this.content = "\n";
this.format = "";
this.author = "";
this.language = "";
this.defaultLanguage = "";
this.attachmentList = new ArrayList<XWikiAttachment>();
this.customClass = "";
this.comment = "";
// Note: As there's no notion of an Empty document we don't set the original document
// field. Thus getOriginalDocument() may return null.
}
/**
* @return the copy of this XWikiDocument instance before any modification was made to it.
* @see #originalDocument
*/
public XWikiDocument getOriginalDocument()
{
return this.originalDocument;
}
/**
* @param originalDocument the original document representing this document instance before any change was made to
* it, prior to the last time it was saved
* @see #originalDocument
*/
public void setOriginalDocument(XWikiDocument originalDocument)
{
this.originalDocument = originalDocument;
}
public XWikiDocument getParentDoc()
{
return new XWikiDocument(getSpace(), getParent());
}
public String getParent()
{
return this.parent != null ? this.parent : "";
}
public void setParent(String parent)
{
if (parent != null && !parent.equals(this.parent)) {
setMetaDataDirty(true);
}
this.parent = parent;
}
public String getContent()
{
return this.content;
}
public void setContent(String content)
{
if (content == null) {
content = "";
}
if (!content.equals(this.content)) {
setContentDirty(true);
setWikiNode(null);
}
this.content = content;
// invalidate parsed xdom
this.xdom = null;
}
public String getRenderedContent(XWikiContext context) throws XWikiException
{
// Note: We are currently duplicating code from the other getRendered signature since there are
// some unresolved issues with saving/restoring the context in some cases (need to be investigated),
// for example in the Admin Import page.
String renderedContent;
Object isInRenderingEngine = context.get("isInRenderingEngine");
try {
// This tells display() methods that we are inside the rendering engine and thus
// that they can return wiki syntax and not HTML syntax (which is needed when
// outside the rendering engine, i.e. when we're inside templates using only
// Velocity for example).
context.put("isInRenderingEngine", true);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one.
if (is10Syntax()) {
renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context);
} else {
renderedContent =
performSyntaxConversion(getTranslatedContent(context), getSyntaxId(), "xhtml/1.0", true);
}
} finally {
if (isInRenderingEngine != null) {
context.put("isInRenderingEngine", isInRenderingEngine);
} else {
context.remove("isInRenderingEngine");
}
}
return renderedContent;
}
/**
* @param text the text to render
* @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0")
* @param context the XWiki Context object
* @return the given text rendered in the context of this document using the passed Syntax
* @since 1.6M1
*/
public String getRenderedContent(String text, String syntaxId, XWikiContext context)
{
String result;
HashMap<String, Object> backup = new HashMap<String, Object>();
Object isInRenderingEngine = context.get("isInRenderingEngine");
try {
backupContext(backup, context);
setAsContextDoc(context);
// This tells display() methods that we are inside the rendering engine and thus
// that they can return wiki syntax and not HTML syntax (which is needed when
// outside the rendering engine, i.e. when we're inside templates using only
// Velocity for example).
context.put("isInRenderingEngine", true);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one.
if (is10Syntax(syntaxId)) {
result = context.getWiki().getRenderingEngine().renderText(text, this, context);
} else {
result = performSyntaxConversion(text, getSyntaxId(), "xhtml/1.0", true);
}
} catch (XWikiException e) {
// Failed to render for some reason. This method should normally throw an exception but this
// requires changing the signature of calling methods too.
LOG.warn(e);
result = "";
} finally {
restoreContext(backup, context);
if (isInRenderingEngine != null) {
context.put("isInRenderingEngine", isInRenderingEngine);
} else {
context.remove("isInRenderingEngine");
}
}
return result;
}
public String getEscapedContent(XWikiContext context) throws XWikiException
{
CharacterFilter filter = new CharacterFilter();
return filter.process(getTranslatedContent(context));
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
/**
* {@inheritDoc}
*/
public void setParent(DocumentName parentName)
{
this.parent = parentName.toString();
}
public String getFullName()
{
StringBuffer buf = new StringBuffer();
buf.append(getSpace());
buf.append(".");
buf.append(getName());
return buf.toString();
}
public void setFullName(String name)
{
setFullName(name, null);
}
/**
* @return a proper {@link DocumentName} for this document.
*/
public DocumentName getDocumentName()
{
return new DocumentName(getWikiName(), getSpaceName(), getPageName());
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getWikiName()
*/
public String getWikiName()
{
return StringUtils.isEmpty(getDatabase()) ? DEFAULT_WIKI_NAME : getDatabase();
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getSpaceName()
*/
public String getSpaceName()
{
return this.getSpace();
}
/**
* {@inheritDoc}
*
* @see DocumentModelBridge#getSpaceName()
*/
public String getPageName()
{
return this.getName();
}
public String getTitle()
{
return (this.title != null) ? this.title : "";
}
/**
* @param context the XWiki context used to get access to the XWikiRenderingEngine object
* @return the document title. If a title has not been provided, look for a section title in the document's content
* and if not found return the page name. The returned title is also interpreted which means it's allowed to
* use Velocity, Groovy, etc syntax within a title.
*/
public String getDisplayTitle(XWikiContext context)
{
// 1) Check if the user has provided a title
String title = getTitle();
// 2) If not, then try to extract the title from the first document section title
if (title.length() == 0) {
title = extractTitle();
}
// 3) Last if a title has been found renders it as it can contain macros, velocity code,
// groovy, etc.
if (title.length() > 0) {
// This will not completely work for scripting code in title referencing variables
// defined elsewhere. In that case it'll only work if those variables have been
// parsed and put in the corresponding scripting context. This will not work for
// breadcrumbs for example.
title = context.getWiki().getRenderingEngine().interpretText(title, this, context);
} else {
// 4) No title has been found, return the page name as the title
title = getName();
}
return title;
}
public String extractTitle()
{
String title = "";
try {
if (is10Syntax()) {
title = extractTitle10();
} else {
List<HeaderBlock> blocks = getXDOM().getChildrenByType(HeaderBlock.class, true);
if (blocks.size() > 0) {
HeaderBlock header = blocks.get(0);
if (header.getLevel().compareTo(HeaderLevel.LEVEL2) <= 0) {
title = renderXDOM(new XDOM(header.getChildren()), "plain/1.0");
}
}
}
} catch (Exception e) {
}
return title;
}
/**
* @return the first level 1 or level 1.1 title text in the document's content or "" if none are found
* @todo this method has nothing to do in this class and should be moved elsewhere
*/
public String extractTitle10()
{
String content = getContent();
int i1 = 0;
int i2;
while (true) {
i2 = content.indexOf("\n", i1);
String title = "";
if (i2 != -1) {
title = content.substring(i1, i2).trim();
} else {
title = content.substring(i1).trim();
}
if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) {
return title.substring(title.indexOf(" ")).trim();
}
if (i2 == -1) {
break;
}
i1 = i2 + 1;
}
return "";
}
public void setTitle(String title)
{
if (title != null && !title.equals(this.title)) {
setContentDirty(true);
}
this.title = title;
}
public String getFormat()
{
return this.format != null ? this.format : "";
}
public void setFormat(String format)
{
this.format = format;
if (!format.equals(this.format)) {
setMetaDataDirty(true);
}
}
public String getAuthor()
{
return this.author != null ? this.author.trim() : "";
}
public String getContentAuthor()
{
return this.contentAuthor != null ? this.contentAuthor.trim() : "";
}
public void setAuthor(String author)
{
if (!getAuthor().equals(author)) {
setMetaDataDirty(true);
}
this.author = author;
}
public void setContentAuthor(String contentAuthor)
{
if (!getContentAuthor().equals(contentAuthor)) {
setMetaDataDirty(true);
}
this.contentAuthor = contentAuthor;
}
public String getCreator()
{
return this.creator != null ? this.creator.trim() : "";
}
public void setCreator(String creator)
{
if (!getCreator().equals(creator)) {
setMetaDataDirty(true);
}
this.creator = creator;
}
public Date getDate()
{
if (this.updateDate == null) {
return new Date();
} else {
return this.updateDate;
}
}
public void setDate(Date date)
{
if ((date != null) && (!date.equals(this.updateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.updateDate = date;
}
public Date getCreationDate()
{
if (this.creationDate == null) {
return new Date();
} else {
return this.creationDate;
}
}
public void setCreationDate(Date date)
{
if ((date != null) && (!date.equals(this.creationDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.creationDate = date;
}
public Date getContentUpdateDate()
{
if (this.contentUpdateDate == null) {
return new Date();
} else {
return this.contentUpdateDate;
}
}
public void setContentUpdateDate(Date date)
{
if ((date != null) && (!date.equals(this.contentUpdateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.contentUpdateDate = date;
}
public String getMeta()
{
return this.meta;
}
public void setMeta(String meta)
{
if (meta == null) {
if (this.meta != null) {
setMetaDataDirty(true);
}
} else if (!meta.equals(this.meta)) {
setMetaDataDirty(true);
}
this.meta = meta;
}
public void appendMeta(String meta)
{
StringBuffer buf = new StringBuffer(this.meta);
buf.append(meta);
buf.append("\n");
this.meta = buf.toString();
setMetaDataDirty(true);
}
public boolean isContentDirty()
{
return this.isContentDirty;
}
public void incrementVersion()
{
if (this.version == null) {
this.version = new Version("1.1");
} else {
if (isMinorEdit()) {
this.version = this.version.next();
} else {
this.version = this.version.getBranchPoint().next().newBranch(1);
}
}
}
public void setContentDirty(boolean contentDirty)
{
this.isContentDirty = contentDirty;
}
public boolean isMetaDataDirty()
{
return this.isMetaDataDirty;
}
public void setMetaDataDirty(boolean metaDataDirty)
{
this.isMetaDataDirty = metaDataDirty;
}
public String getAttachmentURL(String filename, XWikiContext context)
{
return getAttachmentURL(filename, "download", context);
}
public String getAttachmentURL(String filename, String action, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(),
context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalAttachmentURL(String filename, String action, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(),
context);
return url.toString();
}
public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring,
getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, String params, boolean redirect, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context);
if (redirect) {
if (url == null) {
return null;
} else {
return url.toString();
}
} else {
return context.getURLFactory().getURL(url, context);
}
}
public String getURL(String action, boolean redirect, XWikiContext context)
{
return getURL(action, null, redirect, context);
}
public String getURL(String action, XWikiContext context)
{
return getURL(action, false, context);
}
public String getURL(String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, String querystring, String anchor, XWikiContext context)
{
URL url =
context.getURLFactory().createURL(getSpace(), getName(), action, querystring, anchor, getDatabase(),
context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalURL(String action, XWikiContext context)
{
URL url =
context.getURLFactory()
.createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context);
return url.toString();
}
public String getExternalURL(String action, String querystring, XWikiContext context)
{
URL url =
context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(),
context);
return url.toString();
}
public String getParentURL(XWikiContext context) throws XWikiException
{
XWikiDocument doc = new XWikiDocument();
doc.setFullName(getParent(), context);
URL url =
context.getURLFactory()
.createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException
{
loadArchive(context);
return getDocumentArchive();
}
/**
* Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from
* scripting.
*
* @param customClassName the name of the custom {@link com.xpn.xwiki.api.Document} class of the object to create.
* @param context the XWiki context.
* @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument,
* XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context)
{
if (!((customClassName == null) || (customClassName.equals("")))) {
try {
return newDocument(Class.forName(customClassName), context);
} catch (ClassNotFoundException e) {
LOG.error("Failed to get java Class object from class name", e);
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
/**
* Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from
* scripting.
*
* @param customClass the custom {@link com.xpn.xwiki.api.Document} class the object to create.
* @param context the XWiki context.
* @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument,
* XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(Class< ? > customClass, XWikiContext context)
{
if (customClass != null) {
try {
Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class};
Object[] args = new Object[] {this, context};
return (com.xpn.xwiki.api.Document) customClass.getConstructor(classes).newInstance(args);
} catch (Exception e) {
LOG.error("Failed to create a custom Document object", e);
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
public com.xpn.xwiki.api.Document newDocument(XWikiContext context)
{
String customClass = getCustomClass();
return newDocument(customClass, context);
}
public void loadArchive(XWikiContext context) throws XWikiException
{
if (this.archive == null || this.archive.get() == null) {
XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context);
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during
// the request)
this.archive = new SoftReference<XWikiDocumentArchive>(arch);
}
}
public XWikiDocumentArchive getDocumentArchive()
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the
// request)
if (this.archive == null) {
return null;
} else {
return this.archive.get();
}
}
public void setDocumentArchive(XWikiDocumentArchive arch)
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the
// request)
if (arch != null) {
this.archive = new SoftReference<XWikiDocumentArchive>(arch);
}
}
public void setDocumentArchive(String sarch) throws XWikiException
{
XWikiDocumentArchive xda = new XWikiDocumentArchive(getId());
xda.setArchive(sarch);
setDocumentArchive(xda);
}
public Version[] getRevisions(XWikiContext context) throws XWikiException
{
return getVersioningStore(context).getXWikiDocVersions(this, context);
}
public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException
{
try {
Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context);
int length = nb;
// 0 means all revisions
if (nb == 0) {
length = revisions.length;
}
if (revisions.length < length) {
length = revisions.length;
}
String[] recentrevs = new String[length];
for (int i = 1; i <= length; i++) {
recentrevs[i - 1] = revisions[revisions.length - i].toString();
}
return recentrevs;
} catch (Exception e) {
return new String[0];
}
}
/**
* Get document versions matching criterias like author, minimum creation date, etc.
*
* @param criteria criteria used to match versions
* @return a list of matching versions
*/
public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException
{
List<String> results = new ArrayList<String>();
Version[] revisions = getRevisions(context);
XWikiRCSNodeInfo nextNodeinfo = null;
XWikiRCSNodeInfo nodeinfo = null;
for (int i = 0; i < revisions.length; i++) {
nodeinfo = nextNodeinfo;
nextNodeinfo = getRevisionInfo(revisions[i].toString(), context);
if (nodeinfo == null) {
continue;
}
// Minor/Major version matching
if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) {
// Author matching
if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) {
// Date range matching
Date versionDate = nodeinfo.getDate();
if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) {
results.add(nodeinfo.getVersion().toString());
}
}
}
}
nodeinfo = nextNodeinfo;
if (nodeinfo != null) {
if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) {
// Date range matching
Date versionDate = nodeinfo.getDate();
if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) {
results.add(nodeinfo.getVersion().toString());
}
}
}
return criteria.getRange().subList(results);
}
public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException
{
return getDocumentArchive(context).getNode(new Version(version));
}
/**
* @return Is this version the most recent one. False if and only if there are newer versions of this document in
* the database.
*/
public boolean isMostRecent()
{
return this.mostRecent;
}
/**
* must not be used unless in store system.
*
* @param mostRecent - mark document as most recent.
*/
public void setMostRecent(boolean mostRecent)
{
this.mostRecent = mostRecent;
}
public BaseClass getxWikiClass()
{
if (this.xWikiClass == null) {
this.xWikiClass = new BaseClass();
this.xWikiClass.setName(getFullName());
}
return this.xWikiClass;
}
public void setxWikiClass(BaseClass xWikiClass)
{
this.xWikiClass = xWikiClass;
}
public Map<String, Vector<BaseObject>> getxWikiObjects()
{
return this.xWikiObjects;
}
public void setxWikiObjects(Map<String, Vector<BaseObject>> xWikiObjects)
{
this.xWikiObjects = xWikiObjects;
}
public BaseObject getxWikiObject()
{
return getObject(getFullName());
}
public List<BaseClass> getxWikiClasses(XWikiContext context)
{
List<BaseClass> list = new ArrayList<BaseClass>();
// xWikiObjects is a TreeMap, with elements sorted by className
for (String classname : getxWikiObjects().keySet()) {
BaseClass bclass = null;
Vector<BaseObject> objects = getObjects(classname);
for (BaseObject obj : objects) {
if (obj != null) {
bclass = obj.getxWikiClass(context);
if (bclass != null) {
break;
}
}
}
if (bclass != null) {
list.add(bclass);
}
}
return list;
}
public int createNewObject(String classname, XWikiContext context) throws XWikiException
{
BaseObject object = BaseClass.newCustomClassInstance(classname, context);
object.setWiki(getDatabase());
object.setName(getFullName());
object.setClassName(classname);
Vector<BaseObject> objects = getObjects(classname);
if (objects == null) {
objects = new Vector<BaseObject>();
setObjects(classname, objects);
}
objects.add(object);
int nb = objects.size() - 1;
object.setNumber(nb);
setContentDirty(true);
return nb;
}
public int getObjectNumbers(String classname)
{
try {
return getxWikiObjects().get(classname).size();
} catch (Exception e) {
return 0;
}
}
public Vector<BaseObject> getObjects(String classname)
{
if (classname == null) {
return new Vector<BaseObject>();
}
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return getxWikiObjects().get(classname);
}
public void setObjects(String classname, Vector<BaseObject> objects)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
getxWikiObjects().put(classname, objects);
}
public BaseObject getObject(String classname)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
Vector<BaseObject> objects = getxWikiObjects().get(classname);
if (objects == null) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = objects.get(i);
if (obj != null) {
return obj;
}
}
return null;
}
public BaseObject getObject(String classname, int nb)
{
try {
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return getxWikiObjects().get(classname).get(nb);
} catch (Exception e) {
return null;
}
}
public BaseObject getObject(String classname, String key, String value)
{
return getObject(classname, key, value, false);
}
public BaseObject getObject(String classname, String key, String value, boolean failover)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
try {
if (value == null) {
if (failover) {
return getObject(classname);
} else {
return null;
}
}
Vector<BaseObject> objects = getxWikiObjects().get(classname);
if ((objects == null) || (objects.size() == 0)) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = objects.get(i);
if (obj != null) {
if (value.equals(obj.getStringValue(key))) {
return obj;
}
}
}
if (failover) {
return getObject(classname);
} else {
return null;
}
} catch (Exception e) {
if (failover) {
return getObject(classname);
}
e.printStackTrace();
return null;
}
}
public void addObject(String classname, BaseObject object)
{
if (object != null) {
object.setWiki(getDatabase());
object.setName(getFullName());
}
Vector<BaseObject> vobj = getObjects(classname);
if (vobj == null) {
setObject(classname, 0, object);
} else {
setObject(classname, vobj.size(), object);
}
setContentDirty(true);
}
public void setObject(String classname, int nb, BaseObject object)
{
if (object != null) {
object.setWiki(getDatabase());
object.setName(getFullName());
}
Vector<BaseObject> objects = getObjects(classname);
if (objects == null) {
objects = new Vector<BaseObject>();
setObjects(classname, objects);
}
if (nb >= objects.size()) {
objects.setSize(nb + 1);
}
objects.set(nb, object);
object.setNumber(nb);
setContentDirty(true);
}
/**
* @return true if the document is a new one (i.e. it has never been saved) or false otherwise
*/
public boolean isNew()
{
return this.isNew;
}
public void setNew(boolean aNew)
{
this.isNew = aNew;
}
public void mergexWikiClass(XWikiDocument templatedoc)
{
BaseClass bclass = getxWikiClass();
BaseClass tbclass = templatedoc.getxWikiClass();
if (tbclass != null) {
if (bclass == null) {
setxWikiClass((BaseClass) tbclass.clone());
} else {
getxWikiClass().merge((BaseClass) tbclass.clone());
}
}
setContentDirty(true);
}
public void mergexWikiObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
for (String name : templatedoc.getxWikiObjects().keySet()) {
Vector<BaseObject> myObjects = getxWikiObjects().get(name);
if (myObjects == null) {
myObjects = new Vector<BaseObject>();
}
for (BaseObject otherObject : templatedoc.getxWikiObjects().get(name)) {
if (otherObject != null) {
BaseObject myObject = (BaseObject) otherObject.clone();
// BaseObject.clone copies the GUID, so randomize it for the copied object.
myObject.setGuid(UUID.randomUUID().toString());
myObjects.add(myObject);
myObject.setNumber(myObjects.size() - 1);
}
}
getxWikiObjects().put(name, myObjects);
}
setContentDirty(true);
}
public void clonexWikiObjects(XWikiDocument templatedoc)
{
for (String name : templatedoc.getxWikiObjects().keySet()) {
Vector<BaseObject> tobjects = templatedoc.getObjects(name);
Vector<BaseObject> objects = new Vector<BaseObject>();
objects.setSize(tobjects.size());
for (int i = 0; i < tobjects.size(); i++) {
BaseObject otherObject = tobjects.get(i);
if (otherObject != null) {
BaseObject myObject = (BaseObject) otherObject.clone();
objects.set(i, myObject);
}
}
getxWikiObjects().put(name, objects);
}
}
public String getTemplate()
{
return StringUtils.defaultString(this.template);
}
public void setTemplate(String template)
{
this.template = template;
setMetaDataDirty(true);
}
public String displayPrettyName(String fieldname, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayPrettyName(fieldname, showMandatory, before, object, context);
} catch (Exception e) {
return "";
}
}
public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj,
XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String dprettyName = "";
if (showMandatory) {
dprettyName = context.getWiki().addMandatory(context);
}
if (before) {
return dprettyName + pclass.getPrettyName(context);
} else {
return pclass.getPrettyName(context) + dprettyName;
}
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayTooltip(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String tooltip = pclass.getTooltip(context);
if ((tooltip != null) && (!tooltip.trim().equals(""))) {
String img =
"<img src=\"" + context.getWiki().getSkinFile("info.gif", context)
+ "\" class=\"tooltip_image\" align=\"middle\" />";
return context.getWiki().addTooltip(img, tooltip, context);
} else {
return "";
}
} catch (Exception e) {
return "";
}
}
public String display(String fieldname, String type, BaseObject obj, XWikiContext context)
{
return display(fieldname, type, "", obj, context.getWiki().getCurrentContentSyntaxId(getSyntaxId(), context),
context);
}
/**
* Note: We've introduced this signature taking an extra syntaxId parameter to handle the case where Panels are
* written in a syntax other than the main document. The problem is that currently the displayPanel() velocity macro
* in macros.vm calls display() on the main document and not on the panel document. Thus if we don't tell what
* syntax to use the main document syntax will be used to display panels even if they're written in another syntax.
*/
public String display(String fieldname, String type, BaseObject obj, String syntaxId, XWikiContext context)
{
return display(fieldname, type, "", obj, syntaxId, context);
}
public String display(String fieldname, String type, String pref, BaseObject obj, String syntaxId,
XWikiContext context)
{
if (obj == null) {
return "";
}
boolean isInRenderingEngine = BooleanUtils.toBoolean((Boolean) context.get("isInRenderingEngine"));
HashMap<String, Object> backup = new HashMap<String, Object>();
try {
backupContext(backup, context);
setAsContextDoc(context);
type = type.toLowerCase();
StringBuffer result = new StringBuffer();
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_";
if (pclass.isCustomDisplayed(context)) {
pclass.displayCustom(result, fieldname, prefix, type, obj, context);
} else if (type.equals("view")) {
pclass.displayView(result, fieldname, prefix, obj, context);
} else if (type.equals("rendered")) {
String fcontent = pclass.displayView(fieldname, prefix, obj, context);
// This mode is deprecated for the new rendering and should also be removed for the old rendering
// since the way to implement this now is to choose the type of rendering to do in the class itself.
// Thus for the new rendering we simply make this mode work like the "view" mode.
if (is10Syntax(syntaxId)) {
result.append(getRenderedContent(fcontent, getSyntaxId(), context));
} else {
result.append(fcontent);
}
} else if (type.equals("edit")) {
context.addDisplayedField(fieldname);
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
// If the Syntax id is not "xwiki/1.0", i.e. if the new rendering engine is used then we need to
// protect the content with a <pre> since otherwise whitespaces will be stripped by the HTML macro
// used to surround the object property content (see below).
if (is10Syntax(syntaxId)) {
result.append("{pre}");
} else {
result.append("<pre>");
}
pclass.displayEdit(result, fieldname, prefix, obj, context);
if (is10Syntax(syntaxId)) {
result.append("{/pre}");
} else {
result.append("</pre>");
}
} else if (type.equals("hidden")) {
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
if (is10Syntax(syntaxId)) {
result.append("{pre}");
}
pclass.displayHidden(result, fieldname, prefix, obj, context);
if (is10Syntax(syntaxId)) {
result.append("{/pre}");
}
} else if (type.equals("search")) {
// If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
// rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
// escaping. For example for a textarea check the TextAreaClass class.
if (is10Syntax(syntaxId)) {
result.append("{pre}");
}
prefix = obj.getxWikiClass(context).getName() + "_";
pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context);
if (is10Syntax(syntaxId)) {
result.append("{/pre}");
}
} else {
pclass.displayView(result, fieldname, prefix, obj, context);
}
// If we're in new rendering engine we want to wrap the HTML returned by displayView() in
// a {{html/}} macro so that the user doesn't have to do it.
// We test if we're inside the rendering engine since it's also possible that this display() method is
// called
// directly from a template and in this case we only want HTML as a result and not wiki syntax.
// TODO: find a more generic way to handle html macro because this works only for XWiki 1.0 and XWiki 2.0
// Add the {{html}}{{/html}} only when result really contains html since it's not needed for pure text
if (isInRenderingEngine && !is10Syntax(syntaxId)
&& (result.indexOf("<") != -1 || result.indexOf(">") != -1)) {
result.insert(0, "{{html clean=\"false\" wiki=\"false\"}}");
result.append("{{/html}}");
}
return result.toString();
} catch (Exception ex) {
// TODO: It would better to check if the field exists rather than catching an exception
// raised by a NPE as this is currently the case here...
LOG.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object ["
+ (obj == null ? "NULL" : obj.getName()) + "]");
ex.printStackTrace();
return "";
} finally {
restoreContext(backup, context);
}
}
public String display(String fieldname, BaseObject obj, XWikiContext context)
{
String type = null;
try {
type = (String) context.get("display");
} catch (Exception e) {
}
if (type == null) {
type = "view";
}
return display(fieldname, type, obj, context);
}
public String display(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return display(fieldname, object, context);
} catch (Exception e) {
LOG.error("Failed to display field " + fieldname + " of document " + getFullName(), e);
}
return "";
}
public String display(String fieldname, String mode, XWikiContext context)
{
return display(fieldname, mode, "", context);
}
public String display(String fieldname, String mode, String prefix, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
if (object == null) {
return "";
} else {
return display(fieldname, mode, prefix, object, context.getDoc() != null ? context.getDoc()
.getSyntaxId() : getSyntaxId(), context);
}
} catch (Exception e) {
return "";
}
}
public String displayForm(String className, String header, String format, XWikiContext context)
{
return displayForm(className, header, format, true, context);
}
public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context)
{
Vector<BaseObject> objects = getObjects(className);
if (format.endsWith("\\n")) {
linebreak = true;
}
BaseObject firstobject = null;
Iterator<BaseObject> foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
if (bclass.getPropertyList().size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
VelocityContext vcontext = new VelocityContext();
for (String propertyName : bclass.getPropertyList()) {
PropertyClass pclass = (PropertyClass) bclass.getField(propertyName);
vcontext.put(pclass.getName(), pclass.getPrettyName());
}
result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context));
if (linebreak) {
result.append("\n");
}
// display each line
for (int i = 0; i < objects.size(); i++) {
vcontext.put("id", new Integer(i + 1));
BaseObject object = objects.get(i);
if (object != null) {
for (String name : bclass.getPropertyList()) {
vcontext.put(name, display(name, object, context));
}
result
.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(), vcontext, context));
if (linebreak) {
result.append("\n");
}
}
}
return result.toString();
}
public String displayForm(String className, XWikiContext context)
{
Vector<BaseObject> objects = getObjects(className);
if (objects == null) {
return "";
}
BaseObject firstobject = null;
Iterator<BaseObject> foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
if (bclass.getPropertyList().size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
result.append("{table}\n");
boolean first = true;
for (String propertyName : bclass.getPropertyList()) {
if (first == true) {
first = false;
} else {
result.append("|");
}
PropertyClass pclass = (PropertyClass) bclass.getField(propertyName);
result.append(pclass.getPrettyName());
}
result.append("\n");
for (int i = 0; i < objects.size(); i++) {
BaseObject object = objects.get(i);
if (object != null) {
first = true;
for (String propertyName : bclass.getPropertyList()) {
if (first == true) {
first = false;
} else {
result.append("|");
}
String data = display(propertyName, object, context);
data = data.trim();
data = data.replaceAll("\n", " ");
if (data.length() == 0) {
result.append(" ");
} else {
result.append(data);
}
}
result.append("\n");
}
}
result.append("{table}\n");
return result.toString();
}
public boolean isFromCache()
{
return this.fromCache;
}
public void setFromCache(boolean fromCache)
{
this.fromCache = fromCache;
}
public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String defaultLanguage = eform.getDefaultLanguage();
if (defaultLanguage != null) {
setDefaultLanguage(defaultLanguage);
}
String defaultTemplate = eform.getDefaultTemplate();
if (defaultTemplate != null) {
setDefaultTemplate(defaultTemplate);
}
String creator = eform.getCreator();
if ((creator != null) && (!creator.equals(getCreator()))) {
if ((getCreator().equals(context.getUser()))
|| (context.getWiki().getRightService().hasAdminRights(context))) {
setCreator(creator);
}
}
String parent = eform.getParent();
if (parent != null) {
setParent(parent);
}
// Read the comment from the form
String comment = eform.getComment();
if (comment != null) {
setComment(comment);
}
// Read the minor edit checkbox from the form
setMinorEdit(eform.isMinorEdit());
String tags = eform.getTags();
if (tags != null) {
setTags(tags, context);
}
// Set the Syntax id if defined
String syntaxId = eform.getSyntaxId();
if (syntaxId != null) {
setSyntaxId(syntaxId);
}
}
/**
* add tags to the document.
*/
public void setTags(String tags, XWikiContext context) throws XWikiException
{
loadTags(context);
StaticListClass tagProp =
(StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS);
tagProp.fromString(tags);
this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags));
setMetaDataDirty(true);
}
public String getTags(XWikiContext context)
{
ListProperty prop = (ListProperty) getTagProperty(context);
if (prop != null) {
return prop.getTextValue();
}
return null;
}
public List<String> getTagsList(XWikiContext context)
{
List<String> tagList = null;
BaseProperty prop = getTagProperty(context);
if (prop != null) {
tagList = (List<String>) prop.getValue();
}
return tagList;
}
private BaseProperty getTagProperty(XWikiContext context)
{
loadTags(context);
return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS));
}
private void loadTags(XWikiContext context)
{
if (this.tags == null) {
this.tags = getObject(XWikiConstant.TAG_CLASS, true, context);
}
}
public List getTagsPossibleValues(XWikiContext context)
{
loadTags(context);
String possibleValues =
((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS))
.getValues();
return ListClass.getListFromString(possibleValues);
// ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString();
}
public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String content = eform.getContent();
if (content != null) {
// Cleanup in case we use HTMLAREA
// content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g",
// content);
content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content);
setContent(content);
}
String title = eform.getTitle();
if (title != null) {
setTitle(title);
}
}
public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
for (String name : getxWikiObjects().keySet()) {
Vector<BaseObject> oldObjects = getObjects(name);
Vector<BaseObject> newObjects = new Vector<BaseObject>();
newObjects.setSize(oldObjects.size());
for (int i = 0; i < oldObjects.size(); i++) {
BaseObject oldobject = oldObjects.get(i);
if (oldobject != null) {
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject =
(BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setGuid(oldobject.getGuid());
newobject.setName(getFullName());
newObjects.set(newobject.getNumber(), newobject);
}
}
getxWikiObjects().put(name, newObjects);
}
setContentDirty(true);
}
public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
readDocMetaFromForm(eform, context);
readTranslationMetaFromForm(eform, context);
readObjectsFromForm(eform, context);
}
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException
{
String template = eform.getTemplate();
readFromTemplate(template, context);
}
public void readFromTemplate(String template, XWikiContext context) throws XWikiException
{
if ((template != null) && (!template.equals(""))) {
String content = getContent();
if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) {
Object[] args = {getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
"Cannot add a template to document {0} because it already has content", null, args);
} else {
if (template.indexOf('.') == -1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = {template, getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplate(template);
setContent(templatedoc.getContent());
// Set the new document syntax as the syntax of the template since the template content
// is copied into the new document
setSyntaxId(templatedoc.getSyntaxId());
if ((getParent() == null) || (getParent().equals(""))) {
String tparent = templatedoc.getParent();
if (tparent != null) {
setParent(tparent);
}
}
if (isNew()) {
// We might have received the object from the cache
// and the template objects might have been copied already
// we need to remove them
setxWikiObjects(new TreeMap<String, Vector<BaseObject>>());
}
// Merge the external objects
// Currently the choice is not to merge the base class and object because it is
// not
// the prefered way of using external classes and objects.
mergexWikiObjects(templatedoc);
}
}
}
setContentDirty(true);
}
public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event,
XWikiContext context)
{
// Do nothing for the moment..
// A useful thing here would be to look at any instances of a Notification Object
// with email addresses and send an email to warn that the document has been modified..
}
/**
* Use the document passed as parameter as the new identity for the current document.
*
* @param document the document containing the new identity
* @throws XWikiException in case of error
*/
private void clone(XWikiDocument document) throws XWikiException
{
setDatabase(document.getDatabase());
setRCSVersion(document.getRCSVersion());
setDocumentArchive(document.getDocumentArchive());
setAuthor(document.getAuthor());
setContentAuthor(document.getContentAuthor());
setContent(document.getContent());
setContentDirty(document.isContentDirty());
setCreationDate(document.getCreationDate());
setDate(document.getDate());
setCustomClass(document.getCustomClass());
setContentUpdateDate(document.getContentUpdateDate());
setTitle(document.getTitle());
setFormat(document.getFormat());
setFromCache(document.isFromCache());
setElements(document.getElements());
setId(document.getId());
setMeta(document.getMeta());
setMetaDataDirty(document.isMetaDataDirty());
setMostRecent(document.isMostRecent());
setName(document.getName());
setNew(document.isNew());
setStore(document.getStore());
setTemplate(document.getTemplate());
setSpace(document.getSpace());
setParent(document.getParent());
setCreator(document.getCreator());
setDefaultLanguage(document.getDefaultLanguage());
setDefaultTemplate(document.getDefaultTemplate());
setValidationScript(document.getValidationScript());
setLanguage(document.getLanguage());
setTranslation(document.getTranslation());
setxWikiClass((BaseClass) document.getxWikiClass().clone());
setxWikiClassXML(document.getxWikiClassXML());
setComment(document.getComment());
setMinorEdit(document.isMinorEdit());
setSyntaxId(document.getSyntaxId());
setHidden(document.isHidden());
clonexWikiObjects(document);
copyAttachments(document);
this.elements = document.elements;
this.originalDocument = document.originalDocument;
}
@Override
public Object clone()
{
XWikiDocument doc = null;
try {
doc = getClass().newInstance();
doc.setDatabase(getDatabase());
// use version field instead of getRCSVersion because it returns "1.1" if version==null.
doc.version = this.version;
doc.setDocumentArchive(getDocumentArchive());
doc.setAuthor(getAuthor());
doc.setContentAuthor(getContentAuthor());
doc.setContent(getContent());
doc.setContentDirty(isContentDirty());
doc.setCreationDate(getCreationDate());
doc.setDate(getDate());
doc.setCustomClass(getCustomClass());
doc.setContentUpdateDate(getContentUpdateDate());
doc.setTitle(getTitle());
doc.setFormat(getFormat());
doc.setFromCache(isFromCache());
doc.setElements(getElements());
doc.setId(getId());
doc.setMeta(getMeta());
doc.setMetaDataDirty(isMetaDataDirty());
doc.setMostRecent(isMostRecent());
doc.setName(getName());
doc.setNew(isNew());
doc.setStore(getStore());
doc.setTemplate(getTemplate());
doc.setSpace(getSpace());
doc.setParent(getParent());
doc.setCreator(getCreator());
doc.setDefaultLanguage(getDefaultLanguage());
doc.setDefaultTemplate(getDefaultTemplate());
doc.setValidationScript(getValidationScript());
doc.setLanguage(getLanguage());
doc.setTranslation(getTranslation());
doc.setxWikiClass((BaseClass) getxWikiClass().clone());
doc.setxWikiClassXML(getxWikiClassXML());
doc.setComment(getComment());
doc.setMinorEdit(isMinorEdit());
doc.setSyntaxId(getSyntaxId());
doc.setHidden(isHidden());
doc.clonexWikiObjects(this);
doc.copyAttachments(this);
doc.elements = this.elements;
doc.originalDocument = this.originalDocument;
} catch (Exception e) {
// This should not happen
LOG.error("Exception while doc.clone", e);
}
return doc;
}
public void copyAttachments(XWikiDocument xWikiSourceDocument)
{
getAttachmentList().clear();
Iterator<XWikiAttachment> attit = xWikiSourceDocument.getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = attit.next();
XWikiAttachment newattachment = (XWikiAttachment) attachment.clone();
newattachment.setDoc(this);
if (newattachment.getAttachment_content() != null) {
newattachment.getAttachment_content().setContentDirty(true);
}
getAttachmentList().add(newattachment);
}
setContentDirty(true);
}
public void loadAttachments(XWikiContext context) throws XWikiException
{
for (XWikiAttachment attachment : getAttachmentList()) {
attachment.loadContent(context);
attachment.loadArchive(context);
}
}
@Override
public boolean equals(Object object)
{
XWikiDocument doc = (XWikiDocument) object;
if (!getName().equals(doc.getName())) {
return false;
}
if (!getSpace().equals(doc.getSpace())) {
return false;
}
if (!getAuthor().equals(doc.getAuthor())) {
return false;
}
if (!getContentAuthor().equals(doc.getContentAuthor())) {
return false;
}
if (!getParent().equals(doc.getParent())) {
return false;
}
if (!getCreator().equals(doc.getCreator())) {
return false;
}
if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) {
return false;
}
if (!getLanguage().equals(doc.getLanguage())) {
return false;
}
if (getTranslation() != doc.getTranslation()) {
return false;
}
if (getDate().getTime() != doc.getDate().getTime()) {
return false;
}
if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) {
return false;
}
if (getCreationDate().getTime() != doc.getCreationDate().getTime()) {
return false;
}
if (!getFormat().equals(doc.getFormat())) {
return false;
}
if (!getTitle().equals(doc.getTitle())) {
return false;
}
if (!getContent().equals(doc.getContent())) {
return false;
}
if (!getVersion().equals(doc.getVersion())) {
return false;
}
if (!getTemplate().equals(doc.getTemplate())) {
return false;
}
if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) {
return false;
}
if (!getValidationScript().equals(doc.getValidationScript())) {
return false;
}
if (!getComment().equals(doc.getComment())) {
return false;
}
if (isMinorEdit() != doc.isMinorEdit()) {
return false;
}
if ((getSyntaxId() != null && !getSyntaxId().equals(doc.getSyntaxId()))
|| (getSyntaxId() == null && doc.getSyntaxId() != null)) {
return false;
}
if (isHidden() != doc.isHidden()) {
return false;
}
if (!getxWikiClass().equals(doc.getxWikiClass())) {
return false;
}
Set<String> myObjectClassnames = getxWikiObjects().keySet();
Set<String> otherObjectClassnames = doc.getxWikiObjects().keySet();
if (!myObjectClassnames.equals(otherObjectClassnames)) {
return false;
}
for (String name : myObjectClassnames) {
Vector<BaseObject> myObjects = getObjects(name);
Vector<BaseObject> otherObjects = doc.getObjects(name);
if (myObjects.size() != otherObjects.size()) {
return false;
}
for (int i = 0; i < myObjects.size(); i++) {
if ((myObjects.get(i) == null) && (otherObjects.get(i) != null)) {
return false;
}
if (!myObjects.get(i).equals(otherObjects.get(i))) {
return false;
}
}
}
// We consider that 2 documents are still equal even when they have different original
// documents (see getOriginalDocument() for more details as to what is an original
// document).
return true;
}
public String toXML(Document doc, XWikiContext context)
{
OutputFormat outputFormat = new OutputFormat("", true);
if ((context == null) || (context.getWiki() == null)) {
outputFormat.setEncoding("UTF-8");
} else {
outputFormat.setEncoding(context.getWiki().getEncoding());
}
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String getXMLContent(XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(context);
Document doc = tdoc.toXMLDocument(true, true, false, false, context);
return toXML(doc, context);
}
public String toXML(XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(context);
return toXML(doc, context);
}
public String toFullXML(XWikiContext context) throws XWikiException
{
return toXML(true, false, true, true, context);
}
public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException
{
try {
String zipname = getSpace() + "/" + getName();
String language = getLanguage();
if ((language != null) && (!language.equals(""))) {
zipname += "." + language;
}
ZipEntry zipentry = new ZipEntry(zipname);
zos.putNextEntry(zipentry);
zos.write(toXML(true, false, true, withVersions, context).getBytes());
zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException
{
addToZip(zos, true, context);
}
public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
return toXML(doc, context);
}
public Document toXMLDocument(XWikiContext context) throws XWikiException
{
return toXMLDocument(true, false, false, false, context);
}
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
boolean bWithVersions, XWikiContext context) throws XWikiException
{
Document doc = new DOMDocument();
Element docel = new DOMElement("xwikidoc");
doc.setRootElement(docel);
Element el = new DOMElement("web");
el.addText(getSpace());
docel.add(el);
el = new DOMElement("name");
el.addText(getName());
docel.add(el);
el = new DOMElement("language");
el.addText(getLanguage());
docel.add(el);
el = new DOMElement("defaultLanguage");
el.addText(getDefaultLanguage());
docel.add(el);
el = new DOMElement("translation");
el.addText("" + getTranslation());
docel.add(el);
el = new DOMElement("parent");
el.addText(getParent());
docel.add(el);
el = new DOMElement("creator");
el.addText(getCreator());
docel.add(el);
el = new DOMElement("author");
el.addText(getAuthor());
docel.add(el);
el = new DOMElement("customClass");
el.addText(getCustomClass());
docel.add(el);
el = new DOMElement("contentAuthor");
el.addText(getContentAuthor());
docel.add(el);
long d = getCreationDate().getTime();
el = new DOMElement("creationDate");
el.addText("" + d);
docel.add(el);
d = getDate().getTime();
el = new DOMElement("date");
el.addText("" + d);
docel.add(el);
d = getContentUpdateDate().getTime();
el = new DOMElement("contentUpdateDate");
el.addText("" + d);
docel.add(el);
el = new DOMElement("version");
el.addText(getVersion());
docel.add(el);
el = new DOMElement("title");
el.addText(getTitle());
docel.add(el);
el = new DOMElement("template");
el.addText(getTemplate());
docel.add(el);
el = new DOMElement("defaultTemplate");
el.addText(getDefaultTemplate());
docel.add(el);
el = new DOMElement("validationScript");
el.addText(getValidationScript());
docel.add(el);
el = new DOMElement("comment");
el.addText(getComment());
docel.add(el);
el = new DOMElement("minorEdit");
el.addText(String.valueOf(isMinorEdit()));
docel.add(el);
el = new DOMElement("syntaxId");
el.addText(getSyntaxId());
docel.add(el);
el = new DOMElement("hidden");
el.addText(String.valueOf(isHidden()));
docel.add(el);
for (XWikiAttachment attach : getAttachmentList()) {
docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context));
}
if (bWithObjects) {
// Add Class
BaseClass bclass = getxWikiClass();
if (bclass.getFieldList().size() > 0) {
// If the class has fields, add class definition and field information to XML
docel.add(bclass.toXML(null));
}
// Add Objects (THEIR ORDER IS MOLDED IN STONE!)
for (Vector<BaseObject> objects : getxWikiObjects().values()) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass objclass = null;
if (StringUtils.equals(getFullName(), obj.getClassName())) {
objclass = bclass;
} else {
objclass = obj.getxWikiClass(context);
}
docel.add(obj.toXML(objclass));
}
}
}
}
// Add Content
el = new DOMElement("content");
// Filter filter = new CharacterFilter();
// String newcontent = filter.process(getContent());
// String newcontent = encodedXMLStringAsUTF8(getContent());
String newcontent = this.content;
el.addText(newcontent);
docel.add(el);
if (bWithRendering) {
el = new DOMElement("renderedcontent");
try {
el.addText(getRenderedContent(context));
} catch (XWikiException e) {
el.addText("Exception with rendering content: " + e.getFullMessage());
}
docel.add(el);
}
if (bWithVersions) {
el = new DOMElement("versions");
try {
el.addText(getDocumentArchive(context).getArchive(context));
docel.add(el);
} catch (XWikiException e) {
LOG.error("Document [" + this.getFullName() + "] has malformed history");
}
}
return doc;
}
protected String encodedXMLStringAsUTF8(String xmlString)
{
if (xmlString == null) {
return "";
}
int length = xmlString.length();
char character;
StringBuffer result = new StringBuffer();
for (int i = 0; i < length; i++) {
character = xmlString.charAt(i);
switch (character) {
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\n':
result.append("\n");
break;
case '\r':
result.append("\r");
break;
case '\t':
result.append("\t");
break;
default:
if (character < 0x20) {
} else if (character > 0x7F) {
result.append("&
result.append(Integer.toHexString(character).toUpperCase());
result.append(";");
} else {
result.append(character);
}
break;
}
}
return result.toString();
}
protected String getElement(Element docel, String name)
{
Element el = docel.element(name);
if (el == null) {
return "";
} else {
return el.getText();
}
}
public void fromXML(String xml) throws XWikiException
{
fromXML(xml, false);
}
public void fromXML(InputStream is) throws XWikiException
{
fromXML(is, false);
}
public void fromXML(String xml, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(xml);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,
"Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(InputStream in, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,
"Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(Document domdoc, boolean withArchive) throws XWikiException
{
Element docel = domdoc.getRootElement();
setName(getElement(docel, "name"));
setSpace(getElement(docel, "web"));
setParent(getElement(docel, "parent"));
setCreator(getElement(docel, "creator"));
setAuthor(getElement(docel, "author"));
setCustomClass(getElement(docel, "customClass"));
setContentAuthor(getElement(docel, "contentAuthor"));
if (docel.element("version") != null) {
setVersion(getElement(docel, "version"));
}
setContent(getElement(docel, "content"));
setLanguage(getElement(docel, "language"));
setDefaultLanguage(getElement(docel, "defaultLanguage"));
setTitle(getElement(docel, "title"));
setDefaultTemplate(getElement(docel, "defaultTemplate"));
setValidationScript(getElement(docel, "validationScript"));
setComment(getElement(docel, "comment"));
String minorEdit = getElement(docel, "minorEdit");
setMinorEdit(Boolean.valueOf(minorEdit).booleanValue());
String hidden = getElement(docel, "hidden");
setHidden(Boolean.valueOf(hidden).booleanValue());
String strans = getElement(docel, "translation");
if ((strans == null) || strans.equals("")) {
setTranslation(0);
} else {
setTranslation(Integer.parseInt(strans));
}
String archive = getElement(docel, "versions");
if (withArchive && archive != null && archive.length() > 0) {
setDocumentArchive(archive);
}
String sdate = getElement(docel, "date");
if (!sdate.equals("")) {
Date date = new Date(Long.parseLong(sdate));
setDate(date);
}
String contentUpdateDateString = getElement(docel, "contentUpdateDate");
if (!StringUtils.isEmpty(contentUpdateDateString)) {
Date contentUpdateDate = new Date(Long.parseLong(contentUpdateDateString));
setContentUpdateDate(contentUpdateDate);
}
String scdate = getElement(docel, "creationDate");
if (!scdate.equals("")) {
Date cdate = new Date(Long.parseLong(scdate));
setCreationDate(cdate);
}
String syntaxId = getElement(docel, "syntaxId");
if ((syntaxId == null) || (syntaxId.length() == 0)) {
// Documents that don't have syntax ids are considered old documents and thus in
// XWiki Syntax 1.0 since newer documents always have syntax ids.
setSyntaxId(XWIKI10_SYNTAXID);
} else {
setSyntaxId(syntaxId);
}
List atels = docel.elements("attachment");
for (int i = 0; i < atels.size(); i++) {
Element atel = (Element) atels.get(i);
XWikiAttachment attach = new XWikiAttachment();
attach.setDoc(this);
attach.fromXML(atel);
getAttachmentList().add(attach);
}
Element cel = docel.element("class");
BaseClass bclass = new BaseClass();
if (cel != null) {
bclass.fromXML(cel);
setxWikiClass(bclass);
}
List objels = docel.elements("object");
for (int i = 0; i < objels.size(); i++) {
Element objel = (Element) objels.get(i);
BaseObject bobject = new BaseObject();
bobject.fromXML(objel);
setObject(bobject.getClassName(), bobject.getNumber(), bobject);
}
// We have been reading from XML so the document does not need a new version when saved
setMetaDataDirty(false);
setContentDirty(false);
// Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to
// have an original document for a de-serialized object.
}
/**
* Check if provided xml document is a wiki document.
*
* @param domdoc the xml document.
* @return true if provided xml document is a wiki document.
*/
public static boolean containsXMLWikiDocument(Document domdoc)
{
return domdoc.getRootElement().getName().equals("xwikidoc");
}
public void setAttachmentList(List<XWikiAttachment> list)
{
this.attachmentList = list;
}
public List<XWikiAttachment> getAttachmentList()
{
return this.attachmentList;
}
public void saveAllAttachments(XWikiContext context) throws XWikiException
{
for (int i = 0; i < this.attachmentList.size(); i++) {
saveAttachmentContent(this.attachmentList.get(i), context);
}
}
public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context)
throws XWikiException
{
for (int i = 0; i < this.attachmentList.size(); i++) {
saveAttachmentContent(this.attachmentList.get(i), updateParent, transaction, context);
}
}
public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
saveAttachmentContent(attachment, true, true, context);
}
public void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction,
XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
// We need to make sure there is a version upgrade
setMetaDataDirty(true);
context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context,
bTransaction);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true);
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException
{
deleteAttachment(attachment, true, context);
}
public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
try {
// We need to make sure there is a version upgrade
setMetaDataDirty(true);
if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) {
context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(),
new Date(), context, true);
}
context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception");
}
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
/**
* Get the wiki pages pointing to this page.
* <p>
* Theses links are stored to the database when documents are saved. You can use "backlinks" in XWikiPreferences or
* "xwiki.backlinks" in xwiki.cfg file to enable links storage in the database.
*
* @param context the XWiki context.
* @return the found wiki pages names.
* @throws XWikiException error when getting pages names from database.
*/
public List<String> getBackLinkedPages(XWikiContext context) throws XWikiException
{
return getStore(context).loadBacklinks(getFullName(), context, true);
}
/**
* Get a list of unique links from this document to others documents.
* <p>
* <ul>
* <li>1.0 content: get the unique links associated to document from database. This is stored when the document is
* saved. You can use "backlinks" in XWikiPreferences or "xwiki.backlinks" in xwiki.cfg file to enable links storage
* in the database.</li>
* <li>Other content: call {@link #getUniqueLinkedPages(XWikiContext)} and generate the List</li>.
* </ul>
*
* @param context the XWiki context
* @return the found wiki links.
* @throws XWikiException error when getting links from database when 1.0 content.
* @since 1.9M2
*/
public Set<XWikiLink> getUniqueWikiLinkedPages(XWikiContext context) throws XWikiException
{
Set<XWikiLink> links;
if (is10Syntax()) {
links = new LinkedHashSet<XWikiLink>(getStore(context).loadLinks(getId(), context, true));
} else {
Set<String> linkedPages = getUniqueLinkedPages(context);
links = new LinkedHashSet<XWikiLink>(linkedPages.size());
for (String linkedPage : linkedPages) {
XWikiLink wikiLink = new XWikiLink();
wikiLink.setDocId(getId());
wikiLink.setFullName(getFullName());
wikiLink.setLink(linkedPage);
links.add(wikiLink);
}
}
return links;
}
/**
* Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this 1.0
* document's content to others documents.
*
* @param context the XWiki context.
* @return the document names for linked pages, if null an error append.
* @since 1.9M2
*/
private Set<String> getUniqueLinkedPages10(XWikiContext context)
{
Set<String> pageNames;
try {
List<String> list = context.getUtil().getUniqueMatches(getContent(), "\\[(.*?)\\]", 1);
pageNames = new HashSet<String>(list.size());
DocumentName currentDocumentName = getDocumentName();
for (String name : list) {
int i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 1);
}
i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 4);
}
i1 = name.indexOf("
if (i1 != -1) {
name = name.substring(0, i1);
}
i1 = name.indexOf("?");
if (i1 != -1) {
name = name.substring(0, i1);
}
// Let's get rid of anything that's not a real link
if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(":
|| (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1)
|| (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) {
continue;
}
// generate the link
String newname = StringUtils.replace(Util.noaccents(name), " ", "");
// If it is a local link let's add the space
if (newname.indexOf(".") == -1) {
newname = getSpace() + "." + name;
}
if (context.getWiki().exists(newname, context)) {
name = newname;
} else {
// If it is a local link let's add the space
if (name.indexOf(".") == -1) {
name = getSpace() + "." + name;
}
}
// If the reference is empty, the link is an autolink
if (!StringUtils.isEmpty(name)) {
// The reference may not have the space or even document specified (in case of an empty
// string)
// Thus we need to find the fully qualified document name
DocumentName documentName = this.documentNameFactory.createDocumentName(name);
// Verify that the link is not an autolink (i.e. a link to the current document)
if (!documentName.equals(currentDocumentName)) {
pageNames.add(this.compactDocumentNameSerializer.serialize(documentName));
}
}
}
return pageNames;
} catch (Exception e) {
// This should never happen
LOG.error("Failed to get linked documents", e);
return null;
}
}
/**
* Extract all the unique static (i.e. not generated by macros) wiki links (pointing to wiki page) from this
* document's content to others documents.
*
* @param context the XWiki context.
* @return the document names for linked pages, if null an error append.
* @since 1.9M2
*/
public Set<String> getUniqueLinkedPages(XWikiContext context)
{
Set<String> pageNames;
XWikiDocument contextDoc = context.getDoc();
String contextWiki = context.getDatabase();
try {
// Make sure the right document is used as context document
context.setDoc(this);
// Make sure the right wiki is used as context document
context.setDatabase(getDatabase());
if (is10Syntax()) {
pageNames = getUniqueLinkedPages10(context);
} else {
XDOM dom = getXDOM();
List<LinkBlock> linkBlocks = dom.getChildrenByType(LinkBlock.class, true);
pageNames = new LinkedHashSet<String>(linkBlocks.size());
DocumentName currentDocumentName = getDocumentName();
for (LinkBlock linkBlock : linkBlocks) {
org.xwiki.rendering.listener.Link link = linkBlock.getLink();
if (link.getType() == LinkType.DOCUMENT) {
// If the reference is empty, the link is an autolink
if (!StringUtils.isEmpty(link.getReference())
|| (StringUtils.isEmpty(link.getAnchor()) && StringUtils.isEmpty(link.getQueryString()))) {
// The reference may not have the space or even document specified (in case of an empty
// string)
// Thus we need to find the fully qualified document name
DocumentName documentName =
this.documentNameFactory.createDocumentName(link.getReference());
// Verify that the link is not an autolink (i.e. a link to the current document)
if (!documentName.equals(currentDocumentName)) {
pageNames.add(this.compactDocumentNameSerializer.serialize(documentName));
}
}
}
}
}
} finally {
context.setDoc(contextDoc);
context.setDatabase(contextWiki);
}
return pageNames;
}
public List<String> getChildren(XWikiContext context) throws XWikiException
{
String[] whereParams = { this.getWikiName() + ":" + this.getFullName(), this.getFullName(), this.getName(),
this.getSpace() };
String whereStatement = "doc.parent=? or doc.parent=? or (doc.parent=? and doc.space=?)";
return context.getWiki().getStore().searchDocumentsNames(whereStatement, Arrays.asList(whereParams), context);
}
public void renameProperties(String className, Map fieldsToRename)
{
Vector<BaseObject> objects = getObjects(className);
if (objects == null) {
return;
}
for (BaseObject bobject : objects) {
if (bobject == null) {
continue;
}
for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) {
String origname = (String) renameit.next();
String newname = (String) fieldsToRename.get(origname);
BaseProperty origprop = (BaseProperty) bobject.safeget(origname);
if (origprop != null) {
BaseProperty prop = (BaseProperty) origprop.clone();
bobject.removeField(origname);
prop.setName(newname);
bobject.addField(newname, prop);
}
}
}
setContentDirty(true);
}
public void addObjectsToRemove(BaseObject object)
{
getObjectsToRemove().add(object);
setContentDirty(true);
}
public ArrayList<BaseObject> getObjectsToRemove()
{
return this.objectsToRemove;
}
public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove)
{
this.objectsToRemove = objectsToRemove;
setContentDirty(true);
}
public List<String> getIncludedPages(XWikiContext context)
{
if (is10Syntax()) {
return getIncludedPagesForXWiki10Syntax(getContent(), context);
} else {
// Find all include macros listed on the page
XDOM dom = getXDOM();
List<String> result = new ArrayList<String>();
for (MacroBlock macroBlock : dom.getChildrenByType(MacroBlock.class, true)) {
// - Add each document pointed to by the include macro
// - Also add all the included pages found in the velocity macro when using the deprecated #include*
// macros
// This should be removed when we fully drop support for the XWiki Syntax 1.0 but for now we want to
// play
// nice with people migrating from 1.0 to 2.0 syntax
if (macroBlock.getName().equalsIgnoreCase("include")) {
String documentName = macroBlock.getParameters().get("document");
if (documentName.indexOf(".") == -1) {
documentName = getSpace() + "." + documentName;
}
result.add(documentName);
} else if (macroBlock.getName().equalsIgnoreCase("velocity")
&& !StringUtils.isEmpty(macroBlock.getContent())) {
// Try to find matching content inside each velocity macro
result.addAll(getIncludedPagesForXWiki10Syntax(macroBlock.getContent(), context));
}
}
return result;
}
}
private List<String> getIncludedPagesForXWiki10Syntax(String content, XWikiContext context)
{
try {
String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)";
List<String> list = context.getUtil().getUniqueMatches(content, pattern, 2);
for (int i = 0; i < list.size(); i++) {
try {
String name = list.get(i);
if (name.indexOf(".") == -1) {
list.set(i, getSpace() + "." + name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return list;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public List<String> getIncludedMacros(XWikiContext context)
{
return context.getWiki().getIncludedMacros(getSpace(), getContent(), context);
}
public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
throws XWikiException
{
String result = pclass.displayView(pclass.getName(), prefix, object, context);
return getRenderedContent(result, XWIKI10_SYNTAXID, context);
}
public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context);
}
public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context);
}
public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context);
}
public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context)
{
return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context);
}
public XWikiAttachment getAttachment(String filename)
{
for (XWikiAttachment attach : getAttachmentList()) {
if (attach.getFilename().equals(filename)) {
return attach;
}
}
for (XWikiAttachment attach : getAttachmentList()) {
if (attach.getFilename().startsWith(filename + ".")) {
return attach;
}
}
return null;
}
public XWikiAttachment addAttachment(String fileName, InputStream iStream, XWikiContext context)
throws XWikiException, IOException
{
ByteArrayOutputStream bAOut = new ByteArrayOutputStream();
IOUtils.copy(iStream, bAOut);
return addAttachment(fileName, bAOut.toByteArray(), context);
}
public XWikiAttachment addAttachment(String fileName, byte[] data, XWikiContext context) throws XWikiException
{
int i = fileName.indexOf("\\");
if (i == -1) {
i = fileName.indexOf("/");
}
String filename = fileName.substring(i + 1);
// TODO : avoid name clearing when encoding problems will be solved
filename = context.getWiki().clearName(filename, false, true, context);
XWikiAttachment attachment = getAttachment(filename);
if (attachment == null) {
attachment = new XWikiAttachment();
// TODO: Review this code and understand why it's needed.
// Add the attachment in the current doc
getAttachmentList().add(attachment);
}
attachment.setContent(data);
attachment.setFilename(filename);
attachment.setAuthor(context.getUser());
// Add the attachment to the document
attachment.setDoc(this);
return attachment;
}
public BaseObject getFirstObject(String fieldname)
{
// Keeping this function with context null for compatibility reasons.
// It should not be used, since it would miss properties which are only defined in the class
// and not present in the object because the object was not updated
return getFirstObject(fieldname, null);
}
public BaseObject getFirstObject(String fieldname, XWikiContext context)
{
Collection<Vector<BaseObject>> objectscoll = getxWikiObjects().values();
if (objectscoll == null) {
return null;
}
for (Vector<BaseObject> objects : objectscoll) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
if (bclass != null) {
Set<String> set = bclass.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
Set<String> set = obj.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
}
}
return null;
}
public void setProperty(String className, String fieldName, BaseProperty value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.safeput(fieldName, value);
setContentDirty(true);
}
public int getIntValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getIntValue(fieldName);
}
public long getLongValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getLongValue(fieldName);
}
public String getStringValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return "";
}
String result = obj.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public int getIntValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getIntValue(fieldName);
}
}
public long getLongValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getLongValue(fieldName);
}
}
public String getStringValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return "";
}
String result = object.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public void setStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringValue(fieldName, value);
setContentDirty(true);
}
public List getListValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return new ArrayList();
}
return obj.getListValue(fieldName);
}
public List getListValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return new ArrayList();
}
return object.getListValue(fieldName);
}
public void setStringListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringListValue(fieldName, value);
setContentDirty(true);
}
public void setDBStringListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setDBStringListValue(fieldName, value);
setContentDirty(true);
}
public void setLargeStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setLargeStringValue(fieldName, value);
setContentDirty(true);
}
public void setIntValue(String className, String fieldName, int value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setIntValue(fieldName, value);
setContentDirty(true);
}
public String getDatabase()
{
return this.database;
}
public void setDatabase(String database)
{
this.database = database;
}
public void setFullName(String fullname, XWikiContext context)
{
DocumentName documentName = this.documentNameFactory.createDocumentName(fullname);
setDatabase(documentName.getWiki());
setSpace(documentName.getSpace());
setName(documentName.getPage());
setContentDirty(true);
}
public String getLanguage()
{
if (this.language == null) {
return "";
} else {
return this.language.trim();
}
}
public void setLanguage(String language)
{
this.language = language;
}
public String getDefaultLanguage()
{
if (this.defaultLanguage == null) {
return "";
} else {
return this.defaultLanguage.trim();
}
}
public void setDefaultLanguage(String defaultLanguage)
{
this.defaultLanguage = defaultLanguage;
setMetaDataDirty(true);
}
public int getTranslation()
{
return this.translation;
}
public void setTranslation(int translation)
{
this.translation = translation;
setMetaDataDirty(true);
}
public String getTranslatedContent(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedContent(language, context);
}
public String getTranslatedContent(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(language, context);
String rev = (String) context.get("rev");
if ((rev == null) || (rev.length() == 0)) {
return tdoc.getContent();
}
XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context);
return cdoc.getContent();
}
public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedDocument(language, context);
}
public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = this;
if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) {
tdoc = new XWikiDocument(getSpace(), getName());
tdoc.setLanguage(language);
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
tdoc = getStore(context).loadXWikiDoc(tdoc, context);
if (tdoc.isNew()) {
tdoc = this;
}
} catch (Exception e) {
tdoc = this;
} finally {
context.setDatabase(database);
}
}
return tdoc;
}
public String getRealLanguage(XWikiContext context) throws XWikiException
{
return getRealLanguage();
}
public String getRealLanguage()
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public List<String> getTranslationList(XWikiContext context) throws XWikiException
{
return getStore().getTranslationList(this, context);
}
public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc
.toXML(context))));
}
public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc
.getContent())));
}
public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getContentDiff(fromDoc, toDoc, context);
}
public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getContentDiff(revdoc, this, context);
}
public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException
{
Version version = getRCSVersion();
try {
String prev = getDocumentArchive(context).getPrevVersion(version).toString();
XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context);
return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString
.stringToArray(getContent())));
} catch (Exception ex) {
LOG.debug("Exception getting differences from previous version: " + ex.getMessage());
}
return new ArrayList<Delta>();
}
public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
String originalContent, newContent;
originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context);
newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context);
return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent)));
}
public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getRenderedContentDiff(fromDoc, toDoc, context);
}
public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException,
DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getRenderedContentDiff(revdoc, this, context);
}
protected List<Delta> getDeltas(Revision rev)
{
List<Delta> list = new ArrayList<Delta>();
for (int i = 0; i < rev.size(); i++) {
list.add(rev.getDelta(i));
}
return list;
}
public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getMetaDataDiff(fromDoc, toDoc, context);
}
public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getMetaDataDiff(revdoc, this, context);
}
public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
List<MetaDataDiff> list = new ArrayList<MetaDataDiff>();
if ((fromDoc == null) || (toDoc == null)) {
return list;
}
if (!fromDoc.getParent().equals(toDoc.getParent())) {
list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent()));
}
if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) {
list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor()));
}
if (!fromDoc.getSpace().equals(toDoc.getSpace())) {
list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace()));
}
if (!fromDoc.getName().equals(toDoc.getName())) {
list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName()));
}
if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) {
list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage()));
}
if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) {
list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage()));
}
return list;
}
public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context)
throws XWikiException
{
XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context);
XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context);
return getObjectDiff(fromDoc, toDoc, context);
}
public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context);
return getObjectDiff(revdoc, this, context);
}
/**
* Return the object differences between two document versions. There is no hard requirement on the order of the two
* versions, but the results are semantically correct only if the two versions are given in the right order.
*
* @param fromDoc The old ('before') version of the document.
* @param toDoc The new ('after') version of the document.
* @param context The {@link com.xpn.xwiki.XWikiContext context}.
* @return The object differences. The returned list's elements are other lists, one for each changed object. The
* inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object.
* Additionally, if the object was added or removed, then the first entry in the list will be an
* "object-added" or "object-removed" marker.
* @throws XWikiException If there's an error computing the differences.
*/
public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>();
// Since objects could have been deleted or added, we iterate on both the old and the new
// object collections.
// First, iterate over the old objects.
for (Vector<BaseObject> objects : fromDoc.getxWikiObjects().values()) {
for (BaseObject originalObj : objects) {
// This happens when objects are deleted, and the document is still in the cache
// storage.
if (originalObj != null) {
BaseObject newObj = toDoc.getObject(originalObj.getClassName(), originalObj.getNumber());
List<ObjectDiff> dlist;
if (newObj == null) {
// The object was deleted.
dlist = new BaseObject().getDiff(originalObj, context);
ObjectDiff deleteMarker =
new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), originalObj.getGuid(),
"object-removed", "", "", "");
dlist.add(0, deleteMarker);
} else {
// The object exists in both versions, but might have been changed.
dlist = newObj.getDiff(originalObj, context);
}
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
// Second, iterate over the objects which are only in the new version.
for (Vector<BaseObject> objects : toDoc.getxWikiObjects().values()) {
for (BaseObject newObj : objects) {
// This happens when objects are deleted, and the document is still in the cache
// storage.
if (newObj != null) {
BaseObject originalObj = fromDoc.getObject(newObj.getClassName(), newObj.getNumber());
if (originalObj == null) {
// Only consider added objects, the other case was treated above.
originalObj = new BaseObject();
originalObj.setClassName(newObj.getClassName());
originalObj.setNumber(newObj.getNumber());
originalObj.setGuid(newObj.getGuid());
List<ObjectDiff> dlist = newObj.getDiff(originalObj, context);
ObjectDiff addMarker =
new ObjectDiff(newObj.getClassName(), newObj.getNumber(), newObj.getGuid(), "object-added",
"", "", "");
dlist.add(0, addMarker);
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
}
return difflist;
}
public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>();
BaseClass oldClass = fromDoc.getxWikiClass();
BaseClass newClass = toDoc.getxWikiClass();
if ((newClass == null) && (oldClass == null)) {
return difflist;
}
List<ObjectDiff> dlist = newClass.getDiff(oldClass, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
return difflist;
}
/**
* @param fromDoc
* @param toDoc
* @param context
* @return
* @throws XWikiException
*/
public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context)
throws XWikiException
{
List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>();
for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) {
String fileName = origAttach.getFilename();
XWikiAttachment newAttach = toDoc.getAttachment(fileName);
if (newAttach == null) {
difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null));
} else {
if (!origAttach.getVersion().equals(newAttach.getVersion())) {
difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion()));
}
}
}
for (XWikiAttachment newAttach : toDoc.getAttachmentList()) {
String fileName = newAttach.getFilename();
XWikiAttachment origAttach = fromDoc.getAttachment(fileName);
if (origAttach == null) {
difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion()));
}
}
return difflist;
}
/**
* Rename the current document and all the backlinks leading to it. See
* {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details.
*
* @param newDocumentName the new document name. If the space is not specified then defaults to the current space.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, XWikiContext context) throws XWikiException
{
rename(newDocumentName, getBackLinkedPages(context), context);
}
/**
* Rename the current document and all the links pointing to it in the list of passed backlink documents. The
* renaming algorithm takes into account the fact that there are several ways to write a link to a given page and
* all those forms need to be renamed. For example the following links all point to the same page:
* <ul>
* <li>[Page]</li>
* <li>[Page?param=1]</li>
* <li>[currentwiki:Page]</li>
* <li>[CurrentSpace.Page]</li>
* </ul>
* <p>
* Note: links without a space are renamed with the space added.
* </p>
*
* @param newDocumentName the new document name. If the space is not specified then defaults to the current space.
* @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the
* new renamed document.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context)
throws XWikiException
{
// TODO: Do all this in a single DB transaction as otherwise the state will be unknown if
// something fails in the middle...
if (isNew()) {
return;
}
// This link handler recognizes that 2 links are the same when they point to the same
// document (regardless of query string, target or alias). It keeps the query string,
// target and alias from the link being replaced.
RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler();
// Transform string representation of old and new links so that they can be manipulated.
Link oldLink = new LinkParser().parse(getFullName());
Link newLink = new LinkParser().parse(newDocumentName);
// Verify if the user is trying to rename to the same name... In that case, simply exits
// for efficiency.
if (linkHandler.compare(newLink, oldLink)) {
return;
}
// Step 1: Copy the document and all its translations under a new name
context.getWiki().copyDocument(getFullName(), newDocumentName, false, context);
// Step 2: For each backlink to rename, parse the backlink document and replace the links
// with the new name.
// Note: we ignore invalid links here. Invalid links should be shown to the user so
// that they fix them but the rename feature ignores them.
DocumentParser documentParser = new DocumentParser();
for (String backlinkDocumentName : backlinkDocumentNames) {
XWikiDocument backlinkDocument = context.getWiki().getDocument(backlinkDocumentName, context);
// Note: Here we cannot do a simple search/replace as there are several ways to point
// to the same document. For example [Page], [Page?param=1], [currentwiki:Page],
// [CurrentSpace.Page] all point to the same document. Thus we have to parse the links
// to recognize them and do the replace.
ReplacementResultCollection result =
documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler,
getSpace());
backlinkDocument.setContent((String) result.getModifiedContent());
context.getWiki().saveDocument(backlinkDocument,
context.getMessageTool().get("core.comment.renameLink", Arrays.asList(new String[] {newDocumentName})),
true, context);
}
// Step 3: Delete the old document
context.getWiki().deleteDocument(this, context);
// Step 4: The current document needs to point to the renamed document as otherwise it's
// pointing to an invalid XWikiDocument object as it's been deleted...
clone(context.getWiki().getDocument(newDocumentName, context));
}
public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException
{
String oldname = getFullName();
loadAttachments(context);
loadArchive(context);
/*
* if (oldname.equals(docname)) return this;
*/
XWikiDocument newdoc = (XWikiDocument) clone();
newdoc.setFullName(newDocumentName, context);
newdoc.setContentDirty(true);
newdoc.getxWikiClass().setName(newDocumentName);
Vector<BaseObject> objects = newdoc.getObjects(oldname);
if (objects != null) {
for (BaseObject object : objects) {
object.setName(newDocumentName);
// Since GUIDs are supposed to be Unique, although this object holds the same data, it is not exactly
// the same object, so it should have a different identifier.
object.setGuid(UUID.randomUUID().toString());
}
}
XWikiDocumentArchive archive = newdoc.getDocumentArchive();
if (archive != null) {
newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context));
}
return newdoc;
}
public XWikiLock getLock(XWikiContext context) throws XWikiException
{
XWikiLock theLock = getStore(context).loadLock(getId(), context, true);
if (theLock != null) {
int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context);
if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) {
getStore(context).deleteLock(theLock, context, true);
theLock = null;
}
}
return theLock;
}
public void setLock(String userName, XWikiContext context) throws XWikiException
{
XWikiLock lock = new XWikiLock(getId(), userName);
getStore(context).saveLock(lock, context, true);
}
public void removeLock(XWikiContext context) throws XWikiException
{
XWikiLock lock = getStore(context).loadLock(getId(), context, true);
if (lock != null) {
getStore(context).deleteLock(lock, context, true);
}
}
public void insertText(String text, String marker, XWikiContext context) throws XWikiException
{
setContent(StringUtils.replaceOnce(getContent(), marker, text + marker));
context.getWiki().saveDocument(this, context);
}
public Object getWikiNode()
{
return this.wikiNode;
}
public void setWikiNode(Object wikiNode)
{
this.wikiNode = wikiNode;
}
public String getxWikiClassXML()
{
return this.xWikiClassXML;
}
public void setxWikiClassXML(String xWikiClassXML)
{
this.xWikiClassXML = xWikiClassXML;
}
public int getElements()
{
return this.elements;
}
public void setElements(int elements)
{
this.elements = elements;
}
public void setElement(int element, boolean toggle)
{
if (toggle) {
this.elements = this.elements | element;
} else {
this.elements = this.elements & (~element);
}
}
public boolean hasElement(int element)
{
return ((this.elements & element) == element);
}
/**
* @return "inline" if the document should be edited in inline mode by default or "edit" otherwise.
* @throws XWikiException if an error happens when computing the edit mode
*/
public String getDefaultEditMode(XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
if (is10Syntax()) {
if (getContent().indexOf("includeForm(") != -1) {
return "inline";
}
} else {
// Algorithm: look in all include macro and for all document included check if one of them
// has an SheetClass object attached to it. If so then the edit mode is inline.
// Find all include macros and extract the document names
for (MacroBlock macroBlock : getXDOM().getChildrenByType(MacroBlock.class, false)) {
// TODO: Is there a good way not to hardcode the macro name? The macro itself shouldn't know
// its own name since it's a deployment time concern.
if ("include".equals(macroBlock.getName())) {
String documentName = macroBlock.getParameter("document");
if (documentName != null) {
XWikiDocument includedDocument = xwiki.getDocument(documentName, context);
if (!includedDocument.isNew()) {
BaseObject sheetClassObject = includedDocument.getObject(XWikiConstant.SHEET_CLASS);
if (sheetClassObject != null) {
// Use the user-defined default edit mode if set.
String defaultEditMode = sheetClassObject.getStringValue("defaultEditMode");
if (StringUtils.isBlank(defaultEditMode)) {
return "inline";
} else {
return defaultEditMode;
}
}
}
}
}
}
}
return "edit";
}
public String getDefaultEditURL(XWikiContext context) throws XWikiException
{
String editMode = getDefaultEditMode(context);
if ("inline".equals(editMode)) {
return getEditURL("inline", "", context);
} else {
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String editor = xwiki.getEditorPreference(context);
return getEditURL("edit", editor, context);
}
}
public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String language = "";
XWikiDocument tdoc = (XWikiDocument) context.get("tdoc");
String realLang = tdoc.getRealLanguage(context);
if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) {
language = realLang;
}
return getEditURL(action, mode, language, context);
}
public String getEditURL(String action, String mode, String language, XWikiContext context)
{
StringBuffer editparams = new StringBuffer();
if (!mode.equals("")) {
editparams.append("xpage=");
editparams.append(mode);
}
if (!language.equals("")) {
if (!mode.equals("")) {
editparams.append("&");
}
editparams.append("language=");
editparams.append(language);
}
return getURL(action, editparams.toString(), context);
}
public String getDefaultTemplate()
{
if (this.defaultTemplate == null) {
return "";
} else {
return this.defaultTemplate;
}
}
public void setDefaultTemplate(String defaultTemplate)
{
this.defaultTemplate = defaultTemplate;
setMetaDataDirty(true);
}
public Vector<BaseObject> getComments()
{
return getComments(true);
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentModelBridge#getSyntaxId()
*/
public String getSyntaxId()
{
// Can't be initialized in the XWikiDocument constructor because #getDefaultDocumentSyntax() need to create a
// XWikiDocument object to get preferences and generate an infinite loop
if (isNew() && this.syntaxId == null) {
this.syntaxId = getDefaultDocumentSyntax();
}
return this.syntaxId;
}
/**
* @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc)
* @see #getSyntaxId()
*/
public void setSyntaxId(String syntaxId)
{
this.syntaxId = syntaxId;
}
public Vector<BaseObject> getComments(boolean asc)
{
if (asc) {
return getObjects("XWiki.XWikiComments");
} else {
Vector<BaseObject> list = getObjects("XWiki.XWikiComments");
if (list == null) {
return list;
}
Vector<BaseObject> newlist = new Vector<BaseObject>();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public boolean isCurrentUserCreator(XWikiContext context)
{
return isCreator(context.getUser());
}
public boolean isCreator(String username)
{
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return username.equals(getCreator());
}
public boolean isCurrentUserPage(XWikiContext context)
{
String username = context.getUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public boolean isCurrentLocalUserPage(XWikiContext context)
{
String username = context.getLocalUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public void resetArchive(XWikiContext context) throws XWikiException
{
boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context);
if (hasVersioning) {
getVersioningStore(context).resetRCSArchive(this, true, context);
}
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException
{
// Read info in object
ObjectAddForm form = new ObjectAddForm();
form.setRequest((HttpServletRequest) context.getRequest());
form.readRequest();
String className = form.getClassName();
BaseObject object = newObject(className, context);
BaseClass baseclass = object.getxWikiClass(context);
baseclass.fromMap(form.getObject(className), object);
return object;
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, "", 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, prefix, 0, context);
}
// This functions adds multiple objects from an new objects creation form
public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List<Integer> objectsNumberDone = new ArrayList<Integer>();
List<BaseObject> objects = new ArrayList<BaseObject>();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(addObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException
{
return addObjectFromRequest(className, "", num, context);
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context)
throws XWikiException
{
BaseObject object = newObject(className, context);
BaseClass baseclass = object.getxWikiClass(context);
baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), object);
return object;
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException
{
return updateObjectFromRequest(className, "", context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, prefix, 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context)
throws XWikiException
{
int nb;
BaseObject oldobject = getObject(className, num);
if (oldobject == null) {
nb = createNewObject(className, context);
oldobject = getObject(className, nb);
} else {
nb = oldobject.getNumber();
}
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject =
(BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb),
oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setGuid(oldobject.getGuid());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public List<BaseObject> updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return updateObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List<Integer> objectsNumberDone = new ArrayList<Integer>();
List<BaseObject> objects = new ArrayList<BaseObject>();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(updateObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
public boolean isAdvancedContent()
{
String[] matches =
{"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content",
"/* Programmatic content */", "## Programmatic content"};
String content2 = this.content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
if (HTML_TAG_PATTERN.matcher(content2).find()) {
return true;
}
return false;
}
public boolean isProgrammaticContent()
{
String[] matches =
{"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()",
"$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content",
"$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup",
"$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString",
"$doc.toXML()", "$doc.toXMLDocument()",};
String content2 = this.content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
return false;
}
public boolean removeObject(BaseObject bobj)
{
Vector<BaseObject> objects = getObjects(bobj.getClassName());
if (objects == null) {
return false;
}
if (objects.elementAt(bobj.getNumber()) == null) {
return false;
}
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
return true;
}
/**
* Remove all the objects of a given type (XClass) from the document.
*
* @param className The class name of the objects to be removed.
*/
public boolean removeObjects(String className)
{
Vector<BaseObject> objects = getObjects(className);
if (objects == null) {
return false;
}
Iterator<BaseObject> it = objects.iterator();
while (it.hasNext()) {
BaseObject bobj = it.next();
if (bobj != null) {
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
}
}
return true;
}
/**
* @return the sections in the current document
* @throws XWikiException
*/
public List<DocumentSection> getSections() throws XWikiException
{
if (is10Syntax()) {
return getSections10();
} else {
List<DocumentSection> splitSections = new ArrayList<DocumentSection>();
List<HeaderBlock> headers = getXDOM().getChildrenByType(HeaderBlock.class, true);
int sectionNumber = 1;
for (HeaderBlock header : headers) {
// put -1 as index since there is no way to get the position of the header in the source
int documentSectionIndex = -1;
// Need to do the same thing than 1.0 content here
String documentSectionLevel = StringUtils.repeat("1.", header.getLevel().getAsInt() - 1) + "1";
DocumentSection docSection =
new DocumentSection(sectionNumber++, documentSectionIndex, documentSectionLevel, renderXDOM(
new XDOM(header.getChildren()), getSyntaxId()));
splitSections.add(docSection);
}
return splitSections;
}
}
/**
* @return the sections in the current document
*/
public List<DocumentSection> getSections10()
{
// Pattern to match the title. Matches only level 1 and level 2 headings.
Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE);
Matcher matcher = headingPattern.matcher(getContent());
List<DocumentSection> splitSections = new ArrayList<DocumentSection>();
int sectionNumber = 0;
// find title to split
while (matcher.find()) {
++sectionNumber;
String sectionLevel = matcher.group(1);
String sectionTitle = matcher.group(3);
int sectionIndex = matcher.start();
// Initialize a documentSection object.
DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle);
// Add the document section to list.
splitSections.add(docSection);
}
return splitSections;
}
/**
* Return a Document section with parameter is sectionNumber.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return
* @throws XWikiException error when extracting sections from document
*/
public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException
{
// return a document section according to section number
return getSections().get(sectionNumber - 1);
}
/**
* Return the content of a section.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return the content of a section or null if the section can't be found.
* @throws XWikiException error when trying to extract section content
*/
public String getContentOfSection(int sectionNumber) throws XWikiException
{
String content = null;
if (is10Syntax()) {
content = getContentOfSection10(sectionNumber);
} else {
List<HeaderBlock> headers = getXDOM().getChildrenByType(HeaderBlock.class, true);
if (headers.size() >= sectionNumber) {
SectionBlock section = headers.get(sectionNumber - 1).getSection();
content = renderXDOM(new XDOM(Collections.<Block> singletonList(section)), getSyntaxId());
}
}
return content;
}
/**
* Return the content of a section.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @return the content of a section
* @throws XWikiException error when trying to extract section content
*/
public String getContentOfSection10(int sectionNumber) throws XWikiException
{
List<DocumentSection> splitSections = getSections();
int indexEnd = 0;
// get current section
DocumentSection section = splitSections.get(sectionNumber - 1);
int indexStart = section.getSectionIndex();
String sectionLevel = section.getSectionLevel();
// Determine where this section ends, which is at the start of the next section of the
// same or a higher level.
for (int i = sectionNumber; i < splitSections.size(); i++) {
DocumentSection nextSection = splitSections.get(i);
String nextLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) {
indexEnd = nextSection.getSectionIndex();
break;
}
}
String sectionContent = null;
if (indexStart < 0) {
indexStart = 0;
}
if (indexEnd == 0) {
sectionContent = getContent().substring(indexStart);
} else {
sectionContent = getContent().substring(indexStart, indexEnd);
}
return sectionContent;
}
/**
* Update a section content in document.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @param newSectionContent the new section content.
* @return the new document content.
* @throws XWikiException error when updating content
*/
public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException
{
String content;
if (is10Syntax()) {
content = updateDocumentSection10(sectionNumber, newSectionContent);
} else {
XDOM xdom = getXDOM();
// Get the current section block
HeaderBlock header = xdom.getChildrenByType(HeaderBlock.class, true).get(sectionNumber - 1);
// newSectionContent -> Blocks
List<Block> blocks = parseContent(newSectionContent).getChildren();
int sectionLevel = header.getLevel().getAsInt();
for (int level = 1; level < sectionLevel && blocks.size() == 1 && blocks.get(0) instanceof SectionBlock; ++level) {
blocks = blocks.get(0).getChildren();
}
// replace old current SectionBlock with new Blocks
header.getSection().replace(blocks);
// render back XDOM to document's content syntax
content = renderXDOM(xdom, getSyntaxId());
}
return content;
}
/**
* Update a section content in document.
*
* @param sectionNumber the index (+1) of the section in the list of all sections in the document.
* @param newSectionContent the new section content.
* @return the new document content.
* @throws XWikiException error when updating document content with section content
*/
public String updateDocumentSection10(int sectionNumber, String newSectionContent) throws XWikiException
{
StringBuffer newContent = new StringBuffer();
// get document section that will be edited
DocumentSection docSection = getDocumentSection(sectionNumber);
int numberOfSections = getSections().size();
int indexSection = docSection.getSectionIndex();
if (numberOfSections == 1) {
// there is only a sections in document
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else if (sectionNumber == numberOfSections) {
// edit lastest section that doesn't contain subtitle
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else {
String sectionLevel = docSection.getSectionLevel();
int nextSectionIndex = 0;
// get index of next section
for (int i = sectionNumber; i < numberOfSections; i++) {
DocumentSection nextSection = getDocumentSection(i + 1); // get next section
String nextSectionLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextSectionLevel)) {
nextSectionIndex = nextSection.getSectionIndex();
break;
} else if (sectionLevel.length() > nextSectionLevel.length()) {
nextSectionIndex = nextSection.getSectionIndex();
break;
}
}
if (nextSectionIndex == 0) {// edit the last section
newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent);
return newContent.toString();
} else {
String contentAfter = getContent().substring(nextSectionIndex);
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter);
}
return newContent.toString();
}
}
/**
* Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO:
* cache the hash value, update only on modification.
*/
public String getVersionHashCode(XWikiContext context)
{
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
LOG.error("Cannot create MD5 object", ex);
return this.hashCode() + "";
}
try {
String valueBeforeMD5 = toXML(true, false, true, false, context);
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
return sb.toString();
} catch (Exception ex) {
LOG.error("Exception while computing document hash", ex);
}
return this.hashCode() + "";
}
public static String getInternalPropertyName(String propname, XWikiContext context)
{
XWikiMessageTool msg = context.getMessageTool();
String cpropname = StringUtils.capitalize(propname);
return (msg == null) ? cpropname : msg.get(cpropname);
}
public String getInternalProperty(String propname)
{
String methodName = "get" + StringUtils.capitalize(propname);
try {
Method method = getClass().getDeclaredMethod(methodName, (Class[]) null);
return (String) method.invoke(this, (Object[]) null);
} catch (Exception e) {
return null;
}
}
public String getCustomClass()
{
if (this.customClass == null) {
return "";
}
return this.customClass;
}
public void setCustomClass(String customClass)
{
this.customClass = customClass;
setMetaDataDirty(true);
}
public void setValidationScript(String validationScript)
{
this.validationScript = validationScript;
setMetaDataDirty(true);
}
public String getValidationScript()
{
if (this.validationScript == null) {
return "";
} else {
return this.validationScript;
}
}
public String getComment()
{
if (this.comment == null) {
return "";
}
return this.comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public boolean isMinorEdit()
{
return this.isMinorEdit;
}
public void setMinorEdit(boolean isMinor)
{
this.isMinorEdit = isMinor;
}
// methods for easy table update. It is need only for hibernate.
// when hibernate update old database without minorEdit field, hibernate will create field with
// null in despite of notnull in hbm.
// so minorEdit will be null for old documents. But hibernate can't convert null to boolean.
// so we need convert Boolean to boolean
protected Boolean getMinorEdit1()
{
return Boolean.valueOf(this.isMinorEdit);
}
protected void setMinorEdit1(Boolean isMinor)
{
this.isMinorEdit = (isMinor != null && isMinor.booleanValue());
}
public BaseObject newObject(String classname, XWikiContext context) throws XWikiException
{
int nb = createNewObject(classname, context);
return getObject(classname, nb);
}
public BaseObject getObject(String classname, boolean create, XWikiContext context)
{
try {
BaseObject obj = getObject(classname);
if ((obj == null) && create) {
return newObject(classname, context);
}
if (obj == null) {
return null;
} else {
return obj;
}
} catch (Exception e) {
return null;
}
}
public boolean validate(XWikiContext context) throws XWikiException
{
return validate(null, context);
}
public boolean validate(String[] classNames, XWikiContext context) throws XWikiException
{
boolean isValid = true;
if ((classNames == null) || (classNames.length == 0)) {
for (String classname : getxWikiObjects().keySet()) {
BaseClass bclass = context.getWiki().getClass(classname, context);
Vector<BaseObject> objects = getObjects(classname);
for (BaseObject obj : objects) {
if (obj != null) {
isValid &= bclass.validateObject(obj, context);
}
}
}
} else {
for (int i = 0; i < classNames.length; i++) {
Vector<BaseObject> objects = getObjects(classNames[i]);
if (objects != null) {
for (BaseObject obj : objects) {
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
isValid &= bclass.validateObject(obj, context);
}
}
}
}
}
String validationScript = "";
XWikiRequest req = context.getRequest();
if (req != null) {
validationScript = req.get("xvalidation");
}
if ((validationScript == null) || (validationScript.trim().equals(""))) {
validationScript = getValidationScript();
}
if ((validationScript != null) && (!validationScript.trim().equals(""))) {
isValid &= executeValidationScript(context, validationScript);
}
return isValid;
}
private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException
{
try {
XWikiValidationInterface validObject =
(XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context);
return validObject.validateDocument(this, context);
} catch (Throwable e) {
XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context);
return false;
}
}
public static void backupContext(Map<String, Object> backup, XWikiContext context)
{
backup.put("doc", context.getDoc());
VelocityManager velocityManager = (VelocityManager) Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
if (vcontext != null) {
backup.put("vdoc", vcontext.get("doc"));
backup.put("vcdoc", vcontext.get("cdoc"));
backup.put("vtdoc", vcontext.get("tdoc"));
}
Map gcontext = (Map) context.get("gcontext");
if (gcontext != null) {
backup.put("gdoc", gcontext.get("doc"));
backup.put("gcdoc", gcontext.get("cdoc"));
backup.put("gtdoc", gcontext.get("tdoc"));
}
}
public static void restoreContext(Map<String, Object> backup, XWikiContext context)
{
if (backup.get("doc") != null) {
context.setDoc((XWikiDocument) backup.get("doc"));
}
VelocityManager velocityManager = (VelocityManager) Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
if (backup.get("vdoc") != null) {
vcontext.put("doc", backup.get("vdoc"));
}
if (backup.get("vcdoc") != null) {
vcontext.put("cdoc", backup.get("vcdoc"));
}
if (backup.get("vtdoc") != null) {
vcontext.put("tdoc", backup.get("vtdoc"));
}
}
if (gcontext != null) {
if (backup.get("gdoc") != null) {
gcontext.put("doc", backup.get("gdoc"));
}
if (backup.get("gcdoc") != null) {
gcontext.put("cdoc", backup.get("gcdoc"));
}
if (backup.get("gtdoc") != null) {
gcontext.put("tdoc", backup.get("gtdoc"));
}
}
}
public void setAsContextDoc(XWikiContext context)
{
try {
context.setDoc(this);
com.xpn.xwiki.api.Document apidoc = this.newDocument(context);
com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument();
VelocityManager velocityManager = (VelocityManager) Utils.getComponent(VelocityManager.class);
VelocityContext vcontext = velocityManager.getVelocityContext();
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
vcontext.put("doc", apidoc);
vcontext.put("tdoc", tdoc);
}
if (gcontext != null) {
gcontext.put("doc", apidoc);
gcontext.put("tdoc", tdoc);
}
} catch (XWikiException ex) {
LOG.warn("Unhandled exception setting context", ex);
}
}
public String getPreviousVersion()
{
return getDocumentArchive().getPrevVersion(this.version).toString();
}
@Override
public String toString()
{
return getFullName();
}
/**
* Indicates whether the document should be 'hidden' or not, meaning that it should not be returned in public search
* results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should
* rely on or use this property, since it will be replaced with a generic metadata.
*
* @param hidden The new value of the {@link #hidden} property.
*/
public void setHidden(Boolean hidden)
{
if (hidden == null) {
this.hidden = false;
} else {
this.hidden = hidden;
}
}
/**
* Indicates whether the document is 'hidden' or not, meaning that it should not be returned in public search
* results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should
* rely on or use this property, since it will be replaced with a generic metadata.
*
* @return <code>true</code> if the document is hidden and does not appear among the results of
* {@link com.xpn.xwiki.api.XWiki#searchDocuments(String)}, <code>false</code> otherwise.
*/
public Boolean isHidden()
{
return this.hidden;
}
/**
* Convert the current document content from its current syntax to the new syntax passed as parameter.
*
* @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc)
* @throws XWikiException if an exception occurred during the conversion process
*/
public void convertSyntax(String targetSyntaxId, XWikiContext context) throws XWikiException
{
// convert content
setContent(performSyntaxConversion(getContent(), getSyntaxId(), targetSyntaxId, false));
// convert objects
Map<String, Vector<BaseObject>> objectsByClass = getxWikiObjects();
for (Vector<BaseObject> objects : objectsByClass.values()) {
for (BaseObject bobject : objects) {
if (bobject != null) {
BaseClass bclass = bobject.getxWikiClass(context);
for (Object fieldClass : bclass.getProperties()) {
if (fieldClass instanceof TextAreaClass && ((TextAreaClass) fieldClass).isWikiContent()) {
TextAreaClass textAreaClass = (TextAreaClass) fieldClass;
LargeStringProperty field = (LargeStringProperty) bobject.getField(textAreaClass.getName());
if (field != null) {
field.setValue(performSyntaxConversion(field.getValue(), getSyntaxId(), targetSyntaxId,
false));
}
}
}
}
}
}
// change syntax id
setSyntaxId(targetSyntaxId);
}
/**
* @return the XDOM conrrexponding to the document's string content.
*/
public XDOM getXDOM()
{
if (this.xdom == null) {
try {
this.xdom = parseContent(getContent());
} catch (XWikiException e) {
LOG.error("Failed to parse document content to XDOM", e);
}
}
return this.xdom.clone();
}
/**
* Convert the passed content from the passed syntax to the passed new syntax.
*
* @param content the content to convert
* @param currentSyntaxId the syntax of the current content to convert
* @param targetSyntaxId the new syntax after the conversion
* @param transform indicate if transformations has to be applied or not
* @return the converted content in the new syntax
* @throws XWikiException if an exception occurred during the conversion process
*/
private static String performSyntaxConversion(String content, String currentSyntaxId, String targetSyntaxId,
boolean transform) throws XWikiException
{
try {
XDOM dom = parseContent(currentSyntaxId, content);
return performSyntaxConversion(dom, currentSyntaxId, targetSyntaxId, transform);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntaxId + "]", e);
}
}
/**
* Convert the passed content from the passed syntax to the passed new syntax.
*
* @param content the XDOM content to convert, the XDOM can be modified during the transformation
* @param currentSyntaxId the syntax of the current content to convert
* @param targetSyntaxId the new syntax after the conversion
* @param transform indicate if transformations has to be applied or not
* @return the converted content in the new syntax
* @throws XWikiException if an exception occurred during the conversion process
*/
private static String performSyntaxConversion(XDOM content, String currentSyntaxId, String targetSyntaxId,
boolean transform) throws XWikiException
{
try {
if (transform) {
// Transform XDOM
TransformationManager transformations =
(TransformationManager) Utils.getComponent(TransformationManager.class);
SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.class);
transformations
.performTransformations(content, syntaxFactory.createSyntaxFromIdString(currentSyntaxId));
}
// Render XDOM
return renderXDOM(content, targetSyntaxId);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to convert document to syntax [" + targetSyntaxId + "]", e);
}
}
/**
* Render privided XDOM into content of the provided syntax identifier.
*
* @param content the XDOM content to render
* @param targetSyntaxId the syntax identifier of the rendered content
* @return the rendered content
* @throws XWikiException if an exception occurred during the rendering process
*/
private static String renderXDOM(XDOM content, String targetSyntaxId) throws XWikiException
{
try {
SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.class);
PrintRendererFactory factory = (PrintRendererFactory) Utils.getComponent(PrintRendererFactory.class);
WikiPrinter printer = new DefaultWikiPrinter();
content.traverse(factory.createRenderer(syntaxFactory.createSyntaxFromIdString(targetSyntaxId), printer));
return printer.toString();
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to render document to syntax [" + targetSyntaxId + "]", e);
}
}
private XDOM parseContent(String content) throws XWikiException
{
return parseContent(getSyntaxId(), content);
}
private static XDOM parseContent(String syntaxId, String content) throws XWikiException
{
try {
Parser parser = (Parser) Utils.getComponent(Parser.class, syntaxId);
return parser.parse(new StringReader(content));
} catch (ParseException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to parse content of syntax [" + syntaxId + "]", e);
}
}
private String getDefaultDocumentSyntax()
{
return ((CoreConfiguration) Utils.getComponent(CoreConfiguration.class)).getDefaultDocumentSyntax();
}
/**
* @return true if the document has a xwiki/1.0 syntax content
*/
public boolean is10Syntax()
{
return is10Syntax(getSyntaxId());
}
/**
* @return true if the document has a xwiki/1.0 syntax content
*/
public boolean is10Syntax(String syntaxId)
{
return XWIKI10_SYNTAXID.equalsIgnoreCase(syntaxId);
}
}
|
package org.jbox2d.dynamics;
import org.jbox2d.collision.broadphase.BroadPhase;
import org.jbox2d.collision.shapes.Shape;
import org.jbox2d.common.Mat22;
import org.jbox2d.common.Sweep;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.contacts.Contact;
import org.jbox2d.pooling.TLFixtureDef;
import org.jbox2d.pooling.TLMassData;
import org.jbox2d.pooling.TLTransform;
import org.jbox2d.pooling.TLVec2;
import org.jbox2d.structs.collision.WorldManifold;
import org.jbox2d.structs.collision.shapes.MassData;
import org.jbox2d.structs.dynamics.contacts.ContactEdge;
// updated to rev 100
// thead safe pooling
/**
* A rigid body. These are created via World.createBody.
*/
public class Body {
public static final int e_islandFlag = 0x0001;
public static final int e_awakeFlag = 0x0002;
public static final int e_autoSleepFlag = 0x0004;
public static final int e_bulletFlag = 0x0008;
public static final int e_fixedRotationFlag = 0x0010;
public static final int e_activeFlag = 0x0020;
public static final int e_toiFlag = 0x0040;
public BodyType m_type;
public int m_flags;
public int m_islandIndex;
/**
* The body orgin transform.
*/
public final Transform m_xf = new Transform();
/**
* The swept motion for CCD
*/
public final Sweep m_sweep = new Sweep();
public final Vec2 m_linearVelocity = new Vec2();
public float m_angularVelocity = 0;
public final Vec2 m_force = new Vec2();
public float m_torque = 0;
public World m_world;
public Body m_prev;
public Body m_next;
public Fixture m_fixtureList;
public int m_fixtureCount;
public JointEdge m_jointList;
public ContactEdge m_contactList;
public float m_mass, m_invMass;
// Rotational inertia about the center of mass.
public float m_I, m_invI;
public float m_linearDamping;
public float m_angularDamping;
public float m_sleepTime;
public Object m_userData;
public Body(final BodyDef bd, World world){
assert( bd.position.isValid());
assert( bd.linearVelocity.isValid());
assert( bd.inertiaScale >= 0.0f);
assert( bd.angularDamping >= 0.0f);
assert( bd.linearDamping >= 0.0f);
m_flags = 0;
if (bd.bullet){
m_flags |= e_bulletFlag;
}
if (bd.fixedRotation){
m_flags |= e_fixedRotationFlag;
}
if (bd.allowSleep){
m_flags |= e_autoSleepFlag;
}
if (bd.awake){
m_flags |= e_awakeFlag;
}
if (bd.active){
m_flags |= e_activeFlag;
}
m_world = world;
m_xf.position.set(bd.position);
m_xf.R.set(bd.angle);
m_sweep.localCenter.setZero();
m_sweep.a0 = m_sweep.a = bd.angle;
//m_sweep.c0 = m_sweep.c = Transform.mul(m_xf, m_sweep.localCenter);
Transform.mulToOut(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
m_jointList = null;
m_contactList = null;
m_prev = null;
m_next = null;
m_linearVelocity = bd.linearVelocity;
m_angularVelocity = bd.angularVelocity;
m_linearDamping = bd.linearDamping;
m_angularDamping = bd.angularDamping;
m_force.setZero();
m_torque = 0.0f;
m_sleepTime = 0.0f;
m_type = bd.type;
if(m_type == BodyType.DYNAMIC){
m_mass = 1f;
m_invMass = 1f;
}else{
m_mass = 0f;
m_invMass = 0f;
}
m_I = 0.0f;
m_invI = 0.0f;
m_userData = bd.userData;
m_fixtureList = null;
m_fixtureCount = 0;
}
// TODO djm: check out about this new fixture here
/**
* Creates a fixture and attach it to this body. Use this function if you need
* to set some fixture parameters, like friction. Otherwise you can create the
* fixture directly from a shape.
* If the density is non-zero, this function automatically updates the mass of the body.
* Contacts are not created until the next time step.
* @param def the fixture definition.
* @warning This function is locked during callbacks.
*/
public final Fixture createFixture( FixtureDef def){
assert(m_world.isLocked() == false);
if (m_world.isLocked() == true){
return null;
}
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
// djm TODO from pool?
Fixture fixture = new Fixture();
fixture.create(this, def);
fixture.m_next = m_fixtureList;
m_fixtureList = fixture;
++m_fixtureCount;
fixture.m_body = this;
// Adjust mass properties if needed.
if (fixture.m_density > 0.0f){
resetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
m_world.m_flags |= World.e_newFixture
return fixture;
}
// djm pooling
private static final TLFixtureDef tldef = new TLFixtureDef();
/**
* Creates a fixture from a shape and attach it to this body.
* This is a convenience function. Use FixtureDef if you need to set parameters
* like friction, restitution, user data, or filtering.
* If the density is non-zero, this function automatically updates the mass of the body.
* @param shape the shape to be cloned.
* @param density the shape density (set to zero for static bodies).
* @warning This function is locked during callbacks.
*/
public final Fixture createFixture( Shape shape, float density){
FixtureDef def = tldef.get();
def.shape = shape;
def.density = density;
return createFixture(def);
}
// TODO djm: pool fixtures?
/**
* Destroy a fixture. This removes the fixture from the broad-phase and
* destroys all contacts associated with this fixture. This will
* automatically adjust the mass of the body if the body is dynamic and the
* fixture has positive density.
* All fixtures attached to a body are implicitly destroyed when the body is destroyed.
* @param fixture the fixture to be removed.
* @warning This function is locked during callbacks.
*/
public final void destroyFixture(Fixture fixture){
assert(m_world.isLocked() == false);
if (m_world.isLocked() == true){
return;
}
assert(fixture.m_body == this);
// Remove the fixture from this body's singly linked list.
assert(m_fixtureCount > 0);
Fixture node = m_fixtureList;
boolean found = false;
while (node != null){
if (node == fixture){
node = fixture.m_next;
found = true;
break;
}
node = node.m_next;
}
// You tried to remove a shape that is not attached to this body.
assert(found);
// Destroy any contacts associated with the fixture.
ContactEdge edge = m_contactList;
while (edge != null){
Contact c = edge.contact;
edge = edge.next;
Fixture fixtureA = c.getFixtureA();
Fixture fixtureB = c.getFixtureB();
if (fixture == fixtureA || fixture == fixtureB){
// This destroys the contact and removes it from
// this body's contact list.
m_world.m_contactManager.destroy(c);
}
}
if ((m_flags & e_activeFlag) == 1){
assert(fixture.m_proxy != null);
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
fixture.destroyProxy(broadPhase);
}
else{
assert(fixture.m_proxy == null);
}
fixture.destroy();
fixture.m_body = null;
fixture.m_next = null;
//fixture.~Fixture();
//allocator.Free(fixture, sizeof(Fixture));
--m_fixtureCount;
// Reset the mass data.
resetMassData();
}
/**
* Set the position of the body's origin and rotation.
* This breaks any contacts and wakes the other bodies.
* Manipulating a body's transform may cause non-physical behavior.
* @param position the world position of the body's local origin.
* @param angle the world rotation in radians.
*/
public final void setTransform( Vec2 position, float angle){
assert(m_world.isLocked() == false);
if (m_world.isLocked() == true){
return;
}
m_xf.R.set(angle);
m_xf.position.set(position);
//m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOut(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
m_sweep.a0 = m_sweep.a = angle;
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next)
{
f.synchronize(broadPhase, m_xf, m_xf);
}
m_world.m_contactManager.findNewContacts();
}
/**
* Get the body transform for the body's origin.
* @return the world transform of the body's origin.
*/
public final Transform getTransform(){
return m_xf;
}
/**
* Get the world body origin position. Do not modify.
* @return the world position of the body's origin.
*/
public final Vec2 getPosition(){
return m_xf.position;
}
/**
* Get the angle in radians.
* @return the current world rotation angle in radians.
*/
public final float getAngle(){
return m_sweep.a;
}
/**
* Get the world position of the center of mass. Do not modify.
*/
public final Vec2 getWorldCenter(){
return m_sweep.c;
}
/**
* Get the local position of the center of mass. Do not modify.
*/
public final Vec2 getLocalCenter(){
return m_sweep.localCenter;
}
/**
* Set the linear velocity of the center of mass.
* @param v the new linear velocity of the center of mass.
*/
public final void setLinearVelocity( Vec2 v){
if(m_type == BodyType.STATIC){
return;
}
if(Vec2.dot(v, v) > 0.0f){
setAwake(true);
}
m_linearVelocity.set(v);
}
/**
* Get the linear velocity of the center of mass. Do not modify,
* instead use {@link #setLinearVelocity(Vec2)}.
* @return the linear velocity of the center of mass.
*/
public final Vec2 getLinearVelocity(){
return m_linearVelocity;
}
/**
* Set the angular velocity.
* @param omega the new angular velocity in radians/second.
*/
public final void setAngularVelocity(float w){
if(m_type == BodyType.STATIC){
return;
}
if( w*w > 0f){
setAwake(true);
}
m_angularVelocity = w;
}
/**
* Get the angular velocity.
* @return the angular velocity in radians/second.
*/
public final float getAngularVelocity(){
return m_angularVelocity;
}
// djm pooling
private static final TLVec2 tltemp = new TLVec2();
/**
* Apply a force at a world point. If the force is not
* applied at the center of mass, it will generate a torque and
* affect the angular velocity. This wakes up the body.
* @param force the world force vector, usually in Newtons (N).
* @param point the world position of the point of application.
*/
public final void applyForce( Vec2 force, Vec2 point){
if (m_type != BodyType.DYNAMIC){
return;
}
if (isAwake() == false){
setAwake(true);
}
m_force.addLocal(force);
Vec2 temp = tltemp.get();
temp.set(point).subLocal(m_sweep.c);
m_torque += Vec2.cross(temp, force);
}
/**
* Apply a torque. This affects the angular velocity
* without affecting the linear velocity of the center of mass.
* This wakes up the body.
* @param torque about the z-axis (out of the screen), usually in N-m.
*/
public final void applyTorque(float torque){
if (m_type != BodyType.DYNAMIC){
return;
}
if (isAwake() == false){
setAwake(true);
}
m_torque += torque;
}
// djm pooling from above
/**
* Apply an impulse at a point. This immediately modifies the velocity.
* It also modifies the angular velocity if the point of application
* is not at the center of mass. This wakes up the body.
* @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
* @param point the world position of the point of application.
*/
public final void applyLinearImpulse( Vec2 impulse, Vec2 point){
if (m_type != BodyType.DYNAMIC){
return;
}
if (isAwake() == false){
setAwake(true);
}
Vec2 temp = tltemp.get();
temp.set(impulse).mulLocal(m_invMass);
m_linearVelocity.addLocal(temp);
temp.set(point).subLocal(m_sweep.c);
m_angularVelocity += m_invI * Vec2.cross(temp, impulse);
}
/**
* Apply an angular impulse.
* @param impulse the angular impulse in units of kg*m*m/s
*/
public void applyAngularImpulse(float impulse){
if (m_type != BodyType.DYNAMIC){
return;
}
if (isAwake() == false){
setAwake(true);
}
m_angularVelocity += m_invI * impulse;
}
/**
* Get the total mass of the body.
* @return the mass, usually in kilograms (kg).
*/
public final float getMass(){
return m_mass;
}
/**
* Get the central rotational inertia of the body.
* @return the rotational inertia, usually in kg-m^2.
*/
public final float getInertia(){
return m_I + m_mass * Vec2.dot(m_sweep.localCenter, m_sweep.localCenter);
}
/**
* Get the mass data of the body. The rotational inertia is relative
* to the center of mass.
* @return a struct containing the mass, inertia and center of the body.
*/
public final void getMassData(MassData data){
data.mass = m_mass;
data.I = m_I + m_mass * Vec2.dot(m_sweep.localCenter, m_sweep.localCenter);
data.center.set(m_sweep.localCenter);
}
// djm pooling from below
/**
* Set the mass properties to override the mass properties of the fixtures.
* Note that this changes the center of mass position.
* Note that creating or destroying fixtures can also alter the mass.
* This function has no effect if the body isn't dynamic.
* @param massData the mass properties.
*/
public final void setMassData( MassData massData){
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
assert(m_world.isLocked() == false);
if (m_world.isLocked() == true){
return;
}
if(m_type != BodyType.DYNAMIC){
return;
}
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_mass = massData.mass;
if(m_mass <= 0.0f){
m_mass = 1f;
}
m_invMass = 1.0f / m_mass;
if (massData.I > 0.0f && (m_flags & e_fixedRotationFlag) == 0){
m_I = massData.I - m_mass * Vec2.dot(massData.center, massData.center);
assert(m_I > 0.0f);
m_invI = 1.0f / m_I;
}
// Move center of mass.
Vec2 oldCenter = m_sweep.c;
m_sweep.localCenter = massData.center;
//m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOut(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
// Update center of mass velocity.
//m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter);
Vec2 temp = tltemp.get();
temp.set(m_sweep.c).subLocal(oldCenter);
Vec2.crossToOut(m_angularVelocity, temp, temp);
m_linearVelocity.addLocal(temp);
}
// djm pooling from below;
private static final TLVec2 tlcenter = new TLVec2();
private static final TLMassData tlmd = new TLMassData();
/**
* This resets the mass properties to the sum of the mass properties of the fixtures.
* This normally does not need to be called unless you called setMassData to override
* the mass and you later want to reset the mass.
*/
public final void resetMassData(){
// Compute mass data from shapes. Each shape has its own density.
m_mass = 0.0f;
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_sweep.localCenter.setZero();
// Static and kinematic bodies have zero mass.
if (m_type == BodyType.STATIC || m_type == BodyType.KINEMATIC){
m_sweep.c0 = m_sweep.c = m_xf.position;
return;
}
assert(m_type == BodyType.DYNAMIC);
// Accumulate mass over all fixtures.
Vec2 center = tlcenter.get();
center.setZero();
Vec2 temp = tltemp.get();
MassData massData = tlmd.get();
for (Fixture f = m_fixtureList; f != null; f = f.m_next){
if(f.m_density == 0.0f){
continue;
}
f.getMassData(massData);
m_mass += massData.mass;
//center += massData.mass * massData.center;
temp.set(massData.center).mulLocal(massData.mass);
center.addLocal(temp);
m_I += massData.I;
}
// Compute center of mass.
if (m_mass > 0.0f){
m_invMass = 1.0f / m_mass;
center.mulLocal(m_invMass);
}else{
// Force all dynamic bodies to have a positive mass.
m_mass = 1.0f;
m_invMass = 1.0f;
}
if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0){
// Center the inertia about the center of mass.
m_I -= m_mass * Vec2.dot(center, center);
assert(m_I > 0.0f);
m_invI = 1.0f / m_I;
}
else{
m_I = 0.0f;
m_invI = 0.0f;
}
// Move center of mass.
Vec2 oldCenter = m_sweep.c;
m_sweep.localCenter = center;
//m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOut(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
// Update center of mass velocity.
//m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter);
temp.set(m_sweep.c).subLocal(oldCenter);
Vec2.crossToOut(m_angularVelocity, temp, temp);
m_linearVelocity.addLocal(temp);
}
/**
* Get the world coordinates of a point given the local coordinates.
* @param localPoint a point on the body measured relative the the body's origin.
* @return the same point expressed in world coordinates.
*/
public final Vec2 getWorldPoint( Vec2 localPoint){
Vec2 v = new Vec2();
getWorldPointToOut(localPoint, v);
return v;
}
public final void getWorldPointToOut(Vec2 localPoint, Vec2 out){
Transform.mulToOut(m_xf, localPoint, out);
}
/**
* Get the world coordinates of a vector given the local coordinates.
* @param localVector a vector fixed in the body.
* @return the same vector expressed in world coordinates.
*/
public final Vec2 getWorldVector( Vec2 localVector){
Vec2 out = new Vec2();
getWorldVectorToOut(localVector, out);
return out;
}
public final void getWorldVectorToOut( Vec2 localVector, Vec2 out){
Mat22.mulToOut(m_xf.R, localVector, out);
}
/**
* Gets a local point relative to the body's origin given a world point.
* @param a point in world coordinates.
* @return the corresponding local point relative to the body's origin.
*/
public final Vec2 getLocalPoint( Vec2 worldPoint){
Vec2 out = new Vec2();
getLocalPointToOut(worldPoint, out);
return out;
}
public final void getLocalPointToOut( Vec2 worldPoint, Vec2 out){
Transform.mulTransToOut(m_xf, worldPoint, out);
}
/**
* Gets a local vector given a world vector.
* @param a vector in world coordinates.
* @return the corresponding local vector.
*/
public final Vec2 getLocalVector( Vec2 worldVector){
Vec2 out = new Vec2();
getLocalVectorToOut(worldVector, out);
return out;
}
public final void getLocalVectorToOut( Vec2 worldVector, Vec2 out){
Mat22.mulTransToOut(m_xf.R, worldVector, out);
}
/**
* Get the world linear velocity of a world point attached to this body.
* @param a point in world coordinates.
* @return the world velocity of a point.
*/
public final Vec2 getLinearVelocityFromWorldPoint( Vec2 worldPoint){
Vec2 out = new Vec2();
getLinearVelocityFromWorldPointToOut(worldPoint, out);
return out;
}
public final void getLinearVelocityFromWorldPointToOut( Vec2 worldPoint, Vec2 out){
out.set(worldPoint).subLocal(m_sweep.c);
Vec2.crossToOut(m_angularVelocity, out, out);
out.addLocal(m_linearVelocity);
}
/**
* Get the world velocity of a local point.
* @param a point in local coordinates.
* @return the world velocity of a point.
*/
public final Vec2 getLinearVelocityFromLocalPoint( Vec2 localPoint){
Vec2 out = new Vec2();
getLinearVelocityFromLocalPointToOut(localPoint, out);
return out;
}
public final void getLinearVelocityFromLocalPointToOut( Vec2 localPoint, Vec2 out){
getWorldPointToOut(localPoint,out);
getLinearVelocityFromWorldPointToOut(localPoint, out);
}
/** Get the linear damping of the body. */
public final float getLinearDamping(){
return m_linearDamping;
}
/** Set the linear damping of the body. */
public final void setLinearDamping(float linearDamping){
m_linearDamping = linearDamping;
}
/** Get the angular damping of the body. */
public final float getAngularDamping(){
return m_angularDamping;
}
/** Set the angular damping of the body. */
public final void setAngularDamping(float angularDamping){
m_angularDamping = angularDamping;
}
public BodyType getType(){
return m_type;
}
/**
* Set the type of this body. This may alter the mass and velocity.
* @param type
*/
public void setType(BodyType type){
if (m_type == type){
return;
}
m_type = type;
resetMassData();
if (m_type == BodyType.STATIC){
m_linearVelocity.setZero();
m_angularVelocity = 0.0f;
}
setAwake(true);
m_force.setZero();
m_torque = 0.0f;
// Since the body type changed, we need to flag contacts for filtering.
for (ContactEdge ce = m_contactList; ce != null; ce = ce.next){
ce.contact.flagForFiltering();
}
}
/** Is this body treated like a bullet for continuous collision detection?*/
public final boolean isBullet(){
return (m_flags & e_bulletFlag) == e_bulletFlag;
}
/** Should this body be treated like a bullet for continuous collision detection?*/
public final void setBullet(boolean flag){
if (flag){
m_flags |= e_bulletFlag;
}
else{
m_flags &= ~e_bulletFlag;
}
}
/**
* You can disable sleeping on this body. If you disable sleeping, the
* body will be woken.
* @param flag
*/
public void setSleepingAllowed(boolean flag){
if (flag){
m_flags |= e_autoSleepFlag;
}
else{
m_flags &= ~e_autoSleepFlag;
setAwake(true);
}
}
/**
* Is this body allowed to sleep
* @return
*/
public boolean isSleepingAllowed(){
return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
}
/**
* Set the sleep state of the body. A sleeping body has very
* low CPU cost.
* @param flag set to true to put body to sleep, false to wake it.
* @param flag
*/
public void setAwake(boolean flag){
if (flag){
if ((m_flags & e_awakeFlag) == 0){
m_flags |= e_awakeFlag;
m_sleepTime = 0.0f;
}
}
else
{
m_flags &= ~e_awakeFlag;
m_sleepTime = 0.0f;
m_linearVelocity.setZero();
m_angularVelocity = 0.0f;
m_force.setZero();
m_torque = 0.0f;
}
}
/**
* Get the sleeping state of this body.
* @return true if the body is sleeping.
*/
public boolean isAwake(){
return (m_flags & e_awakeFlag) == e_awakeFlag;
}
/**
* Set the active state of the body. An inactive body is not
* simulated and cannot be collided with or woken up.
* If you pass a flag of true, all fixtures will be added to the
* broad-phase.
* If you pass a flag of false, all fixtures will be removed from
* the broad-phase and all contacts will be destroyed.
* Fixtures and joints are otherwise unaffected. You may continue
* to create/destroy fixtures and joints on inactive bodies.
* Fixtures on an inactive body are implicitly inactive and will
* not participate in collisions, ray-casts, or queries.
* Joints connected to an inactive body are implicitly inactive.
* An inactive body is still owned by a World object and remains
* in the body list.
* @param flag
*/
public void setActive(boolean flag){
if (flag == isActive()){
return;
}
if (flag){
m_flags |= e_activeFlag;
// Create all proxies.
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next){
f.createProxy(broadPhase, m_xf);
}
// Contacts are created the next time step.
}
else{
m_flags &= ~e_activeFlag;
// Destroy all proxies.
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next){
f.destroyProxy(broadPhase);
}
// Destroy the attached contacts.
ContactEdge ce = m_contactList;
while (ce != null){
ContactEdge ce0 = ce;
ce = ce.next;
m_world.m_contactManager.destroy(ce0.contact);
}
m_contactList = null;
}
}
/**
* Get the active state of the body.
* @return
*/
public boolean isActive(){
return (m_flags & e_activeFlag) == e_activeFlag;
}
/**
* Set this body to have fixed rotation. This causes the mass
* to be reset.
* @param flag
*/
public void setFixedRotation(boolean flag){
if (flag){
m_flags |= e_fixedRotationFlag;
}
else{
m_flags &= ~e_fixedRotationFlag;
}
resetMassData();
}
/**
* Does this body have fixed rotation?
* @return
*/
public boolean isFixedRotation(){
return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
}
/** Get the list of all fixtures attached to this body.*/
public final Fixture getFixtureList(){
return m_fixtureList;
}
/** Get the list of all joints attached to this body.*/
public final JointEdge getJointList(){
return m_jointList;
}
/**
* Get the list of all contacts attached to this body.
* @warning this list changes during the time step and you may
* miss some collisions if you don't use ContactListener.
*/
public final ContactEdge getContactList(){
return m_contactList;
}
/** Get the next body in the world's body list.*/
public final Body getNext(){
return m_next;
}
/** Get the user data pointer that was provided in the body definition.*/
public final Object getUserData(){
return m_userData;
}
/**
* Set the user data. Use this to store your application specific data.*/
public final void setUserData(Object data){
m_userData = data;
}
/**
* Get the parent world of this body.*/
public final World getWorld(){
return m_world;
}
// djm pooling
private static final TLTransform tlxf1 = new TLTransform();
protected final void synchronizeFixtures(){
Transform xf1 = tlxf1.get();
xf1.R.set(m_sweep.a0);
//xf1.position = m_sweep.c0 - Mul(xf1.R, m_sweep.localCenter);
Mat22.mulToOut(xf1.R, m_sweep.localCenter, xf1.position);
xf1.position.mulLocal(-1).addLocal(m_sweep.c0);
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next){
f.synchronize(broadPhase, xf1, m_xf);
}
}
public final void synchronizeTransform(){
m_xf.R.set(m_sweep.a);
//m_xf.position = m_sweep.c - Mul(m_xf.R, m_sweep.localCenter);
Mat22.mulToOut(m_xf.R, m_sweep.localCenter, m_xf.position);
m_xf.position.mul(-1).addLocal(m_sweep.c);
}
/**
* This is used to prevent connected bodies from colliding.
* It may lie, depending on the collideConnected flag.
* @param other
* @return
*/
public boolean shouldCollide(Body other){
// At least one body should be dynamic.
if (m_type != BodyType.DYNAMIC && other.m_type != BodyType.DYNAMIC){
return false;
}
// Does a joint prevent collision?
for (JointEdge jn = m_jointList; jn; jn = jn.next){
if (jn.other == other){
if (jn.joint.m_collideConnected == false){
return false;
}
}
}
return true;
}
protected final void advance(float t){
// Advance to the new safe time.
m_sweep.advance(t);
m_sweep.c.set(m_sweep.c0);
m_sweep.a = m_sweep.a0;
synchronizeTransform();
}
}
|
package org.opencms.ui.login;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsUser;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.shared.CmsGwtConstants;
import org.opencms.i18n.CmsEncoder;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.ui.A_CmsUI;
import org.opencms.ui.CmsVaadinErrorHandler;
import org.opencms.ui.CmsVaadinUtils;
import org.opencms.ui.Messages;
import org.opencms.ui.apps.CmsAppWorkplaceUi;
import org.opencms.ui.components.CmsBasicDialog;
import org.opencms.ui.components.CmsBasicDialog.DialogWidth;
import org.opencms.ui.login.CmsLoginHelper.LoginParameters;
import org.opencms.ui.shared.CmsVaadinConstants;
import org.opencms.util.CmsFileUtil;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceManager;
import org.opencms.workplace.CmsWorkplaceSettings;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.Version;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* The UI class for the Vaadin-based login dialog.<p>
*/
@Theme("opencms")
public class CmsLoginUI extends A_CmsUI {
/**
* Parameters which are initialized during the initial page load of the login dialog.<p>
*/
public static class Parameters implements Serializable {
/** The serial version id. */
private static final long serialVersionUID = -4885232184680664315L;
/** The locale. */
public Locale m_locale;
/** The PC type (public or private). */
public String m_pcType;
/** The preselected OU. */
public String m_preselectedOu;
/** The requested resource. */
public String m_requestedResource;
/** The requested workplace app path. */
public String m_requestedWorkplaceApp;
/**
* Creates a new instance.<p>
*
* @param pcType the PC type
* @param preselectedOu the preselected OU
* @param locale the locale
* @param requestedResource the requested resource
* @param requestedWorkplaceApp the requested workplace app path
*/
public Parameters(
String pcType,
String preselectedOu,
Locale locale,
String requestedResource,
String requestedWorkplaceApp) {
m_pcType = pcType;
m_preselectedOu = preselectedOu;
m_locale = locale;
m_requestedResource = requestedResource;
m_requestedWorkplaceApp = requestedWorkplaceApp;
}
/**
* Gets the locale.<p>
*
* @return the locale
*/
public Locale getLocale() {
return m_locale;
}
/**
* Gets the PC type (private or public).<p>
*
* @return the pc type
*/
public String getPcType() {
return m_pcType;
}
/**
* Gets the preselected OU.<p>
*
* @return the preselected OU
*/
public String getPreselectedOu() {
return m_preselectedOu;
}
/**
* Gets the requested resource path.<p>
*
* @return the requested resource path
*/
public String getRequestedResource() {
return m_requestedResource;
}
/**
* Returns the requested workplace app path.<p>
*
* @return the requested workplace app path
*/
public String getRequestedWorkplaceApp() {
return m_requestedWorkplaceApp;
}
}
/**
* Attribute used to store initialization data when the UI is first loaded.
*/
public static final String INIT_DATA_SESSION_ATTR = "CmsLoginUI_initData";
/** The admin CMS context. */
static CmsObject m_adminCms;
/** Logger instance for this class. */
private static final Log LOG = CmsLog.getLog(CmsLoginUI.class);
/** Serial version id. */
private static final long serialVersionUID = 1L;
/** The login controller. */
private CmsLoginController m_controller;
/** The login form. */
private CmsLoginForm m_loginForm;
/** The widget used to open the login target. */
private CmsLoginTargetOpener m_targetOpener;
/**
* Returns the initial HTML for the Vaadin based login dialog.<p>
*
* @param request the request
* @param response the response
*
* @return the initial page HTML for the Vaadin login dialog
*
* @throws IOException in case writing to the response fails
* @throws CmsException in case the user has not the required role
*/
public static String displayVaadinLoginDialog(HttpServletRequest request, HttpServletResponse response)
throws IOException, CmsException {
CmsFlexController controller = CmsFlexController.getController(request);
if (controller == null) {
// controller not found - this request was not initialized properly
throw new CmsRuntimeException(
org.opencms.jsp.Messages.get().container(
org.opencms.jsp.Messages.ERR_MISSING_CMS_CONTROLLER_1,
CmsLoginUI.class.getName()));
}
CmsObject cms = controller.getCmsObject();
if ((OpenCms.getSiteManager().getSites().size() > 1) && !OpenCms.getSiteManager().isWorkplaceRequest(request)) {
// do not send any redirects to the workplace site for security reasons
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
String logout = request.getParameter(CmsLoginHelper.PARAM_ACTION_LOGOUT);
if (Boolean.valueOf(logout).booleanValue()) {
CmsLoginController.logout(cms, request, response);
return null;
}
if (!cms.getRequestContext().getCurrentUser().isGuestUser()) {
String target = request.getParameter(CmsGwtConstants.PARAM_LOGIN_REDIRECT);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(target)) {
target = CmsLoginController.getLoginTarget(cms, getWorkplaceSettings(cms, request.getSession()), null);
}
response.sendRedirect(target);
return null;
}
CmsLoginHelper.LoginParameters params = CmsLoginHelper.getLoginParameters(cms, request, false);
request.getSession().setAttribute(CmsLoginUI.INIT_DATA_SESSION_ATTR, params);
try {
byte[] pageBytes = CmsFileUtil.readFully(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"org/opencms/ui/login/login-page.html"));
String page = new String(pageBytes, "UTF-8");
CmsMacroResolver resolver = new CmsMacroResolver();
String context = OpenCms.getSystemInfo().getContextPath();
String vaadinDir = CmsStringUtil.joinPaths(context, "VAADIN/");
String vaadinVersion = Version.getFullVersion();
String vaadinServlet = CmsStringUtil.joinPaths(context, "workplace/dialogs/");
String vaadinBootstrap = CmsStringUtil.joinPaths(
context,
"VAADIN/vaadinBootstrap.js?v=" + OpenCms.getSystemInfo().getVersionNumber());
String autocomplete = params.isPrivatePc() ? "on" : "off";
String cmsLogo = OpenCms.getSystemInfo().getContextPath()
+ CmsWorkplace.RFS_PATH_RESOURCES
+ "commons/login_logo.png";
resolver.addMacro("loadingHtml", CmsVaadinConstants.LOADING_INDICATOR_HTML);
resolver.addMacro("vaadinDir", vaadinDir);
resolver.addMacro("vaadinVersion", vaadinVersion);
resolver.addMacro("vaadinServlet", vaadinServlet);
resolver.addMacro("vaadinBootstrap", vaadinBootstrap);
resolver.addMacro("cmsLogo", cmsLogo);
resolver.addMacro("autocomplete", autocomplete);
resolver.addMacro("title", CmsLoginHelper.getTitle(params.getLocale()));
if (params.isPrivatePc()) {
resolver.addMacro(
"hiddenPasswordField",
" <input type=\"password\" id=\"hidden-password\" name=\"ocPword\" autocomplete=\"%(autocomplete)\" >");
}
if (params.getUsername() != null) {
resolver.addMacro("predefUser", "value=\"" + CmsEncoder.escapeXml(params.getUsername()) + "\"");
}
page = resolver.resolveMacros(page);
return page;
} catch (Exception e) {
LOG.error("Failed to display login dialog.", e);
return "<!--Error
}
}
/**
* Returns the bootstrap html fragment required to display the login dialog.<p>
*
* @param cms the cms context
* @param request the request
*
* @return the html fragment
*
* @throws IOException in case reading the html template fails
*/
public static String generateLoginHtmlFragment(CmsObject cms, VaadinRequest request) throws IOException {
LoginParameters parameters = CmsLoginHelper.getLoginParameters(cms, (HttpServletRequest)request, true);
request.getWrappedSession().setAttribute(CmsLoginUI.INIT_DATA_SESSION_ATTR, parameters);
byte[] pageBytes;
pageBytes = CmsFileUtil.readFully(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"org/opencms/ui/login/login-fragment.html"));
String html = new String(pageBytes, "UTF-8");
String autocomplete = ((parameters.getPcType() == null)
|| parameters.getPcType().equals(CmsLoginHelper.PCTYPE_PRIVATE)) ? "on" : "off";
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.addMacro("autocompplete", autocomplete);
if ((parameters.getPcType() == null) || parameters.getPcType().equals(CmsLoginHelper.PCTYPE_PRIVATE)) {
resolver.addMacro(
"hiddenPasswordField",
" <input type=\"password\" id=\"hidden-password\" name=\"ocPword\" autocomplete=\"%(autocomplete)\" >");
}
if (parameters.getUsername() != null) {
resolver.addMacro("predefUser", "value=\"" + CmsEncoder.escapeXml(parameters.getUsername()) + "\"");
}
html = resolver.resolveMacros(html);
return html;
}
/**
* Sets the admin CMS object.<p>
*
* @param cms the admin cms object
*/
public static void setAdminCmsObject(CmsObject cms) {
m_adminCms = cms;
}
/**
* Returns the current users workplace settings.<p>
*
* @param cms the CMS context
* @param session the session
*
* @return the settings
*/
private static CmsWorkplaceSettings getWorkplaceSettings(CmsObject cms, HttpSession session) {
CmsWorkplaceSettings settings = (CmsWorkplaceSettings)session.getAttribute(
CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS);
if (settings == null) {
settings = CmsLoginHelper.initSiteAndProject(cms);
if (VaadinService.getCurrentRequest() != null) {
VaadinService.getCurrentRequest().getWrappedSession().setAttribute(
CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS,
settings);
} else {
session.setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings);
}
}
return settings;
}
/**
* Gets the selected org unit.<p>
*
* @return the selected org unit
*/
public String getOrgUnit() {
String result = m_loginForm.getOrgUnit();
if (result == null) {
result = "";
}
return result;
}
/**
* Gets the password.<p>
*
* @return the password
*/
public String getPassword() {
return m_loginForm.getPassword();
}
/**
* Gets the selected PC type.<p>
*
* @return the PC type
*/
public String getPcType() {
String result = m_loginForm.getPcType();
if (result == null) {
result = CmsLoginForm.PC_TYPE_PUBLIC;
}
return result;
}
/**
* Gets the user name.<p>
*
* @return the user name
*/
public String getUser() {
return m_loginForm.getUser();
}
/**
* Opens the login target for a logged in user.<p>
*
* @param loginTarget the login target
* @param isPublicPC the public PC flag
*/
public void openLoginTarget(String loginTarget, boolean isPublicPC) {
// login was successful, remove login init data from session
VaadinService.getCurrentRequest().getWrappedSession().removeAttribute(INIT_DATA_SESSION_ATTR);
m_targetOpener.openTarget(loginTarget, isPublicPC);
}
/**
* Sets the org units which should be selectable by the user.<p>
*
* @param ous the selectable org units
*/
public void setSelectableOrgUnits(List<CmsOrganizationalUnit> ous) {
m_loginForm.setSelectableOrgUnits(ous);
}
/**
* Show notification that the user is already loogged in.<p>
*/
public void showAlreadyLoggedIn() {
// TODO: do something useful
Notification.show("You are already logged in");
}
/**
* Shows the 'forgot password view'.<p>
*
* @param authToken the authorization token given as a request parameter
*/
public void showForgotPasswordView(String authToken) {
try {
CmsTokenValidator validator = new CmsTokenValidator();
String validationResult = validator.validateToken(
A_CmsUI.getCmsObject(),
authToken,
OpenCms.getLoginManager().getTokenLifetime());
if (validationResult == null) {
CmsUser user = validator.getUser();
if (!user.isManaged()) {
CmsSetPasswordDialog dlg = new CmsSetPasswordDialog(m_adminCms, user, getLocale());
A_CmsUI.get().setContentToDialog(
Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_HEADER_0)
+ user.getName(),
dlg);
} else {
Notification.show(
CmsVaadinUtils.getMessageText(Messages.ERR_USER_NOT_SELF_MANAGED_1, user.getName()),
Type.ERROR_MESSAGE);
}
} else {
A_CmsUI.get().setError(
Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_INVALID_TOKEN_0));
LOG.info("Invalid authorization token: " + authToken + " / " + validationResult);
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
/**
* Shows the given login error message.<p>
*
* @param messageHtml the message HTML
*/
public void showLoginError(String messageHtml) {
m_loginForm.displayError(messageHtml);
}
/**
* Initializes the login view.<p>
*
* @param preselectedOu a potential preselected OU
*/
public void showLoginView(String preselectedOu) {
VerticalLayout content = new VerticalLayout();
content.setSizeFull();
m_targetOpener = new CmsLoginTargetOpener(A_CmsUI.get());
//content.setExpandRatio(m_targetOpener, 0f);
content.addComponent(m_loginForm);
content.setComponentAlignment(m_loginForm, Alignment.MIDDLE_CENTER);
content.setExpandRatio(m_loginForm, 1);
setContent(content);
if (preselectedOu == null) {
preselectedOu = "/";
}
m_loginForm.selectOrgUnit(preselectedOu);
}
/**
* Shows the password reset dialog.<p>
*/
public void showPasswordResetDialog() {
String caption = CmsVaadinUtils.getMessageText(Messages.GUI_PWCHANGE_FORGOT_PASSWORD_0);
A_CmsUI r = A_CmsUI.get();
r.setContent(new Label());
Window window = CmsBasicDialog.prepareWindow(DialogWidth.narrow);
CmsBasicDialog dialog = new CmsBasicDialog();
VerticalLayout result = new VerticalLayout();
dialog.setContent(result);
window.setContent(dialog);
window.setCaption(caption);
window.setClosable(true);
final CmsForgotPasswordDialog forgotPassword = new CmsForgotPasswordDialog();
window.addCloseListener(new CloseListener() {
/** Serial version id. */
private static final long serialVersionUID = 1L;
public void windowClose(CloseEvent e) {
forgotPassword.cancel();
}
});
for (Button button : forgotPassword.getButtons()) {
dialog.addButton(button);
}
r.addWindow(window);
window.center();
VerticalLayout vl = result;
vl.addComponent(forgotPassword);
}
/**
* @see com.vaadin.ui.UI#init(com.vaadin.server.VaadinRequest)
*/
@Override
protected void init(VaadinRequest request) {
addStyleName("login-dialog");
LoginParameters params = (LoginParameters)(request.getWrappedSession().getAttribute(INIT_DATA_SESSION_ATTR));
if (params == null) {
params = CmsLoginHelper.getLoginParameters(getCmsObject(), (HttpServletRequest)request, true);
request.getWrappedSession().setAttribute(CmsLoginUI.INIT_DATA_SESSION_ATTR, params);
}
VaadinSession.getCurrent().setErrorHandler(new CmsVaadinErrorHandler());
m_controller = new CmsLoginController(m_adminCms, params);
m_controller.setUi(this);
setLocale(params.getLocale());
m_loginForm = new CmsLoginForm(m_controller, params.getLocale());
m_controller.onInit();
getPage().setTitle(
CmsAppWorkplaceUi.WINDOW_TITLE_PREFIX
+ CmsVaadinUtils.getMessageText(org.opencms.workplace.Messages.GUI_LOGIN_HEADLINE_0));
}
}
|
package org.nick.wwwjdic.widgets;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.nick.wwwjdic.Constants;
import org.nick.wwwjdic.GzipStringResponseHandler;
import org.nick.wwwjdic.KanjiEntry;
import org.nick.wwwjdic.KanjiEntryDetail;
import org.nick.wwwjdic.R;
import org.nick.wwwjdic.StringUtils;
import org.nick.wwwjdic.WwwjdicApplication;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
public class GetKanjiService extends Service {
private static final String TAG = GetKanjiService.class.getSimpleName();
private static final String DEFAULT_WWWJDIC_URL = "http:
private static final String PREF_WWWJDIC_URL_KEY = "pref_wwwjdic_mirror_url";
private static final String PREF_WWWJDIC_TIMEOUT_KEY = "pref_wwwjdic_timeout";
private static final Pattern PRE_START_PATTERN = Pattern
.compile("^<pre>.*$");
private static final Pattern PRE_END_PATTERN = Pattern
.compile("^</pre>.*$");
private static final String PRE_END_TAG = "</pre>";
private static final int NUM_RETRIES = 3;
private final RandomJisGenerator jisGenerator = new RandomJisGenerator();
private final Executor executor = Executors.newSingleThreadExecutor();
@Override
public void onStart(Intent intent, int startId) {
executor.execute(new GetKanjiTask());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class GetKanjiTask implements Runnable {
public void run() {
RemoteViews updateViews = buildUpdate(GetKanjiService.this);
ComponentName thisWidget = new ComponentName(GetKanjiService.this,
KodWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(GetKanjiService.this);
manager.updateAppWidget(thisWidget, updateViews);
stopSelf();
}
}
private RemoteViews buildUpdate(Context context) {
RemoteViews views = null;
try {
views = new RemoteViews(context.getPackageName(),
R.layout.kod_widget);
showLoading(views);
HttpClient client = createHttpClient(getWwwjdicUrl(),
getHttpTimeoutSeconds() * 1000);
String jisCode = jisGenerator.generate();
Log.d(TAG, "KOD JIS: " + jisCode);
String backdoorCode = generateBackdoorCode(jisCode);
Log.d(TAG, "backdoor code: " + backdoorCode);
String wwwjdicResponse = null;
for (int i = 0; i < NUM_RETRIES; i++) {
try {
wwwjdicResponse = query(client, getWwwjdicUrl(),
backdoorCode);
if (wwwjdicResponse != null) {
break;
}
} catch (Exception e) {
if (i < NUM_RETRIES - 1) {
Log.w(TAG, "Couldn't contact WWWJDIC, will retry.", e);
} else {
Log.e(TAG, "Couldn't contact WWWJDIC.", e);
}
}
}
if (wwwjdicResponse == null) {
Log.e(TAG, String.format("Failed to get WWWJDIC response "
+ "after %d tries, giving up.", NUM_RETRIES));
showError(views);
return views;
}
Log.d(TAG, "WWWJDIC response " + wwwjdicResponse);
List<KanjiEntry> entries = parseResult(wwwjdicResponse);
if (entries.isEmpty()) {
showError(views);
return views;
}
String kod = entries.get(0).getHeadword();
Log.d(TAG, "KOD: " + kod);
Intent intent = new Intent(context, KanjiEntryDetail.class);
intent.putExtra(Constants.KANJI_ENTRY_KEY, entries.get(0));
intent.putExtra(Constants.KOD_WIDGET_CLICK, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
views.setTextViewText(R.id.kod_text, kod);
views.setOnClickPendingIntent(R.id.kod_text, pendingIntent);
clearLoading(views);
return views;
} catch (Exception e) {
Log.e(TAG, "Couldn't contact WWWJDIC", e);
views = new RemoteViews(context.getPackageName(),
R.layout.kod_widget);
showError(views);
return views;
}
}
private void showError(RemoteViews views) {
views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
views.setTextViewText(R.id.kod_message_text, getResources().getString(
R.string.error));
views.setViewVisibility(R.id.kod_text, View.GONE);
views.setViewVisibility(R.id.kod_footer_text, View.GONE);
}
private void showLoading(RemoteViews views) {
views.setTextViewText(R.id.kod_message_text, getResources().getString(
R.string.widget_loading));
views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
views.setViewVisibility(R.id.kod_text, View.GONE);
views.setViewVisibility(R.id.kod_footer_text, View.GONE);
}
private void clearLoading(RemoteViews views) {
views.setViewVisibility(R.id.kod_message_text, View.GONE);
views.setViewVisibility(R.id.kod_text, View.VISIBLE);
views.setViewVisibility(R.id.kod_footer_text, View.VISIBLE);
}
private HttpClient createHttpClient(String url, int timeoutMillis) {
Log.d(TAG, "WWWJDIC URL: " + url);
Log.d(TAG, "HTTP timeout: " + timeoutMillis);
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMillis);
HttpProtocolParams.setUserAgent(httpParams, WwwjdicApplication
.getUserAgentString());
return httpclient;
}
private String query(HttpClient httpclient, String url, String backdoorCode) {
try {
String lookupUrl = String.format("%s?%s", url, backdoorCode);
HttpGet get = new HttpGet(lookupUrl);
GzipStringResponseHandler responseHandler = new GzipStringResponseHandler();
String responseStr = httpclient.execute(get, responseHandler);
// localContext);
return responseStr;
} catch (ClientProtocolException cpe) {
Log.e("WWWJDIC", "ClientProtocolException", cpe);
throw new RuntimeException(cpe);
} catch (IOException e) {
Log.e("WWWJDIC", "IOException", e);
throw new RuntimeException(e);
}
}
protected List<KanjiEntry> parseResult(String html) {
List<KanjiEntry> result = new ArrayList<KanjiEntry>();
boolean isInPre = false;
String[] lines = html.split("\n");
for (String line : lines) {
if (StringUtils.isEmpty(line)) {
continue;
}
Matcher m = PRE_START_PATTERN.matcher(line);
if (m.matches()) {
isInPre = true;
continue;
}
m = PRE_END_PATTERN.matcher(line);
if (m.matches()) {
break;
}
if (isInPre) {
boolean hasEndPre = false;
// some entries have </pre> on the same line
if (line.contains(PRE_END_TAG)) {
hasEndPre = true;
line = line.replaceAll(PRE_END_TAG, "");
}
Log.d(TAG, "dic entry line: " + line);
KanjiEntry entry = KanjiEntry.parseKanjidic(line);
result.add(entry);
if (hasEndPre) {
break;
}
}
}
return result;
}
private String generateBackdoorCode(String jisCode) {
StringBuffer buff = new StringBuffer();
// always "1" for kanji?
buff.append("1");
// raw
buff.append("Z");
// code
buff.append("K");
// JIS
buff.append("J");
try {
buff.append(URLEncoder.encode(jisCode, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return buff.toString();
}
private String getWwwjdicUrl() {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
return preferences.getString(PREF_WWWJDIC_URL_KEY, DEFAULT_WWWJDIC_URL);
}
private int getHttpTimeoutSeconds() {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String timeoutStr = preferences.getString(PREF_WWWJDIC_TIMEOUT_KEY,
"10");
return Integer.parseInt(timeoutStr);
}
}
|
package dr.app.util;
import java.util.StringTokenizer;
public class Arguments {
public static final String ARGUMENT_CHARACTER = "-";
public static class ArgumentException extends Exception {
private static final long serialVersionUID = -3229759954341228233L;
public ArgumentException() { super(); }
public ArgumentException(String message) { super(message); }
}
public static class Option {
public Option(String label, String description) {
this.label = label;
this.description = description;
}
String label;
String description;
boolean isAvailable = false;
}
public static class StringOption extends Option {
/**
*
* @param label Option name:
* @param tag Descriptive name of option argument.
* Example - tag "file-name" will show '-save <file-name>' in the usage.
* @param description
*/
public StringOption(String label, String tag, String description) {
super(label, description);
this.tag = tag;
}
public StringOption(String label, String[] options, boolean caseSensitive, String description) {
super(label, description);
this.options = options;
this.caseSensitive = caseSensitive;
}
String[] options = null;
String tag = null;
boolean caseSensitive = false;
String value = null;
}
public static class IntegerOption extends Option {
public IntegerOption(String label, String description) {
super(label, description);
}
public IntegerOption(String label, int minValue, int maxValue, String description) {
super(label, description);
this.minValue = minValue;
this.maxValue = maxValue;
}
int minValue = Integer.MIN_VALUE;
int maxValue = Integer.MAX_VALUE;
int value = 0;
}
public static class IntegerArrayOption extends IntegerOption {
public IntegerArrayOption(String label, String description) {
this(label, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, description);
}
public IntegerArrayOption(String label, int count, String description) {
this(label, count, Integer.MIN_VALUE, Integer.MAX_VALUE, description);
}
public IntegerArrayOption(String label, int minValue, int maxValue, String description) {
this(label, 0, minValue, maxValue, description);
}
public IntegerArrayOption(String label, int count, int minValue, int maxValue, String description) {
super(label, minValue, maxValue, description);
this.count = count; }
int count;
int[] values = null;
}
public static class LongOption extends Option {
public LongOption(String label, String description) {
super(label, description);
}
public LongOption(String label, long minValue, long maxValue, String description) {
super(label, description);
this.minValue = minValue;
this.maxValue = maxValue;
}
long minValue = Long.MIN_VALUE;
long maxValue = Long.MAX_VALUE;
long value = 0;
}
public static class RealOption extends Option {
public RealOption(String label, String description) {
super(label, description);
}
public RealOption(String label, double minValue, double maxValue, String description) {
super(label, description);
this.minValue = minValue;
this.maxValue = maxValue;
}
double minValue = Double.NEGATIVE_INFINITY;
double maxValue = Double.POSITIVE_INFINITY;
double value = 0;
}
public static class RealArrayOption extends RealOption {
public RealArrayOption(String label, String description) {
this(label, 0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, description);
}
public RealArrayOption(String label, int count, String description) {
this(label, count, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, description);
}
public RealArrayOption(String label, double minValue, double maxValue, String description) {
this(label, 0, minValue, maxValue, description);
}
public RealArrayOption(String label, int count, double minValue, double maxValue, String description) {
super(label, minValue, maxValue, description);
this.count = count;
}
private int count;
double[] values = null;
}
/**
* Parse a list of arguments ready for accessing
*/
public Arguments(Option[] options) {
this.options = options;
}
public Arguments(Option[] options, boolean caseSensitive) {
this.options = options;
this.caseSensitive = caseSensitive;
}
/**
* Parse a list of arguments ready for accessing
*/
public void parseArguments(String[] arguments) throws ArgumentException {
int[] optionIndex = new int[arguments.length];
for (int i = 0; i < optionIndex.length; i++) {
optionIndex[i] = -1;
}
for (int i = 0; i < options.length; i++) {
Option option = options[i];
int index = findArgument(arguments, option.label);
if (index != -1) {
if (optionIndex[index] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
// the first value may be appended to the option label (e.g., '-t1.0'):
String arg = arguments[index].substring(option.label.length() + 1);
optionIndex[index] = i;
option.isAvailable = true;
if (option instanceof IntegerArrayOption) {
IntegerArrayOption o = (IntegerArrayOption)option;
o.values = new int[o.count];
int k = index;
int j = 0;
while (j < o.count) {
if (arg.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(arg, ",\t ");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.length() > 0) {
try {
o.values[j] = Integer.parseInt(token);
} catch (NumberFormatException nfe) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad integer value: " + token);
}
if (o.values[j] > o.maxValue || o.values[j] < o.minValue) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad integer value: " + token);
}
j++;
}
}
}
k++;
if (j < o.count) {
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing one or more values: expecting " + o.count + " integers");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
}
} else if (option instanceof IntegerOption) {
IntegerOption o = (IntegerOption)option;
if (arg.length() == 0) {
int k = index + 1;
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing its value: expecting an integer");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
try {
o.value = Integer.parseInt(arg);
} catch (NumberFormatException nfe) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad integer value: " + arg);
}
if (o.value > o.maxValue || o.value < o.minValue) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad integer value: " + arg);
}
} else if (option instanceof LongOption) {
LongOption o = (LongOption)option;
if (arg.length() == 0) {
int k = index + 1;
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing its value: expecting a long integer");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
try {
o.value = Long.parseLong(arg);
} catch (NumberFormatException nfe) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad integer value: " + arg);
}
if (o.value > o.maxValue || o.value < o.minValue) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad long integer value: " + arg);
}
} else if (option instanceof RealArrayOption) {
RealArrayOption o = (RealArrayOption)option;
o.values = new double[o.count];
int k = index;
int j = 0;
while (j < o.count) {
if (arg.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(arg, ",\t ");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.length() > 0) {
try {
o.values[j] = Double.parseDouble(token);
} catch (NumberFormatException nfe) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad real value: " + token);
}
if (o.values[j] > o.maxValue || o.values[j] < o.minValue) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad real value: " + token);
}
j++;
}
}
}
k++;
if (j < o.count) {
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing one or more values: expecting " + o.count + " integers");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
}
} else if (option instanceof RealOption) {
RealOption o = (RealOption)option;
if (arg.length() == 0) {
int k = index + 1;
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing its value: expecting a real number");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
try {
o.value = Double.parseDouble(arg);
} catch (NumberFormatException nfe) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad real value: " + arg);
}
if (o.value > o.maxValue || o.value < o.minValue) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad real value: " + arg);
}
} else if (option instanceof StringOption) {
StringOption o = (StringOption)option;
if (arg.length() == 0) {
int k = index + 1;
if (k >= arguments.length) {
throw new ArgumentException("Argument, " + arguments[index] +
" is missing its value: expecting a string");
}
if (optionIndex[k] != -1) {
throw new ArgumentException("Argument, " + arguments[index] + " overlaps with another argument");
}
arg = arguments[k];
optionIndex[k] = i;
}
o.value = arg;
if (o.options != null) {
boolean found = false;
for (String option1 : o.options) {
if ((!caseSensitive && option1.equalsIgnoreCase(o.value)) || option1.equals(o.value)) {
found = true;
break;
}
}
if (!found) {
throw new ArgumentException("Argument, " + arguments[index] +
" has a bad string value: " + arg);
}
}
} else { // is simply an Option - nothing to do...
}
}
}
int n = 0;
int i = arguments.length - 1;
while (i >= 0 && optionIndex[i] == -1 && !arguments[i].startsWith(ARGUMENT_CHARACTER)) {
n++;
i
}
leftoverArguments = new String[n];
for (i = 0; i < n; i++) {
leftoverArguments[i] = arguments[arguments.length - n + i];
}
for (i = 0; i < arguments.length - n; i++) {
if (optionIndex[i] == -1) {
throw new ArgumentException("Unrecognized argument: " + arguments[i]);
}
}
}
private int findArgument(String[] arguments, String label) {
for (int i = 0; i < arguments.length; i++) {
if (arguments[i].length() - 1 >= label.length()) {
if (arguments[i].startsWith(ARGUMENT_CHARACTER)) {
// String l = arguments[i].substring(1, label.length() + 1);
String l = arguments[i];
if ((!caseSensitive && label.equalsIgnoreCase(l)) || label.equals(l)) {
return i;
}
}
}
}
return -1;
}
/**
* Does an argument with label exist?
*/
public boolean hasOption(String label) {
int n = findOption(label);
if (n == -1) {
return false;
}
return options[n].isAvailable;
}
/**
* Return the value of an integer option
*/
public int getIntegerOption(String label) {
IntegerOption o = (IntegerOption)options[findOption(label)];
return o.value;
}
/**
* Return the value of an integer array option
*/
public int[] getIntegerArrayOption(String label) {
IntegerArrayOption o = (IntegerArrayOption)options[findOption(label)];
return o.values;
}
/**
* Return the value of an integer option
*/
public long getLongOption(String label) {
LongOption o = (LongOption)options[findOption(label)];
return o.value;
}
/**
* Return the value of an real number option
*/
public double getRealOption(String label) {
RealOption o = (RealOption)options[findOption(label)];
return o.value;
}
/**
* Return the value of an real array option
*/
public double[] getRealArrayOption(String label) {
RealArrayOption o = (RealArrayOption)options[findOption(label)];
return o.values;
}
/**
* Return the value of an string option
*/
public String getStringOption(String label) {
StringOption o = (StringOption)options[findOption(label)];
return o.value;
}
/**
* Return any arguments leftover after the options
*/
public String[] getLeftoverArguments() {
return leftoverArguments;
}
public void printUsage(String name, String commandLine) {
System.out.print(" Usage: " + name);
for (Option option : options) {
System.out.print(" [-" + option.label);
if (option instanceof IntegerArrayOption) {
IntegerArrayOption o = (IntegerArrayOption) option;
for (int j = 1; j <= o.count; j++) {
System.out.print(" <i" + j + ">");
}
System.out.print("]");
} else if (option instanceof IntegerOption) {
System.out.print(" <i>]");
} else if (option instanceof RealArrayOption) {
RealArrayOption o = (RealArrayOption) option;
for (int j = 1; j <= o.count; j++) {
System.out.print(" <r" + j + ">");
}
System.out.print("]");
} else if (option instanceof RealOption) {
System.out.print(" <r>]");
} else if (option instanceof StringOption) {
StringOption o = (StringOption) option;
if (o.options != null) {
System.out.print(" <" + o.options[0]);
for (int j = 1; j < o.options.length; j++) {
System.out.print("|" + o.options[j]);
}
System.out.print(">]");
} else {
System.out.print(" <" + o.tag + ">]");
}
} else {
System.out.print("]");
}
}
System.out.println(" " + commandLine);
for (Option option : options) {
System.out.println(" -" + option.label + " " + option.description);
}
}
private int findOption(String label) {
for (int i = 0; i < options.length; i++) {
String l = options[i].label;
if ((!caseSensitive && label.equalsIgnoreCase(l)) || label.equals(l)) {
return i;
}
}
return -1;
}
private Option[] options = null;
private String[] leftoverArguments = null;
private boolean caseSensitive = false;
}
|
package org.commcare.util;
import org.commcare.modern.reference.ArchiveFileRoot;
import org.commcare.modern.reference.JavaFileRoot;
import org.commcare.modern.reference.JavaHttpRoot;
import org.commcare.resources.ResourceManager;
import org.commcare.resources.model.InstallCancelledException;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceInitializationException;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.FormIdDatum;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.Profile;
import org.commcare.suite.model.PropertySetter;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Suite;
import org.javarosa.core.io.BufferedInputStream;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.ResourceReferenceFactory;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageFactory;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.util.DummyIndexedStorageUtility;
import org.javarosa.core.util.externalizable.LivePrototypeFactory;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.javarosa.xpath.XPathMissingInstanceException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
import java.util.zip.ZipFile;
/**
* @author ctsims
*/
public class CommCareConfigEngine {
private final ResourceTable table;
private final ResourceTable updateTable;
private final ResourceTable recoveryTable;
private final PrintStream print;
private final CommCarePlatform platform;
private final PrototypeFactory mLiveFactory;
private ArchiveFileRoot mArchiveRoot;
public CommCareConfigEngine() {
this(new LivePrototypeFactory());
}
public CommCareConfigEngine(PrototypeFactory prototypeFactory) {
this(System.out, prototypeFactory);
}
public CommCareConfigEngine(OutputStream output, PrototypeFactory prototypeFactory) {
this.print = new PrintStream(output);
this.platform = new CommCarePlatform(2, 31);
this.mLiveFactory = prototypeFactory;
setRoots();
table = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
updateTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
recoveryTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
//All of the below is on account of the fact that the installers
//aren't going through a factory method to handle them differently
//per device.
StorageManager.forceClear();
StorageManager.setStorageFactory(new IStorageFactory() {
@Override
public IStorageUtility newStorage(String name, Class type) {
return new DummyIndexedStorageUtility(type, mLiveFactory);
}
});
StorageManager.registerStorage(Profile.STORAGE_KEY, Profile.class);
StorageManager.registerStorage(Suite.STORAGE_KEY, Suite.class);
StorageManager.registerStorage(FormDef.STORAGE_KEY,FormDef.class);
StorageManager.registerStorage(FormInstance.STORAGE_KEY, FormInstance.class);
}
private void setRoots() {
ReferenceManager._().addReferenceFactory(new JavaHttpRoot());
this.mArchiveRoot = new ArchiveFileRoot();
ReferenceManager._().addReferenceFactory(mArchiveRoot);
ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory());
}
public void initFromArchive(String archiveURL) {
String fileName;
if(archiveURL.startsWith("http")) {
fileName = downloadToTemp(archiveURL);
} else {
fileName = archiveURL;
}
ZipFile zip;
try {
zip = new ZipFile(fileName);
} catch (IOException e) {
print.println("File at " + archiveURL + ": is not a valid CommCare Package. Downloaded to: " + fileName);
e.printStackTrace(print);
System.exit(-1);
return;
}
String archiveGUID = this.mArchiveRoot.addArchiveFile(zip);
init("jr://archive/" + archiveGUID + "/profile.ccpr");
}
private String downloadToTemp(String resource) {
try{
URL url = new URL(resource);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully.
HttpURLConnection.setFollowRedirects(true);
File file = File.createTempFile("commcare_", ".ccz");
FileOutputStream fos = new FileOutputStream(file);
StreamsUtil.writeFromInputToOutput(new BufferedInputStream(conn.getInputStream()), fos);
return file.getAbsolutePath();
} catch(IOException e) {
print.println("Issue downloading or create stream for " +resource);
e.printStackTrace(print);
System.exit(-1);
return null;
}
}
public void initFromLocalFileResource(String resource) {
String reference = setFileSystemRootFromResourceAndReturnRelativeRef(resource);
init(reference);
}
private String setFileSystemRootFromResourceAndReturnRelativeRef(String resource) {
int lastSeparator = resource.lastIndexOf(File.separator);
String rootPath;
String filePart;
if(lastSeparator == -1 ) {
rootPath = new File("").getAbsolutePath();
filePart = resource;
} else {
//Get the location of the file. In the future, we'll treat this as the resource root
rootPath = resource.substring(0,resource.lastIndexOf(File.separator));
//cut off the end
filePart = resource.substring(resource.lastIndexOf(File.separator) + 1);
}
//(That root now reads as jr://file/)
ReferenceManager._().addReferenceFactory(new JavaFileRoot(rootPath));
//Now build the testing reference we'll use
return "jr://file/" + filePart;
}
private void init(String profileRef) {
try {
installAppFromReference(profileRef);
print.println("Table resources intialized and fully resolved.");
print.println(table);
} catch (InstallCancelledException e) {
print.println("Install was cancelled by the user or system");
e.printStackTrace(print);
System.exit(-1);
} catch (UnresolvedResourceException e) {
print.println("While attempting to resolve the necessary resources, one couldn't be found: " + e.getResource().getResourceId());
e.printStackTrace(print);
System.exit(-1);
} catch (UnfullfilledRequirementsException e) {
print.println("While attempting to resolve the necessary resources, a requirement wasn't met");
e.printStackTrace(print);
System.exit(-1);
}
}
public void installAppFromReference(String profileReference) throws UnresolvedResourceException,
UnfullfilledRequirementsException, InstallCancelledException {
ResourceManager.installAppResources(platform, profileReference, this.table, true);
}
public void initEnvironment() {
try {
Localization.init(true);
table.initializeResources(platform, false);
//Make sure there's a default locale, since the app doesn't necessarily use the
//localization engine
Localization.getGlobalLocalizerAdvanced().addAvailableLocale("default");
Localization.setDefaultLocale("default");
print.println("Locales defined: ");
for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
System.out.println("* " + locale);
}
setDefaultLocale();
} catch (ResourceInitializationException e) {
print.println("Error while initializing one of the resolved resources");
e.printStackTrace(print);
System.exit(-1);
}
}
private void setDefaultLocale() {
String defaultLocale = "default";
for (PropertySetter prop : platform.getCurrentProfile().getPropertySetters()) {
if ("cur_locale".equals(prop.getKey())) {
defaultLocale = prop.getValue();
break;
}
}
print.println("Setting locale to: " + defaultLocale);
Localization.setLocale(defaultLocale);
}
public void describeApplication() {
print.println("Locales defined: ");
for(String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
System.out.println("* " + locale);
}
Localization.setDefaultLocale("default");
Vector<Menu> root = new Vector<>();
Hashtable<String, Vector<Menu>> mapping = new Hashtable<>();
mapping.put("root",new Vector<Menu>());
for(Suite s : platform.getInstalledSuites()) {
for(Menu m : s.getMenus()) {
if(m.getId().equals("root")) {
root.add(m);
} else {
Vector<Menu> menus = mapping.get(m.getRoot());
if(menus == null) {
menus = new Vector<>();
}
menus.add(m);
mapping.put(m.getRoot(), menus);
}
}
}
for(String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
Localization.setLocale(locale);
print.println("Application details for locale: " + locale);
print.println("CommCare");
for(Menu m : mapping.get("root")) {
print.println("|- " + m.getName().evaluate());
for(String command : m.getCommandIds()) {
for(Suite s : platform.getInstalledSuites()) {
if(s.getEntries().containsKey(command)) {
print(s,s.getEntries().get(command),2);
}
}
}
}
for(Menu m : root) {
for(String command : m.getCommandIds()) {
for(Suite s : platform.getInstalledSuites()) {
if(s.getEntries().containsKey(command)) {
print(s,s.getEntries().get(command),1);
}
}
}
}
}
}
public CommCarePlatform getPlatform() {
return platform;
}
public FormDef loadFormByXmlns(String xmlns) {
IStorageUtilityIndexed<FormDef> formStorage =
(IStorageUtilityIndexed)StorageManager.getStorage(FormDef.STORAGE_KEY);
return formStorage.getRecordForValue("XMLNS", xmlns);
}
private void print(Suite s, Entry e, int level) {
String head = "";
String emptyhead = "";
for(int i = 0; i < level; ++i ){
head += "|- ";
emptyhead += " ";
}
if (e.isView()) {
print.println(head + "View: " + e.getText().evaluate());
} else {
print.println(head + "Entry: " + e.getText().evaluate());
}
for(SessionDatum datum : e.getSessionDataReqs()) {
if(datum instanceof FormIdDatum) {
print.println(emptyhead + "Form: " + datum.getValue());
} else if (datum instanceof EntityDatum) {
String shortDetailId = ((EntityDatum)datum).getShortDetail();
if(shortDetailId != null) {
Detail d = s.getDetail(shortDetailId);
try {
print.println(emptyhead + "|Select: " + d.getTitle().getText().evaluate(new EvaluationContext(null)));
} catch(XPathMissingInstanceException ex) {
print.println(emptyhead + "|Select: " + "(dynamic title)");
}
print.print(emptyhead + "| ");
for(DetailField f : d.getFields()) {
print.print(f.getHeader().evaluate() + " | ");
}
print.print("\n");
}
}
}
}
final static private class QuickStateListener implements TableStateListener{
int lastComplete = 0;
@Override
public void simpleResourceAdded() {
}
@Override
public void compoundResourceAdded(ResourceTable table) {
}
@Override
public void incrementProgress(int complete, int total) {
int diff = complete - lastComplete;
lastComplete = complete;
for(int i = 0 ; i < diff ; ++i) {
System.out.print(".");
}
}
}
public void attemptAppUpdate(String updateTarget) {
ResourceTable global = table;
// Ok, should figure out what the state of this bad boy is.
Resource profileRef = global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
Profile profileObj = this.getPlatform().getCurrentProfile();
global.setStateListener(new QuickStateListener());
updateTable.setStateListener(new QuickStateListener());
// When profileRef points is http, add appropriate dev flags
String authRef = profileObj.getAuthReference();
try {
URL authUrl = new URL(authRef);
// profileRef couldn't be parsed as a URL, so don't worry
// about adding dev flags to the url's query
// If we want to be using/updating to the latest build of the
// app (instead of latest release), add it to the query tags of
// the profile reference
if (updateTarget!= null &&
("https".equals(authUrl.getProtocol()) ||
"http".equals(authUrl.getProtocol()))) {
if (authUrl.getQuery() != null) {
// If the profileRef url already have query strings
// just add a new one to the end
authRef = authRef + "&target=" + updateTarget;
} else {
// otherwise, start off the query string with a ?
authRef = authRef + "?target" + updateTarget;
}
}
} catch (MalformedURLException e) {
System.out.print("Warning: Unrecognized URL format: " + authRef);
}
try {
// This populates the upgrade table with resources based on
// binary files, starting with the profile file. If the new
// profile is not a newer version, statgeUpgradeTable doesn't
// actually pull in all the new references
System.out.println("Checking for updates....");
ResourceManager resourceManager = new ResourceManager(platform, global, updateTable, recoveryTable);
resourceManager.stageUpgradeTable(authRef, true);
Resource newProfile = updateTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if (!newProfile.isNewer(profileRef)) {
System.out.println("Your app is up to date!");
return;
}
System.out.println("Update found. New Version: " + newProfile.getVersion());
System.out.println("Downloading / Preparing Update");
resourceManager.prepareUpgradeResources();
System.out.print("Installing update");
// Replaces global table with temporary, or w/ recovery if
// something goes wrong
resourceManager.upgrade();
} catch(UnresolvedResourceException e) {
System.out.println("Update Failed! Couldn't find or install one of the remote resources");
e.printStackTrace();
return;
} catch(UnfullfilledRequirementsException e) {
System.out.println("Update Failed! This CLI host is incompatible with the app");
e.printStackTrace();
return;
} catch(Exception e) {
System.out.println("Update Failed! There is a problem with one of the resources");
e.printStackTrace();
return;
}
// Initializes app resources and the app itself, including doing a check to see if this
// app record was converted by the db upgrader
initEnvironment();
}
}
|
package net.kencochrane.raven.jul;
import net.kencochrane.raven.Raven;
import net.kencochrane.raven.RavenFactory;
import net.kencochrane.raven.dsn.Dsn;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.interfaces.ExceptionInterface;
import net.kencochrane.raven.event.interfaces.MessageInterface;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.*;
/**
* Logging handler in charge of sending the java.util.logging records to a Sentry server.
*/
public class SentryHandler extends Handler {
protected Raven raven;
private final boolean propagateClose;
private boolean guard = false;
public SentryHandler() {
propagateClose = true;
}
public SentryHandler(Raven raven) {
this(raven, false);
}
public SentryHandler(Raven raven, boolean propagateClose) {
this.raven = raven;
this.propagateClose = propagateClose;
}
protected static Event.Level getLevel(Level level) {
if (level.intValue() >= Level.SEVERE.intValue())
return Event.Level.ERROR;
else if (level.intValue() >= Level.WARNING.intValue())
return Event.Level.WARNING;
else if (level.intValue() >= Level.INFO.intValue())
return Event.Level.INFO;
else if (level.intValue() >= Level.ALL.intValue())
return Event.Level.DEBUG;
else return null;
}
private static List<String> formatParameters(Object[] parameters) {
List<String> formattedParameters = new ArrayList<String>(parameters.length);
for (Object parameter : parameters)
formattedParameters.add((parameter != null) ? parameter.toString() : null);
return formattedParameters;
}
@Override
public synchronized void publish(LogRecord record) {
// Do not log the event if the current thread has been spawned by raven or if the event has been created during
// the logging of an other event.
if (!isLoggable(record) || Raven.RAVEN_THREAD.get() || guard)
return;
try {
guard = true;
if (raven == null)
initRaven();
Event event = buildEvent(record);
raven.sendEvent(event);
} finally {
guard = false;
}
}
/**
* Initialises the Raven instance.
*/
protected void initRaven() {
try {
if (dsn == null)
dsn = Dsn.dsnLookup();
raven = RavenFactory.ravenInstance(new Dsn(dsn), ravenFactory);
} catch (Exception e) {
reportError("An exception occurred during the creation of a raven instance", e, ErrorManager.OPEN_FAILURE);
}
}
protected Event buildEvent(LogRecord record) {
EventBuilder eventBuilder = new EventBuilder()
.setLevel(getLevel(record.getLevel()))
.setTimestamp(new Date(record.getMillis()))
.setLogger(record.getLoggerName());
if (record.getSourceClassName() != null && record.getSourceMethodName() != null) {
StackTraceElement fakeFrame = new StackTraceElement(record.getSourceClassName(),
record.getSourceMethodName(), null, -1);
eventBuilder.setCulprit(fakeFrame);
} else {
eventBuilder.setCulprit(record.getLoggerName());
}
if (record.getThrown() != null) {
eventBuilder.addSentryInterface(new ExceptionInterface(record.getThrown()));
}
if (record.getParameters() != null) {
eventBuilder.addSentryInterface(new MessageInterface(record.getMessage(),
formatParameters(record.getParameters())));
} else {
eventBuilder.setMessage(record.getMessage());
}
raven.runBuilderHelpers(eventBuilder);
return eventBuilder.build();
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
try {
if (propagateClose)
raven.getConnection().close();
} catch (IOException e) {
reportError("An exception occurred while closing the raven connection", e, ErrorManager.CLOSE_FAILURE);
}
}
}
|
// A zorbage example: visualizing the Lorenz system using jMonkeyEngine.
// This code is in the public domain. Use however you wish.
package lorenz;
import com.jme3.app.*;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Line;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.algorithm.ClassicRungeKutta;
import nom.bdezonia.zorbage.procedure.Procedure3;
import nom.bdezonia.zorbage.type.data.float32.real.Float32Member;
import nom.bdezonia.zorbage.type.data.float32.real.Float32VectorMember;
import nom.bdezonia.zorbage.type.storage.datasource.ArrayDataSource;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class Main extends SimpleApplication {
@Override
public void simpleInitApp() {
Procedure3<Float32Member,Float32VectorMember, Float32VectorMember> lorenz =
new Procedure3<Float32Member, Float32VectorMember, Float32VectorMember>()
{
private final float SIGMA = 10;
private final float RHO = 28;
private final float BETA = 8f/3;
private Float32Member xc = G.FLT.construct();
private Float32Member yc = G.FLT.construct();
private Float32Member zc = G.FLT.construct();
@Override
public void call(Float32Member t, Float32VectorMember y, Float32VectorMember result) {
if (y.length() != 4)
throw new IllegalArgumentException("oops");
result.alloc(4);
y.v(0, xc);
y.v(1, yc);
y.v(2, zc);
Float32Member v = G.FLT.construct();
v.setV(SIGMA * (yc.v()-xc.v()));
result.setV(0, v);
v.setV(xc.v()*(RHO-zc.v()) - yc.v());
result.setV(1, v);
v.setV(xc.v()*yc.v() - BETA*zc.v());
result.setV(2, v);
v.setV(1);
result.setV(3, v);
}
};
Float32VectorMember value = G.FLT_VEC.construct();
Float32Member t0 = G.FLT.construct();
Float32VectorMember y0 = G.FLT_VEC.construct("[0.5,0.5,0.1,0]");
int numSteps = 50000;
Float32Member dt = G.FLT.construct(((Double)(1.0 / 64)).toString());
IndexedDataSource<Float32VectorMember> results = ArrayDataSource.construct(G.FLT_VEC, numSteps);
ClassicRungeKutta.compute(G.FLT_VEC, G.FLT, lorenz, t0, y0, numSteps, dt, results);
float[] xs = new float[numSteps];
float[] ys = new float[numSteps];
float[] zs = new float[numSteps];
float[] ts = new float[numSteps];
Float32Member component = G.FLT.construct();
for (int i = 0; i < numSteps; i++) {
results.get(i, value);
value.v(0, component);
xs[i] = component.v();
value.v(1, component);
ys[i] = component.v();
value.v(2, component);
zs[i] = component.v();
value.v(3, component);
ts[i] = component.v();
}
Node origin = new Node("origin");
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md"); // create a simple material
mat.setColor("Color", ColorRGBA.Blue); // set color of material to blue
for (int i = 1; i < numSteps; i++) {
Vector3f start = new Vector3f(xs[i-1], ys[i-1], zs[i-1]);
Vector3f end = new Vector3f(xs[i], ys[i], zs[i]);
Line l = new Line(start, end);
Geometry geom = new Geometry("Line", l); // create geometry from the line
geom.setMaterial(mat); // set the line's material
origin.attachChild(geom);
}
rootNode.attachChild(origin); // make the geometry appear in the scene
}
public static void main(String[] args){
Main app = new Main();
app.start(); // start the viewer
}
}
|
package uk.org.ponder.beanutil;
import java.util.List;
import uk.org.ponder.saxalizer.MethodAnalyser;
import uk.org.ponder.saxalizer.SAXalizerMappingContext;
import uk.org.ponder.stringutil.CharWrap;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* @author Antranig Basman ([email protected])
*
*/
public class BeanUtil {
/**
* The String prefix used for the ID of a freshly created entity to an
* "obstinate" BeanLocator. The text following the prefix is arbitrary. Surely
* noone would be perverse enough to manage to create a legitimate object ID
* containing a space.
*/
public static String NEW_ENTITY_PREFIX = "new ";
// public static final String ELQUOTSTART = "['";
// public static final String ELQUOTEND = "]'";
// TODO: parse the special .['thing with.dots']. form of property names.
public static String[] splitEL(String path) {
// StringList components = new StringList();
// boolean wassquare = true;
// int end = path.length();
// for (int i = 0; i < end; ++ i) {
// if (path.startsWith(ELQUOTSTART, i)) {
// int quotend = path.indexOf(ELQUOTEND, i + 2);
// if (quotend == -1) {
// i + " in "
// + path + " was not closed");
// char c = path.charAt(i);
// if (c == '[' && i < end - 1 && path.charAt(i + 1) == '')
return path.split("\\.");
}
public static String composeEL(String head, String tail) {
return head + '.' + tail;
}
public static String composeEL(StringList tocompose) {
CharWrap togo = new CharWrap();
for (int i = 0; i < tocompose.size(); ++i) {
togo.append(tocompose.stringAt(i));
if (i != tocompose.size() - 1) {
togo.append(".");
}
}
return togo.toString();
}
public static Object navigate(Object rootobj, String path,
SAXalizerMappingContext mappingcontext) {
if (path == null || path.equals("")) {
return rootobj;
}
String[] components = splitEL(path);
Object moveobj = rootobj;
for (int comp = 0; comp < components.length; ++comp) {
if (moveobj == null) {
throw UniversalRuntimeException.accumulate(new IllegalArgumentException(),
"Null value encounted in bean path at component " + components[comp - 1]);
}
if (moveobj instanceof List) {
List movelist = (List) moveobj;
int index = Integer.valueOf(components[comp]).intValue();
moveobj = movelist.get(index);
}
else if (moveobj.getClass().isArray()) {
Object[] movearr = (Object[]) moveobj;
int index = Integer.valueOf(components[comp]).intValue();
moveobj = movearr[index];
}
else {
PropertyAccessor pa = MethodAnalyser.getPropertyAccessor(moveobj,
mappingcontext);
moveobj = pa.getProperty(moveobj, components[comp]);
}
// AccessMethod am = DARApplier.getAMExpected(moveobj, components[comp],
// mappingcontext);
// moveobj = am.getChildObject(moveobj);
}
return moveobj;
}
/**
* Given a string representing an EL expression beginning #{ and ending },
* strip these off returning the bare expression. If the bracketing characters
* are not present, return null.
*/
public static String stripEL(String el) {
if (el == null) {
return null;
}
else if (el.startsWith("#{") && el.endsWith("}")) {
return el.substring(2, el.length() - 1);
}
else
return null;
}
public static String stripELNoisy(String el) {
String stripped = stripEL(el);
if (stripped == null) {
throw new IllegalArgumentException("EL expression \"" + el + "\" is not bracketed with
}
return stripped;
}
}
|
package uk.org.ponder.rsac;
import java.beans.PropertyChangeEvent;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.log4j.Level;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import uk.org.ponder.beanutil.FallbackBeanLocator;
import uk.org.ponder.beanutil.WriteableBeanLocator;
import uk.org.ponder.reflect.ReflectUtils;
import uk.org.ponder.reflect.ReflectiveCache;
import uk.org.ponder.saxalizer.AccessMethod;
import uk.org.ponder.saxalizer.MethodAnalyser;
import uk.org.ponder.saxalizer.SAXalizerMappingContext;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.util.Denumeration;
import uk.org.ponder.util.EnumerationConverter;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.UniversalRuntimeException;
public class RSACBeanLocator implements ApplicationContextAware {
private static Object BEAN_IN_CREATION_OBJECT = new Object();
private ConfigurableApplicationContext blankcontext;
private ApplicationContext parentcontext;
private SAXalizerMappingContext smc;
private ReflectiveCache reflectivecache;
public RSACBeanLocator(ConfigurableApplicationContext context) {
this.blankcontext = context;
}
// NB - currently used only for leafparsers, which are currently JVM-static.
public void setMappingContext(SAXalizerMappingContext smc) {
this.smc = smc;
}
public void setApplicationContext(ApplicationContext applicationContext) {
parentcontext = applicationContext;
}
public void setReflectiveCache(ReflectiveCache reflectivecache) {
this.reflectivecache = reflectivecache;
}
/**
* Initialises the RSAC container if it has not already been so by
* protoStartRequest. Enters the supplied request and response as
* postprocessors for any RequestAware beans in the container.
*/
public void startRequest() {
}
public boolean isStarted() {
return threadlocal.get() != null;
}
/**
* Called at the end of a request. I advise doing this in a finally block.
*/
public void endRequest() {
PerRequestInfo pri = getPerRequest();
for (int i = 0; i < pri.todestroy.size(); ++i) {
String todestroyname = pri.todestroy.stringAt(i);
String destroymethod = (String) rbimap.get(todestroyname);
Object todestroy = null;
try {
todestroy = getBean(pri, todestroyname, false);
reflectivecache.invokeMethod(todestroy, destroymethod);
}
// must try to destroy as many beans as possible, cannot propagate
// exception in a finally block in any case.
catch (Exception e) {
Logger.log.error("Error destroying bean " + todestroy + " with name "
+ todestroyname, e);
}
}
// System.out.println(pri.cbeans + " beans were created");
// Give the garbage collector a head start
pri.clear();
}
// this is a map of bean names to RSACBeanInfo
private HashMap rbimap;
// this is a list of the beans of type RSACLazyTargetSources
private StringList lazysources;
// this is a list of "fallback" beans that have already been queried
private StringList fallbacks;
public void init() {
// at this point we actually expect that the "Dead" factory is FULLY
// CREATED. This checks that all dependencies are resolvable (if this
// has not already been checked by the IDE).
String[] beanNames = blankcontext.getBeanDefinitionNames();
ConfigurableListableBeanFactory factory = blankcontext.getBeanFactory();
// prepare our list of dependencies.
rbimap = new HashMap();
lazysources = new StringList();
fallbacks = new StringList();
for (int i = 0; i < beanNames.length; i++) {
String beanname = beanNames[i];
try {
RSACBeanInfo rbi = BeanDefUtil.convertBeanDef(factory, beanname);
rbimap.put(beanname, rbi);
}
catch (Exception e) {
Logger.log.error("Error loading definition for bean " + beanname, e);
}
}
// Make a last-ditch attempt to infer bean types.
for (int i = 0; i < beanNames.length; ++i) {
String beanname = beanNames[i];
RSACBeanInfo rbi = (RSACBeanInfo) rbimap.get(beanname);
if (rbi.beanclass == null) {
rbi.beanclass = getBeanClass(beanname);
}
if (rbi.beanclass != null) {
if (rbi.islazyinit) { // this will cause an error at
lazysources.add(beanname);
}
if (FallbackBeanLocator.class.isAssignableFrom(rbi.beanclass)) {
fallbacks.add(beanname);
}
rbi.isfactorybean = FactoryBean.class.isAssignableFrom(rbi.beanclass);
}
}
}
/**
* Returns the class of this bean, if it can be statically determined,
* <code>null</code> if it cannot (i.e. this bean is the product of a
* factory-method of a class which is not yet known)
*
* @param beanname
* @return
*/
public Class getBeanClass(String beanname) {
RSACBeanInfo rbi = (RSACBeanInfo) rbimap.get(beanname);
if (rbi == null) {
return parentcontext.getType(beanname);
}
else if (rbi.beanclass != null) {
return rbi.beanclass;
}
else if (rbi.factorymethod != null && rbi.factorybean != null) {
try {
Class factoryclass = getBeanClass(rbi.factorybean);
Method m = ReflectiveCache.getMethod(factoryclass, rbi.factorymethod);
if (m != null) {
rbi.beanclass = m.getReturnType();
}
}
catch (Exception e) {
Logger.log.warn("Error reflecting for factory method "
+ rbi.factorymethod + " in bean " + rbi.factorybean, e);
}
}
// Noone could possibly say we didn't do our best to work out the type of
// this bean.
return rbi.beanclass;
}
private ThreadLocal threadlocal = new ThreadLocal() {
public Object initialValue() {
return new PerRequestInfo(RSACBeanLocator.this, lazysources);
}
};
private PerRequestInfo getPerRequest() {
return (PerRequestInfo) threadlocal.get();
}
public void addPostProcessor(BeanPostProcessor beanpp) {
getPerRequest().postprocessors.add(beanpp);
}
private Object getLocalBean(PerRequestInfo pri, String beanname,
boolean nolazy) {
Object bean = pri.beans.locateBean(beanname);
if (bean == BEAN_IN_CREATION_OBJECT) {
throw new BeanCurrentlyInCreationException(beanname);
}
else if (bean == null) {
FactoryBean pfb = (FactoryBean) pri.lazysources.get(beanname);
if (pfb != null && !nolazy) {
try {
return pfb.getObject();
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error getting proxied bean");
}
}
else {
bean = createBean(pri, beanname);
}
}
return bean;
}
// package access ensures visibility from RSACLazyTargetSource
Object getBean(PerRequestInfo pri, String beanname, boolean nolazy) {
Object bean = null;
// NOTES on parentage: We actually WOULD like to make the "blank" context
// a child context of the parent, so that we could resolve parents across the
// gap - the problem is the line below, where we distinguish local beans from
// parent ones. Revisit this when we have a sensible idea about parent contexts.
if (blankcontext.containsBean(beanname)) {
bean = getLocalBean(pri, beanname, nolazy);
}
else {
if (bean == null) {
bean = this.parentcontext.getBean(beanname);
}
}
return bean;
}
public StringList getFallbackBeans() {
return fallbacks;
}
private Object assembleVectorProperty(PerRequestInfo pri,
StringList beannames, Class declaredType) {
Object deliver = ReflectUtils.instantiateContainer(declaredType, beannames
.size(), reflectivecache);
Denumeration den = EnumerationConverter.getDenumeration(deliver);
for (int i = 0; i < beannames.size(); ++i) {
String thisbeanname = beannames.stringAt(i);
Object bean = getBean(pri, thisbeanname, false);
den.add(bean);
}
return deliver;
}
private Object createBean(PerRequestInfo pri, String beanname) {
++pri.cbeans;
pri.beans.set(beanname, BEAN_IN_CREATION_OBJECT);
RSACBeanInfo rbi = (RSACBeanInfo) rbimap.get(beanname);
if (rbi == null) {
throw new NoSuchBeanDefinitionException(beanname,
"Bean definition not found");
}
Object newbean;
// NB - isn't this odd, and in fact generally undocumented - properties
// defined for factory-method beans are set on the PRODUCT, whereas those
// set on FactoryBeans are set on the FACTORY!!
if (rbi.factorybean != null) {
Object factorybean = getBean(pri, rbi.factorybean, false);
newbean = reflectivecache.invokeMethod(factorybean, rbi.factorymethod);
if (newbean == null) {
throw new IllegalArgumentException(
"Error: null returned from factory method " + rbi.factorymethod
+ " of bean " + rbi.factorybean);
}
// rbi.beanclass = newbean.getClass();
}
else {
// Locate the "dead" bean from the genuine Spring context, and clone it
// as quick as we can - bytecodes might do faster but in the meantime
// observe that a clone typically costs 1.6 reflective calls so in general
// this method will win over a reflective solution.
// NB - all Copiables simply copy dependencies manually for now, no cost.
// Copiable deadbean = (Copiable) livecontext.getBean(rbi.isfactorybean?
// "&" +beanname : beanname);
// All the same, the following line will cost us close to 1us - unless it
// invokes manual code!
newbean = reflectivecache.construct(rbi.beanclass);
}
if (rbi.hasDependencies()) {
// guard this block since if it is a factory-method bean it may be
// something
// extremely undesirable (like an inner class) that we should not even
// dream of reflecting over. If on the other hand the user has specified
// some dependencies they doubtless know what they are doing.
MethodAnalyser ma = smc.getAnalyser(rbi.beanclass);
// Object clonebean = deadbean.copy();
// iterate over each LOCAL dependency of the bean with given name.
for (Iterator depit = rbi.dependencies(); depit.hasNext();) {
String propertyname = (String) depit.next();
try {
AccessMethod setter = ma.getAccessMethod(propertyname);
Object depbean = null;
Object beanref = rbi.beannames(propertyname);
if (beanref instanceof String) {
depbean = getBean(pri, (String) beanref, false);
}
else if (beanref instanceof ValueHolder) {
Class accezzz = setter.getAccessedType();
String value = ((ValueHolder) beanref).value;
if (smc.saxleafparser.isLeafType(accezzz)) {
depbean = smc.saxleafparser.parse(accezzz, value);
}
else {
// exception def copied from the beast BeanWrapperImpl!
throw new TypeMismatchException(new PropertyChangeEvent(newbean,
propertyname, null, value), accezzz, null);
}
}
else {
// Really need generalised conversion of vector values here.
// The code to do this is actually WITHIN the grotty BeanWrapperImpl
// itself in a protected method with 5 arguments!!
// This is a sort of 50% solution. It will deal with all 1-d array
// types and collections
// although clearly there is no "value" support yet and probably
// never will be.
depbean = assembleVectorProperty(pri, (StringList) beanref, setter
.getDeclaredType());
}
// Lose another 500ns here, until we bring on FastClass.
setter.setChildObject(newbean, depbean);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error setting dependency " + propertyname + " of bean "
+ beanname);
}
}
}
// process it FIRST since it will be the factory that is expecting the
// dependencies
// set!
processNewBean(pri, beanname, newbean);
if (rbi.initmethod != null) {
reflectivecache.invokeMethod(newbean, rbi.initmethod);
}
if (newbean instanceof InitializingBean) {
try {
((InitializingBean) newbean).afterPropertiesSet();
}
catch (Exception e) { // Evil Rod! Bad Juergen!
throw UniversalRuntimeException.accumulate(e);
}
}
if (rbi.destroymethod != null) {
pri.todestroy.add(beanname);
}
if (newbean instanceof FactoryBean) {
FactoryBean factorybean = (FactoryBean) newbean;
try {
newbean = factorybean.getObject();
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e);
}
}
// enter the bean into the req-specific map.
pri.beans.set(beanname, newbean);
// now the bean is initialised, attempt to call any init-method or InitBean.
return newbean;
}
private void processNewBean(PerRequestInfo pri, String beanname,
Object newbean) {
for (int i = 0; i < pri.postprocessors.size(); ++i) {
BeanPostProcessor beanpp = (BeanPostProcessor) pri.postprocessors.get(i);
try {
beanpp.postProcessBeforeInitialization(newbean, beanname);
// someday we might put something in between here.
beanpp.postProcessAfterInitialization(newbean, beanname);
}
catch (Exception e) {
Logger.log.log(Level.ERROR, "Exception processing bean "
+ newbean.getClass().getName(), e);
}
}
if (newbean instanceof BeanFactoryAware) {
((BeanFactoryAware) newbean).setBeanFactory(pri.blfactory);
}
if (newbean instanceof BeanNameAware) {
((BeanNameAware) newbean).setBeanName(beanname);
}
if (newbean instanceof ApplicationContextAware) {
((ApplicationContextAware) newbean).setApplicationContext(parentcontext);
}
}
/**
* This method gets a BeanLocator which is good just for the current request
* scope. The ThreadLocal barrier has already been breached in the returned
* object, and evaluation will proceed quickly.
*/
public WriteableBeanLocator getBeanLocator() {
PerRequestInfo pri = getPerRequest();
return pri.requestwbl;
}
/**
* Scope of this BeanLocator is the same as previous, but it will NOT
* auto-create beans that are not present.
*/
public WriteableBeanLocator getDeadBeanLocator() {
PerRequestInfo pri = getPerRequest();
return pri.beans;
}
}
|
package tv.hromadske.app.fragments;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import tv.hromadske.app.R;
import tv.hromadske.app.VideoUkrActivity;
import tv.hromadske.app.utils.SystemUtils;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FragmentVideos extends Fragment implements OnClickListener {
private Button btnEng, btnUkr;
private View containerLoad;
private String engUrl = "";
private String ukrUrl = "";
public FragmentVideos() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_videos, null);
btnUkr = (Button) v.findViewById(R.id.btn_ukr);
btnEng = (Button) v.findViewById(R.id.btn_eng);
containerLoad = v.findViewById(R.id.container_load);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
containerLoad.setOnClickListener(this);
btnUkr.setOnClickListener(this);
btnEng.setOnClickListener(this);
GetYoutubeUrlTask getYoutubeUrlTask = new GetYoutubeUrlTask(containerLoad);
getYoutubeUrlTask.execute();
}
@Override
public void onClick(View v) {
Intent intent;
intent = new Intent(getActivity(), VideoUkrActivity.class);
switch (v.getId()) {
case R.id.btn_ukr:
if (!ukrUrl.isEmpty()) {
intent.putExtra(SystemUtils.UKR_URL, ukrUrl);
startActivity(intent);
} else {
Toast.makeText(getActivity(), R.string.no_link, Toast.LENGTH_LONG).show();
}
break;
case R.id.btn_eng:
if (!engUrl.isEmpty()) {
intent.putExtra(SystemUtils.UKR_URL, engUrl);
startActivity(intent);
} else {
Toast.makeText(getActivity(), R.string.no_link, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
public class GetYoutubeUrlTask extends AsyncTask<Void, Void, Boolean> {
private View loadView;
public GetYoutubeUrlTask(View loadView) {
super();
this.loadView = loadView;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loadView.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
HttpGet httpGet = new HttpGet(String.format(SystemUtils.GDATA_URL));
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpResponse dresponse = mHttpClient.execute(httpGet);
int status = dresponse.getStatusLine().getStatusCode();
if (status == 200) {
String res = SystemUtils.streamToString(dresponse.getEntity().getContent());
JSONObject jRoot = new JSONObject(res);
JSONArray jArray = jRoot.optJSONObject("feed").optJSONArray("entry");
String str = jArray.optJSONObject(0).optJSONObject("content").optString("src");
str = str.substring(str.lastIndexOf('/') + 1);
int index = str.lastIndexOf("?");
if (index > 0){
str = str.substring(0, index);
}
//Log.i("GDATA", " " + str);
ukrUrl = str;
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
loadView.setVisibility(View.GONE);
}
}
}
|
package com.intellij.idea;
import com.intellij.ide.customize.CustomizeIDEWizardStepsProvider;
import com.intellij.util.PlatformUtils;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.concurrent.CompletionStage;
@SuppressWarnings({"UnusedDeclaration"})
public final class MainImpl implements StartupUtil.AppStarter {
public MainImpl() {
PlatformUtils.setDefaultPrefixForCE();
}
@Override
public void start(@NotNull List<String> args, @NotNull CompletionStage<?> initUiTask) {
ApplicationLoader.initApplication(args, initUiTask);
}
@Override
public void startupWizardFinished(@NotNull CustomizeIDEWizardStepsProvider provider) {
IdeStarter.setWizardStepsProvider(provider);
}
}
|
package qaframework.rtv.tests;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TranslationArchiveTests extends TestBase {
@Test(testName = "RTV-19", description = "Catalog Exist")
public void catalogExist() throws Exception {
app.getNavigationHelper().openMainPage();
AccountData account = new AccountData();
account.username = "test004";
account.password = "004test";
app.getAccountHelper().fillLoginForm(app, account);
app.getNavigationHelper().clickCheckBoxRemember();
app.getNavigationHelper().clickButtonLogin();
Thread.sleep(5000);
app.getNavigationHelper().clickpersonalArchiveEventsHeaderControl();
Thread.sleep(2000);
app.getNavigationHelper().clickpersonalArchiveEventsCatalogControl();
Assert.assertTrue(app.getNavigationHelper().gettableArchiveEventsFirstRow());
app.getNavigationHelper().clicktableArchiveEventsFirstRow();
String getArchiveEventsModalName = app.getNavigationHelper().getArchiveEventsModalName();
app.getNavigationHelper().clickBuyLink();
Thread.sleep(2000);
String getIpProductName = app.getNavigationHelper().getIpProductName();
assertThat(getIpProductName, containsString(getArchiveEventsModalName));
app.getNavigationHelper().navigate_back();
Thread.sleep(2000);
app.getNavigationHelper().clickButtonExit();
}
@Test
public void catalogBoughtEventsExist() throws Exception {
app.getNavigationHelper().openMainPage();
AccountData account = new AccountData();
account.username = "test003";
account.password = "003test";
app.getAccountHelper().fillLoginForm(app, account);
app.getNavigationHelper().clickCheckBoxRemember();
app.getNavigationHelper().clickButtonLogin();
Thread.sleep(5000);
app.getNavigationHelper().clickpersonalArchiveEventsHeaderControl();
//Thread.sleep(5000);
//app.getNavigationHelper().clickpersonalArchiveEventsHeaderControl();
Thread.sleep(2000);
app.getNavigationHelper().clickpersonalArchiveEventsPurchasesControl();
Thread.sleep(1000);
String productId = app.getNavigationHelper().getProductId();
//app.getNavigationHelper().openMainPage();
app.getNavigationHelper().openPageForSetPayment();
app.getNavigationHelper().fillFormForSetPayment(app, account, productId);
app.getNavigationHelper().clickButtonSetPayment();
app.getNavigationHelper().openMainPage();
Thread.sleep(4000);
app.getNavigationHelper().clickpersonalArchiveEventsHeaderControl();
Thread.sleep(500);
app.getNavigationHelper().clickpersonalArchiveEventsPurchasesControl();
String videoNameInCaralog = app.getNavigationHelper().getVideoNamePersonalArchiveEventsCatalog();
Thread.sleep(3000);
app.getNavigationHelper().clicktableArchiveEventsPurchasesFirstRow();
Thread.sleep(3000);
String archiveEventsPurchasesName = app.getNavigationHelper().getTextArchiveEventsPurchasesName();
String expResult = "После нажатия на кнопку у вас будет 24 часа для просмотра фильма";
Assert.assertEquals(archiveEventsPurchasesName, expResult, "Wrong text in lightbox");
app.getNavigationHelper().clickarchiveEventsPurchasesVideo();
//String getvideoNameLightbox = app.getNavigationHelper().getvideoNameLightbox();
// Assert.assertEquals(videoNameInCaralog, getvideoNameLightbox, "Text in table and in lightbox is not equal");
app.getNavigationHelper().clickCloseLightboxButton();
app.getNavigationHelper().openPageForSetPayment();
app.getNavigationHelper().fillFormForUnsetPayment(app, account, productId);
app.getNavigationHelper().clickButtonSetPayment();
app.getNavigationHelper().openMainPage();
// app.getNavigationHelper().clickButtonExit();
// app.getVideoHelper().videoTranslationArchivePlayerIframe(); //ToDo
//app.getNavigationHelper().clickCloseLightbox();
app.getNavigationHelper().clickButtonExit();
}
}
|
package com.s3auth.hosts;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.LinkedList;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.io.IOUtils;
/**
* Default implementation of {@link Resource}.
*
* <p>The class is immutable and thread-safe.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.0.1
*/
final class DefaultResource implements Resource {
/**
* The object to work with.
*/
private final transient S3Object object;
/**
* Public ctor.
* @param obj S3 object
*/
public DefaultResource(final S3Object obj) {
this.object = obj;
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo(final OutputStream output) throws IOException {
final InputStream input = this.object.getObjectContent();
IOUtils.copy(input, output);
input.close();
}
/**
* {@inheritDoc}
*/
@Override
public Collection<String> headers() {
final ObjectMetadata meta = this.object.getObjectMetadata();
final Collection<String> headers = new LinkedList<String>();
headers.add(
DefaultResource.header(
HttpHeaders.CONTENT_LENGTH,
Long.toString(meta.getContentLength())
)
);
headers.add(
DefaultResource.header(
HttpHeaders.CONTENT_TYPE,
meta.getContentType()
)
);
return headers;
}
/**
* Create a HTTP header from name and value.
* @param name Name of the header
* @param value The value
* @return Full HTTP header string
*/
public static String header(final String name, final String value) {
return String.format("%s: %s", name, value);
}
}
|
package org.dhatim.safesql;
import static org.dhatim.safesql.assertion.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class SafeSqlBuilderTest {
private static class MySafeSqlizable implements SafeSqlizable {
private static final String MUST_BE = "SELECT * FROM table WHERE column = ? GROUP BY id";
@Override
public void appendTo(SafeSqlAppendable builder) {
builder.append("SELECT * FROM table WHERE column = ")
.param(5)
.append(" GROUP BY id");
}
}
@Test
public void testAppendConstant() {
assertThat(new SafeSqlBuilder().append("SELECT").append(" * ").append("FROM table").toSafeSql())
.hasSql("SELECT * FROM table")
.hasEmptyParameters();
}
@Test
public void testAppendNumber() {
assertThat(new SafeSqlBuilder().param(5).append(" ").param(1.1).toSafeSql())
.hasSql("? ?")
.hasParameters(5, 1.1);
}
@Test
public void testAppendObject() {
assertThat(new SafeSqlBuilder().param(true).toSafeSql())
.hasSql("?")
.hasParameters(true);
}
@Test
public void testAppendIdentifier() {
assertThat(new SafeSqlBuilder().append("SELECT ").appendIdentifier("S21.G00.32.001").toSafeSql())
.hasSql("SELECT \"S21.G00.32.001\"")
.hasEmptyParameters();
assertThat(new SafeSqlBuilder().append("SELECT ").appendIdentifier("hello").toSafeSql())
.hasSql("SELECT hello")
.hasEmptyParameters();
}
@Test
public void testAppendEscaped() {
assertThat(new SafeSqlBuilder().append("SELECT * FORM table WHERE column = ").param("Hello the world").toSafeSql())
.hasSql("SELECT * FORM table WHERE column = ?")
.hasParameters("Hello the world");
}
@Test
public void testAppendSafeSql() {
assertThat(new SafeSqlBuilder().append("SELECT").append(SafeSqlUtils.fromConstant(" * FROM table")).toSafeSql())
.as("Without parameters")
.hasSql("SELECT * FROM table")
.hasEmptyParameters();
assertThat(new SafeSqlBuilder().append("SELECT ").append(SafeSqlUtils.escape("Hello the world")).toSafeSql())
.as("With parameters")
.hasSql("SELECT ?")
.hasParameters("Hello the world");
}
@Test
public void testAppendSafeSqlizable() {
assertThat(new SafeSqlBuilder().append(new MySafeSqlizable()).append(" ORDER BY name").toSafeSql())
.hasSql(MySafeSqlizable.MUST_BE + " ORDER BY name")
.hasParameters(5);
}
@Test
public void testAppendJoined() {
List<SafeSqlizable> list = Arrays.asList(new MySafeSqlizable(), new MySafeSqlizable());
assertThat(new SafeSqlBuilder().append("(").appendJoinedSqlizable("; ", list).append(")").toSafeSql())
.hasSql("(" + MySafeSqlizable.MUST_BE + "; " + MySafeSqlizable.MUST_BE + ")")
.hasParameters(5, 5);
assertThat(new SafeSqlBuilder().appendJoinedSqlizable(", ", Arrays.asList(new MySafeSqlizable())).toSafeSql())
.hasSql(MySafeSqlizable.MUST_BE)
.hasParameters(5);
assertThat(new SafeSqlBuilder().appendJoined(", ", Arrays.asList()).toSafeSql())
.hasEmptySql()
.hasEmptyParameters();
}
}
|
package edu.cc.oba;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class oneButtons extends Activity {
public static TabHost mTabHost;
final String imageStatus = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.onebutton);
// One Buttons
// List view of all one buttons (Only Name)
// get active requests for the user (For now) and inactive list.
updateListViewActive();
updateListViewInactive();
final ListView listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// Toast.makeText(getBaseContext(),
// ((TextView)v.findViewById(R.id.lngValue)).getText().toString(),4).show();
int req_id = Integer.parseInt(((TextView) v
.findViewById(R.id.imageID)).getText().toString());
String imagename = ((TextView) v.findViewById(R.id.imageName))
.getText().toString();
String status = ((TextView) v.findViewById(R.id.imageStatus))
.getText().toString();
if (status.compareToIgnoreCase("ready") == 0) {
String[] conn_data = TestOBA.oba.getConnectData(req_id);
Toast.makeText(getBaseContext(), conn_data.toString(),
Toast.LENGTH_LONG);
Log.i("COnnDATA", conn_data.toString());
if(isHostRDPReady(conn_data[0]))
StartRdpIntent(conn_data);
else
conn_do_ssh(conn_data, imagename); // On Click of
// Listview, get
// putty/rdp
} else if (status.compareToIgnoreCase("loading") == 0) {
Toast.makeText(getBaseContext(),
"Please wait till your reservation is ready",
Toast.LENGTH_LONG).show();
} else if (status.compareToIgnoreCase("timedout") == 0) {
Toast.makeText(getBaseContext(),
"Your reservation has timed out", Toast.LENGTH_LONG)
.show();
updateListViewActive();
updateListViewInactive(); // at the same time, we need to
// add it into the inactive
// list and update the active list.
}
}
});
final ListView listViewInactive = (ListView) findViewById(R.id.listView_inactive);
listViewInactive.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// Toast.makeText(getBaseContext(),
// ((TextView)v.findViewById(R.id.lngValue)).getText().toString(),4).show();
final int request_id = Integer.parseInt(((TextView) v
.findViewById(R.id.listView_inactive)).getText()
.toString());
AlertDialog adb = new AlertDialog.Builder(getBaseContext()).create();
adb.setCancelable(true);
adb.setButton("ACTIVATE",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
// CODE TO EXTEND RESERVATION
}
});
}
});
mainUITabs.mTabHost
.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
if (tabId.compareTo(("One Buttons")) == 0) {
updateListViewActive();
updateListViewInactive();
}
}
});
// Show user active and inactive one buttons
}
private void updateListViewActive() {
ArrayList<Map<String, String>> list = build(1);
String[] from = { "imagename", "requestid", "status" };
int[] to = { R.id.imageName, R.id.imageID, R.id.imageStatus };
System.out.println(list.toString());
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.row,
from, to);
final ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}
private void updateListViewInactive() {
ArrayList<Map<String, String>> list = build(0);
String[] from = { "imagename", "requestid", "status" };
int[] to = { R.id.imageName, R.id.imageID, R.id.imageStatus };
System.out.println(list.toString());
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.row,
from, to);
final ListView listView = (ListView) findViewById(R.id.listView_inactive);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList<Map<String, String>> build(int act) {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
HashMap requests = TestOBA.oba.getRequestIDs();
Object[] req_id = (Object[]) requests.get("requests");
for (Object object : req_id) {
Map obaImagesHash = (Map) object;
HashMap req_status = TestOBA.oba.getRequestStatus(Integer
.parseInt((String) obaImagesHash.get("requestid")));
obaImagesHash.putAll(req_status);
System.out.println("Adding to array: "
+ obaImagesHash.get("requestid").toString());
if (act == 0){
if (obaImagesHash.get("status").toString().compareToIgnoreCase("timedout") == 0)
list.add(obaImagesHash);
}
else{
if (obaImagesHash.get("status").toString().compareToIgnoreCase("ready") == 0 || obaImagesHash.get("status").toString().compareToIgnoreCase("loading") == 0)
list.add(obaImagesHash);
}
}
return list;
}
/**
* Determine if the host is ready for an RDP connection
* @param ipAddress
* @return
*/
public static boolean isHostRDPReady(String ipAddress){
try {
@SuppressWarnings("unused")
Socket socket = new Socket(ipAddress, 3389);
}catch(Exception e) {
return false;
}
return true;
}
static int i;
public void conn_do_ssh(String[] conn_data_secure, String imagename) {
Toast.makeText(getBaseContext(), "Connecting", Toast.LENGTH_LONG);
i++;
try {
String Conn_URI = "ssh://" + conn_data_secure[1] + "@"
+ conn_data_secure[0] + ":22/#" + imagename;
Log.d("conn_string", Conn_URI);
// Show password in notification bar
Context context = this.getApplicationContext();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = conn_data_secure[2];
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "Password for this reservation is";
CharSequence contentText = conn_data_secure[2];
Intent notificationIntent = new Intent(this, oneButtons.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
// Start Connect BOT
// TODO enclose with try catch and handle catch prompting user to
// install connectBOT
try {
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse(Conn_URI));
startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getBaseContext(), "Please install connectBot",
Toast.LENGTH_LONG).show();
}
notificationManager.notify(1, notification);
// notificationManager.cancelAll();
ConnectWithPass.conn_do(conn_data_secure);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// CODE TO CONNECT RDP:
public static final String REMOTE_SERVER = "server";
public static final String REMOTE_PORT = "port";
public static final String REMOTE_DOMAIN = "domain";
public static final String REMOTE_USER = "user";
public static final String REMOTE_PASSWORD = "password";
public static final String REMOTE_WIDTH = "width";
public static final String REMOTE_HEIGHT = "height";
public static final String REMOTE_OPTIONS = "options";
public static final String REMOTE_PROGRAM = "program";
public static final String REMOTE_COLOR = "color";
public static final String REMOTE_AS_HOST = "as_host"; // the client
// computer name
// option values for REMOTE_OPTIONS
public static final int OPTION_CONSOLE = 0x00000001;// connet to console
// session
public static final int OPTION_CLIPBOARD = 0x00000002;// clipbaord
// copy/paste
public static final int OPTION_SDCARD = 0x00000004; // mount sdcard
public static final int OPTION_SOUND = 0x00000008; // audio playback
public static final int OPTION_LEAVE_SOUND = 0x00000010; // leave sound in
// remote
// computer
public static final int OPTION_BEST_EFFECT = 0x00000020;// best display
// effect
public static final int OPTION_RECORD_AUDIO = 0x00000040;// audio recording
public static String LOG = "RDP_TEST";
public static String walter_rdp_uri = "com.toremote.serversmanager";
public static String HOST = "152.7.99.198";
public static String USER = "asudhak";
public static String PORT = "3389";
public static String PWD = "nkAGCW";
public static String DOMAIN = "";
public void StartRdpIntent(String[] conn_data) {
Log.v(LOG, "sending an intent to walter App");
Intent intent = new Intent(Intent.ACTION_VIEW);
// Uri m_uri = Uri.parse(walter_rdp_uri);
// for enterprise version
// intent.setComponent(new ComponentName("com.toremote.serversmanager",
// "com.toremote.RemoteActivity"));
// for standard version
// intent.setComponent(new ComponentName("org.toremote.serversmanager",
// "com.toremote.RemoteActivity"));
// for lite version
try {
intent.setComponent(new ComponentName("org.toremote.rdpdemo",
"com.toremote.RemoteActivity"));
} catch (ActivityNotFoundException e) {
Toast.makeText(
getBaseContext(),
"Please install REMOTE RDP from the Android Market to be able to remotely connect to this Reservation",
Toast.LENGTH_LONG).show();
}
intent.putExtra(REMOTE_SERVER, conn_data[0]);
intent.putExtra(REMOTE_PORT, PORT);
// following are optional:
intent.putExtra(REMOTE_USER, conn_data[1]);
intent.putExtra(REMOTE_PASSWORD, conn_data[2]);
intent.putExtra(REMOTE_DOMAIN, DOMAIN);
intent.putExtra(REMOTE_WIDTH, "0");// "0" means "fit Device screen"
intent.putExtra(REMOTE_HEIGHT, "0");// "0" means "fit Device screen"
intent.putExtra(REMOTE_COLOR, 16);// 16 bit color
intent.putExtra(REMOTE_OPTIONS, OPTION_CLIPBOARD | OPTION_SOUND
| OPTION_SDCARD | OPTION_RECORD_AUDIO | OPTION_CONSOLE
| OPTION_BEST_EFFECT);
startActivity(intent);
}
// END CODE TO CONNECT RDP:
}
|
package com.ericsson.bash.loc;
import com.ericsson.srcfiles.file.TextFileLineReader;
public final class LocCounter {
public static int countLocInFile(String fileName){
TextFileLineReader reader = new TextFileLineReader(fileName);
return reader.countLines();
}
public static void main(String filenames[]){
int runningTotal = 0;
for(String filename : filenames){
int localTotal = countLocInFile(filename);
System.out.println("Size: " + localTotal + " File: " + filename);
runningTotal += localTotal;
}
System.out.println("Total Size: " + runningTotal );
}
}
|
package org.intermine.bio.web.export;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.intermine.api.results.Column;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.model.bio.LocatedSequenceFeature;
import org.intermine.pathquery.Path;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.export.ExportException;
import org.intermine.web.logic.export.ExportHelper;
import org.intermine.web.logic.export.Exporter;
import org.intermine.web.logic.export.ResponseUtil;
import org.intermine.web.logic.export.http.HttpExportUtil;
import org.intermine.web.logic.export.http.HttpExporterBase;
import org.intermine.web.logic.export.http.TableHttpExporter;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.struts.TableExportForm;
/**
* An implementation of TableHttpExporter that exports LocatedSequenceFeature
* objects in GFF3 format.
*
* @author Kim Rutherford
*/
public class GFF3HttpExporter extends HttpExporterBase implements TableHttpExporter
{
/**
* The batch size to use when we need to iterate through the whole result set.
*/
public static final int BIG_BATCH_SIZE = 10000;
/**
* Method called to export a PagedTable object as GFF3. The PagedTable can only be exported if
* there is exactly one LocatedSequenceFeature column and the other columns (if any), are simple
* attributes (rather than objects).
* {@inheritDoc}
*/
public void export(PagedTable pt, HttpServletRequest request, HttpServletResponse response,
TableExportForm form) {
boolean doGzip = (form != null) && form.getDoGzip();
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
if (doGzip) {
ResponseUtil.setGzippedHeader(response, "table" + StringUtil.uniqueString()
+ ".gff3.gz");
} else {
setGFF3Header(response);
}
List<Integer> indexes = ExportHelper.getClassIndexes(ExportHelper.getColumnClasses(pt),
LocatedSequenceFeature.class);
// get the project title to be written in GFF3 records
Properties props = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES);
String sourceName = props.getProperty("project.title");
Exporter exporter;
try {
OutputStream out = response.getOutputStream();
if (doGzip) {
out = new GZIPOutputStream(out);
}
PrintWriter writer = HttpExportUtil.getPrintWriterForClient(request, out);
List<String> paths = new LinkedList<String>();
if (form != null) {
for (String path : StringUtil.serializedSortOrderToMap(form.getPathsString())
.keySet()) {
paths.add(path.replace(':', '.'));
}
} else {
// if no form provided take the paths from the PagedTable columns
for (Column col : pt.getColumns()) {
paths.add(col.getPath().toStringNoConstraints());
}
}
removeFirstItemInPaths(paths);
exporter = new GFF3Exporter(writer,
indexes, getSoClassNames(servletContext), paths, sourceName);
ExportResultsIterator iter = null;
try {
iter = getResultRows(pt, request);
iter.goFaster();
exporter.export(iter);
if (out instanceof GZIPOutputStream) {
try {
((GZIPOutputStream) out).finish();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} finally {
if (iter != null) {
iter.releaseGoFaster();
}
}
} catch (Exception e) {
throw new ExportException("Export failed", e);
}
if (exporter.getWrittenResultsCount() == 0) {
throw new ExportException("Nothing was found for export");
}
}
private void removeFirstItemInPaths(List<String> paths) {
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
paths.set(i, path.substring(path.indexOf(".") + 1, path.length()));
}
}
private void setGFF3Header(HttpServletResponse response) {
ResponseUtil.setTabHeader(response, "table" + StringUtil.uniqueString() + ".gff3");
}
/**
* The intial export path list is just the paths from the columns of the PagedTable.
* {@inheritDoc}
*/
public List<Path> getInitialExportPaths(PagedTable pt) {
return ExportHelper.getColumnPaths(pt);
}
/**
* Read the SO term name to class name mapping file and return it as a Map from class name to
* SO term name. The Map is cached as the SO_CLASS_NAMES attribute in the servlet context.
* @throws ServletException if the SO class names properties file cannot be found
*/
@SuppressWarnings("unchecked")
private Map<String, String> getSoClassNames(ServletContext servletContext)
throws ServletException {
final String soClassNames = "SO_CLASS_NAMES";
Properties soNameProperties;
if (servletContext.getAttribute(soClassNames) == null) {
soNameProperties = new Properties();
try {
InputStream is =
servletContext.getResourceAsStream("/WEB-INF/soClassName.properties");
soNameProperties.load(is);
} catch (Exception e) {
throw new ServletException("Error loading so class name mapping file", e);
}
servletContext.setAttribute(soClassNames, soNameProperties);
} else {
soNameProperties = (Properties) servletContext.getAttribute(soClassNames);
}
return new HashMap<String, String>((Map) soNameProperties);
}
/**
* {@inheritDoc}
*/
public boolean canExport(PagedTable pt) {
return GFF3Exporter.canExportStatic(ExportHelper.getColumnClasses(pt));
}
/**
* {@inheritDoc}
*/
public List<Path> getExportClassPaths(@SuppressWarnings("unused") PagedTable pt) {
return new ArrayList<Path>();
}
}
|
package fi.utu.ville.exercises;
import java.util.Random;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import fi.utu.ville.exercises.helpers.ExerciseExecutionHelper;
import fi.utu.ville.exercises.model.ExecutionSettings;
import fi.utu.ville.exercises.model.ExecutionState;
import fi.utu.ville.exercises.model.ExecutionStateChangeListener;
import fi.utu.ville.exercises.model.Executor;
import fi.utu.ville.exercises.model.ExerciseException;
import fi.utu.ville.exercises.model.SubmissionListener;
import fi.utu.ville.exercises.model.SubmissionType;
import fi.utu.ville.standardutils.Localizer;
import fi.utu.ville.standardutils.TempFilesManager;
public class BlaxBoxExecutor extends VerticalLayout implements
Executor<BlaxBoxExerciseData, BlaxBoxSubmissionInfo> {
private static final long serialVersionUID = 2682119786422750060L;
private final ExerciseExecutionHelper<BlaxBoxSubmissionInfo> execHelper =
new ExerciseExecutionHelper<BlaxBoxSubmissionInfo>();
private final TextField answerField = new TextField();
private TextField tf3;
private TextField tf4;
private Button b1;
private TextField tf1;
private TextField tf2;
private Label l1;
private Label l2;
private Button b3;
private Button b4;
private Label l3;
private Label l4;
private Label l5;
private TextArea ta;
private VerticalLayout container1;
private VerticalLayout container2;
private HorizontalSplitPanel p;
private int x;
private Random r = new Random();
private int z = r.nextInt(3);
private int[] y = new int[3];
private String s;
public BlaxBoxExecutor() {
}
@Override
public void initialize(Localizer localizer,
BlaxBoxExerciseData exerciseData, BlaxBoxSubmissionInfo oldSubm,
TempFilesManager materials, ExecutionSettings fbSettings)
throws ExerciseException {
answerField.setCaption(localizer.getUIText(BlaxBoxUiConstants.ANSWER));
doLayout(exerciseData, oldSubm != null ? oldSubm.getAnswer() : "");
}
private void doLayout(BlaxBoxExerciseData exerciseData, String oldAnswer) {
answerField.setValue(oldAnswer);
p = new HorizontalSplitPanel();
tf1 = new TextField();
tf2 = new TextField();
ta = new TextArea("Results_list");
ta.setHeight(2, Unit.CM);
l1 = new Label(" -> ");
b1 = new Button("GO!");
l2 = new Label("Get it ? Click the button to continue.");
container1 = new VerticalLayout();
container2 = new VerticalLayout();
b3 = new Button("OK");
b4 = new Button("Previous");
l3 = new Label();
l4 = new Label();
l5 = new Label(" -> ");
tf3 = new TextField();
tf4 = new TextField();
l5 = new Label("->");
s = "";
b1.addClickListener(new Button.ClickListener()
{@Override
public void buttonClick(ClickEvent event) {
x = Integer.parseInt(tf3.getValue());
y[0]=(x+3);
y[1] = 3*x-1;
y[2] = (int)Math.pow(x, 2);
String s2 = y[z]+"";
tf4.setValue(s2);
s= s+x+"->"+s2+"\n";
ta.setValue(s);
}
});
HorizontalLayout h1 = new HorizontalLayout();
HorizontalLayout h2 = new HorizontalLayout();
HorizontalLayout h3 = new HorizontalLayout();
HorizontalLayout h4 = new HorizontalLayout();
h1.addComponent(tf3);
h1.addComponent(l5);
h1.addComponent(tf4);
container1.addComponent(h1);
container1.addComponent(b1);
container1.addComponent(h2);
container1.addComponent(ta);
h2.addComponent(l2);
h3.addComponent(tf1);
h3.addComponent(l1);
h3.addComponent(tf2);
h4.addComponent(b3);
container2.addComponent(h3);
container2.addComponent(h4);
p.setFirstComponent(container1);
p.setSecondComponent(container2);
addComponent(p);
}
@Override
public void registerSubmitListener(
SubmissionListener<BlaxBoxSubmissionInfo> submitListener) {
execHelper.registerSubmitListener(submitListener);
}
@Override
public Layout getView() {
return this;
}
@Override
public void shutdown() {
// nothing to do here
}
@Override
public void askReset() {
// nothing to do here
}
@Override
public ExecutionState getCurrentExecutionState() {
return execHelper.getState();
}
@Override
public void askSubmit(SubmissionType submType) {
double corr = 1.0;
String answer = answerField.getValue();
execHelper.informOnlySubmit(corr, new BlaxBoxSubmissionInfo(answer),
submType, null);
}
@Override
public void registerExecutionStateChangeListener(
ExecutionStateChangeListener execStateListener) {
execHelper.registerExerciseExecutionStateListener(execStateListener);
}
}
|
package io.druid.segment;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.common.io.OutputSupplier;
import com.google.common.primitives.Ints;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.metamx.collections.bitmap.BitmapFactory;
import com.metamx.collections.bitmap.ImmutableBitmap;
import com.metamx.collections.bitmap.MutableBitmap;
import com.metamx.collections.spatial.ImmutableRTree;
import com.metamx.collections.spatial.RTree;
import com.metamx.collections.spatial.split.LinearGutmanSplitStrategy;
import com.metamx.common.IAE;
import com.metamx.common.ISE;
import com.metamx.common.guava.CloseQuietly;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.guava.MergeIterable;
import com.metamx.common.guava.nary.BinaryFn;
import com.metamx.common.io.smoosh.Smoosh;
import com.metamx.common.logger.Logger;
import io.druid.collections.CombiningIterable;
import io.druid.common.guava.FileOutputSupplier;
import io.druid.common.guava.GuavaUtils;
import io.druid.common.utils.JodaUtils;
import io.druid.common.utils.SerializerUtils;
import io.druid.guice.GuiceInjectors;
import io.druid.guice.JsonConfigProvider;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.ToLowerCaseAggregatorFactory;
import io.druid.segment.column.ColumnCapabilities;
import io.druid.segment.column.ColumnCapabilitiesImpl;
import io.druid.segment.column.ValueType;
import io.druid.segment.data.BitmapSerdeFactory;
import io.druid.segment.data.ByteBufferWriter;
import io.druid.segment.data.CompressedLongsSupplierSerializer;
import io.druid.segment.data.CompressedObjectStrategy;
import io.druid.segment.data.GenericIndexed;
import io.druid.segment.data.GenericIndexedWriter;
import io.druid.segment.data.IOPeon;
import io.druid.segment.data.Indexed;
import io.druid.segment.data.IndexedInts;
import io.druid.segment.data.IndexedIterable;
import io.druid.segment.data.IndexedRTree;
import io.druid.segment.data.TmpFileIOPeon;
import io.druid.segment.data.VSizeIndexedWriter;
import io.druid.segment.incremental.IncrementalIndex;
import io.druid.segment.incremental.IncrementalIndexAdapter;
import io.druid.segment.serde.ComplexMetricColumnSerializer;
import io.druid.segment.serde.ComplexMetricSerde;
import io.druid.segment.serde.ComplexMetrics;
import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class IndexMerger
{
private static final Logger log = new Logger(IndexMerger.class);
private static final SerializerUtils serializerUtils = new SerializerUtils();
private static final int INVALID_ROW = -1;
private static final Splitter SPLITTER = Splitter.on(",");
private static final ObjectMapper mapper;
private static final BitmapSerdeFactory bitmapSerdeFactory;
static {
final Injector injector = GuiceInjectors.makeStartupInjectorWithModules(
ImmutableList.<Module>of(
new Module()
{
@Override
public void configure(Binder binder)
{
JsonConfigProvider.bind(binder, "druid.processing.bitmap", BitmapSerdeFactory.class);
}
}
)
);
mapper = injector.getInstance(ObjectMapper.class);
bitmapSerdeFactory = injector.getInstance(BitmapSerdeFactory.class);
}
public static File persist(final IncrementalIndex index, File outDir) throws IOException
{
return persist(index, index.getInterval(), outDir);
}
/**
* This is *not* thread-safe and havok will ensue if this is called and writes are still occurring
* on the IncrementalIndex object.
*
* @param index the IncrementalIndex to persist
* @param dataInterval the Interval that the data represents
* @param outDir the directory to persist the data to
*
* @return the index output directory
*
* @throws java.io.IOException if an IO error occurs persisting the index
*/
public static File persist(final IncrementalIndex index, final Interval dataInterval, File outDir) throws IOException
{
return persist(index, dataInterval, outDir, new BaseProgressIndicator());
}
public static File persist(
final IncrementalIndex index, final Interval dataInterval, File outDir, ProgressIndicator progress
) throws IOException
{
if (index.isEmpty()) {
throw new IAE("Trying to persist an empty index!");
}
final long firstTimestamp = index.getMinTime().getMillis();
final long lastTimestamp = index.getMaxTime().getMillis();
if (!(dataInterval.contains(firstTimestamp) && dataInterval.contains(lastTimestamp))) {
throw new IAE(
"interval[%s] does not encapsulate the full range of timestamps[%s, %s]",
dataInterval,
new DateTime(firstTimestamp),
new DateTime(lastTimestamp)
);
}
if (!outDir.exists()) {
outDir.mkdirs();
}
if (!outDir.isDirectory()) {
throw new ISE("Can only persist to directories, [%s] wasn't a directory", outDir);
}
log.info("Starting persist for interval[%s], rows[%,d]", dataInterval, index.size());
return merge(
Arrays.<IndexableAdapter>asList(
new IncrementalIndexAdapter(
dataInterval,
index,
bitmapSerdeFactory.getBitmapFactory()
)
),
index.getMetricAggs(),
outDir,
progress
);
}
public static File mergeQueryableIndex(
List<QueryableIndex> indexes, final AggregatorFactory[] metricAggs, File outDir
) throws IOException
{
return mergeQueryableIndex(indexes, metricAggs, outDir, new BaseProgressIndicator());
}
public static File mergeQueryableIndex(
List<QueryableIndex> indexes, final AggregatorFactory[] metricAggs, File outDir, ProgressIndicator progress
) throws IOException
{
return merge(
Lists.transform(
indexes,
new Function<QueryableIndex, IndexableAdapter>()
{
@Override
public IndexableAdapter apply(final QueryableIndex input)
{
return new QueryableIndexIndexableAdapter(input);
}
}
),
metricAggs,
outDir,
progress
);
}
public static File merge(
List<IndexableAdapter> indexes, final AggregatorFactory[] metricAggs, File outDir
) throws IOException
{
return merge(indexes, metricAggs, outDir, new BaseProgressIndicator());
}
public static File merge(
List<IndexableAdapter> indexes, final AggregatorFactory[] metricAggs, File outDir, ProgressIndicator progress
) throws IOException
{
FileUtils.deleteDirectory(outDir);
if (!outDir.mkdirs()) {
throw new ISE("Couldn't make outdir[%s].", outDir);
}
final AggregatorFactory[] lowerCaseMetricAggs = new AggregatorFactory[metricAggs.length];
for (int i = 0; i < metricAggs.length; i++) {
lowerCaseMetricAggs[i] = new ToLowerCaseAggregatorFactory(metricAggs[i]);
}
final List<String> mergedDimensions = mergeIndexed(
Lists.transform(
indexes,
new Function<IndexableAdapter, Iterable<String>>()
{
@Override
public Iterable<String> apply(@Nullable IndexableAdapter input)
{
return Iterables.transform(
input.getDimensionNames(),
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return input.toLowerCase();
}
}
);
}
}
)
);
final List<String> mergedMetrics = Lists.transform(
mergeIndexed(
Lists.<Iterable<String>>newArrayList(
FunctionalIterable
.create(indexes)
.transform(
new Function<IndexableAdapter, Iterable<String>>()
{
@Override
public Iterable<String> apply(@Nullable IndexableAdapter input)
{
return Iterables.transform(
input.getMetricNames(),
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return input.toLowerCase();
}
}
);
}
}
)
.concat(Arrays.<Iterable<String>>asList(new AggFactoryStringIndexed(lowerCaseMetricAggs)))
)
),
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return input.toLowerCase();
}
}
);
if (mergedMetrics.size() != lowerCaseMetricAggs.length) {
throw new IAE("Bad number of metrics[%d], expected [%d]", mergedMetrics.size(), lowerCaseMetricAggs.length);
}
final AggregatorFactory[] sortedMetricAggs = new AggregatorFactory[mergedMetrics.size()];
for (int i = 0; i < lowerCaseMetricAggs.length; i++) {
AggregatorFactory metricAgg = lowerCaseMetricAggs[i];
sortedMetricAggs[mergedMetrics.indexOf(metricAgg.getName())] = metricAgg;
}
for (int i = 0; i < mergedMetrics.size(); i++) {
if (!sortedMetricAggs[i].getName().equals(mergedMetrics.get(i))) {
throw new IAE(
"Metric mismatch, index[%d] [%s] != [%s]",
i,
lowerCaseMetricAggs[i].getName(),
mergedMetrics.get(i)
);
}
}
Function<ArrayList<Iterable<Rowboat>>, Iterable<Rowboat>> rowMergerFn = new Function<ArrayList<Iterable<Rowboat>>, Iterable<Rowboat>>()
{
@Override
public Iterable<Rowboat> apply(
@Nullable ArrayList<Iterable<Rowboat>> boats
)
{
return CombiningIterable.create(
new MergeIterable<Rowboat>(
Ordering.<Rowboat>natural().nullsFirst(),
boats
),
Ordering.<Rowboat>natural().nullsFirst(),
new RowboatMergeFunction(sortedMetricAggs)
);
}
};
return makeIndexFiles(indexes, outDir, progress, mergedDimensions, mergedMetrics, rowMergerFn);
}
public static File append(
List<IndexableAdapter> indexes, File outDir
) throws IOException
{
return append(indexes, outDir, new BaseProgressIndicator());
}
public static File append(
List<IndexableAdapter> indexes, File outDir, ProgressIndicator progress
) throws IOException
{
FileUtils.deleteDirectory(outDir);
if (!outDir.mkdirs()) {
throw new ISE("Couldn't make outdir[%s].", outDir);
}
final List<String> mergedDimensions = mergeIndexed(
Lists.transform(
indexes,
new Function<IndexableAdapter, Iterable<String>>()
{
@Override
public Iterable<String> apply(@Nullable IndexableAdapter input)
{
return Iterables.transform(
input.getDimensionNames(),
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return input.toLowerCase();
}
}
);
}
}
)
);
final List<String> mergedMetrics = mergeIndexed(
Lists.transform(
indexes,
new Function<IndexableAdapter, Iterable<String>>()
{
@Override
public Iterable<String> apply(@Nullable IndexableAdapter input)
{
return Iterables.transform(
input.getMetricNames(),
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return input.toLowerCase();
}
}
);
}
}
)
);
Function<ArrayList<Iterable<Rowboat>>, Iterable<Rowboat>> rowMergerFn = new Function<ArrayList<Iterable<Rowboat>>, Iterable<Rowboat>>()
{
@Override
public Iterable<Rowboat> apply(
@Nullable final ArrayList<Iterable<Rowboat>> boats
)
{
return new MergeIterable<Rowboat>(
Ordering.<Rowboat>natural().nullsFirst(),
boats
);
}
};
return makeIndexFiles(indexes, outDir, progress, mergedDimensions, mergedMetrics, rowMergerFn);
}
private static File makeIndexFiles(
final List<IndexableAdapter> indexes,
final File outDir,
final ProgressIndicator progress,
final List<String> mergedDimensions,
final List<String> mergedMetrics,
final Function<ArrayList<Iterable<Rowboat>>, Iterable<Rowboat>> rowMergerFn
) throws IOException
{
final Map<String, ValueType> valueTypes = Maps.newTreeMap(Ordering.<String>natural().nullsFirst());
final Map<String, String> metricTypeNames = Maps.newTreeMap(Ordering.<String>natural().nullsFirst());
final Map<String, ColumnCapabilitiesImpl> columnCapabilities = Maps.newHashMap();
for (IndexableAdapter adapter : indexes) {
for (String dimension : adapter.getDimensionNames()) {
ColumnCapabilitiesImpl mergedCapabilities = columnCapabilities.get(dimension);
ColumnCapabilities capabilities = adapter.getCapabilities(dimension);
if (mergedCapabilities == null) {
mergedCapabilities = new ColumnCapabilitiesImpl();
mergedCapabilities.setType(ValueType.STRING);
}
columnCapabilities.put(dimension, mergedCapabilities.merge(capabilities));
}
for (String metric : adapter.getMetricNames()) {
ColumnCapabilitiesImpl mergedCapabilities = columnCapabilities.get(metric);
ColumnCapabilities capabilities = adapter.getCapabilities(metric);
if (mergedCapabilities == null) {
mergedCapabilities = new ColumnCapabilitiesImpl();
}
columnCapabilities.put(metric, mergedCapabilities.merge(capabilities));
valueTypes.put(metric, capabilities.getType());
metricTypeNames.put(metric, adapter.getMetricType(metric));
}
}
final Interval dataInterval;
File v8OutDir = new File(outDir, "v8-tmp");
v8OutDir.mkdirs();
progress.progress();
long startTime = System.currentTimeMillis();
File indexFile = new File(v8OutDir, "index.drd");
FileOutputStream fileOutputStream = null;
FileChannel channel = null;
try {
fileOutputStream = new FileOutputStream(indexFile);
channel = fileOutputStream.getChannel();
channel.write(ByteBuffer.wrap(new byte[]{IndexIO.V8_VERSION}));
GenericIndexed.fromIterable(mergedDimensions, GenericIndexed.stringStrategy).writeToChannel(channel);
GenericIndexed.fromIterable(mergedMetrics, GenericIndexed.stringStrategy).writeToChannel(channel);
DateTime minTime = new DateTime(Long.MAX_VALUE);
DateTime maxTime = new DateTime(0l);
for (IndexableAdapter index : indexes) {
minTime = JodaUtils.minDateTime(minTime, index.getDataInterval().getStart());
maxTime = JodaUtils.maxDateTime(maxTime, index.getDataInterval().getEnd());
}
dataInterval = new Interval(minTime, maxTime);
serializerUtils.writeString(channel, String.format("%s/%s", minTime, maxTime));
serializerUtils.writeString(channel, mapper.writeValueAsString(bitmapSerdeFactory));
}
finally {
CloseQuietly.close(channel);
channel = null;
CloseQuietly.close(fileOutputStream);
fileOutputStream = null;
}
IndexIO.checkFileSize(indexFile);
log.info("outDir[%s] completed index.drd in %,d millis.", v8OutDir, System.currentTimeMillis() - startTime);
progress.progress();
startTime = System.currentTimeMillis();
IOPeon ioPeon = new TmpFileIOPeon();
ArrayList<FileOutputSupplier> dimOuts = Lists.newArrayListWithCapacity(mergedDimensions.size());
Map<String, Integer> dimensionCardinalities = Maps.newHashMap();
ArrayList<Map<String, IntBuffer>> dimConversions = Lists.newArrayListWithCapacity(indexes.size());
for (IndexableAdapter index : indexes) {
dimConversions.add(Maps.<String, IntBuffer>newHashMap());
}
for (String dimension : mergedDimensions) {
final GenericIndexedWriter<String> writer = new GenericIndexedWriter<String>(
ioPeon, dimension, GenericIndexed.stringStrategy
);
writer.open();
List<Indexed<String>> dimValueLookups = Lists.newArrayListWithCapacity(indexes.size());
DimValueConverter[] converters = new DimValueConverter[indexes.size()];
for (int i = 0; i < indexes.size(); i++) {
Indexed<String> dimValues = indexes.get(i).getDimValueLookup(dimension);
if (dimValues != null) {
dimValueLookups.add(dimValues);
converters[i] = new DimValueConverter(dimValues);
}
}
Iterable<String> dimensionValues = CombiningIterable.createSplatted(
Iterables.transform(
dimValueLookups,
new Function<Indexed<String>, Iterable<String>>()
{
@Override
public Iterable<String> apply(@Nullable Indexed<String> indexed)
{
return Iterables.transform(
indexed,
new Function<String, String>()
{
@Override
public String apply(@Nullable String input)
{
return (input == null) ? "" : input;
}
}
);
}
}
)
,
Ordering.<String>natural().nullsFirst()
);
int count = 0;
for (String value : dimensionValues) {
value = value == null ? "" : value;
writer.write(value);
for (int i = 0; i < indexes.size(); i++) {
DimValueConverter converter = converters[i];
if (converter != null) {
converter.convert(value, count);
}
}
++count;
}
dimensionCardinalities.put(dimension, count);
FileOutputSupplier dimOut = new FileOutputSupplier(IndexIO.makeDimFile(v8OutDir, dimension), true);
dimOuts.add(dimOut);
writer.close();
serializerUtils.writeString(dimOut, dimension);
ByteStreams.copy(writer.combineStreams(), dimOut);
for (int i = 0; i < indexes.size(); ++i) {
DimValueConverter converter = converters[i];
if (converter != null) {
dimConversions.get(i).put(dimension, converters[i].getConversionBuffer());
}
}
ioPeon.cleanup();
}
log.info("outDir[%s] completed dim conversions in %,d millis.", v8OutDir, System.currentTimeMillis() - startTime);
progress.progress();
startTime = System.currentTimeMillis();
ArrayList<Iterable<Rowboat>> boats = Lists.newArrayListWithCapacity(indexes.size());
for (int i = 0; i < indexes.size(); ++i) {
final IndexableAdapter adapter = indexes.get(i);
final int[] dimLookup = new int[mergedDimensions.size()];
int count = 0;
for (String dim : adapter.getDimensionNames()) {
dimLookup[count] = mergedDimensions.indexOf(dim.toLowerCase());
count++;
}
final int[] metricLookup = new int[mergedMetrics.size()];
count = 0;
for (String metric : adapter.getMetricNames()) {
metricLookup[count] = mergedMetrics.indexOf(metric);
count++;
}
boats.add(
new MMappedIndexRowIterable(
Iterables.transform(
indexes.get(i).getRows(),
new Function<Rowboat, Rowboat>()
{
@Override
public Rowboat apply(@Nullable Rowboat input)
{
int[][] newDims = new int[mergedDimensions.size()][];
int j = 0;
for (int[] dim : input.getDims()) {
newDims[dimLookup[j]] = dim;
j++;
}
Object[] newMetrics = new Object[mergedMetrics.size()];
j = 0;
for (Object met : input.getMetrics()) {
newMetrics[metricLookup[j]] = met;
j++;
}
return new Rowboat(
input.getTimestamp(),
newDims,
newMetrics,
input.getRowNum()
);
}
}
)
, mergedDimensions, dimConversions.get(i), i
)
);
}
Iterable<Rowboat> theRows = rowMergerFn.apply(boats);
CompressedLongsSupplierSerializer timeWriter = CompressedLongsSupplierSerializer.create(
ioPeon, "little_end_time", IndexIO.BYTE_ORDER, CompressedObjectStrategy.DEFAULT_COMPRESSION_STRATEGY
);
timeWriter.open();
ArrayList<VSizeIndexedWriter> forwardDimWriters = Lists.newArrayListWithCapacity(mergedDimensions.size());
for (String dimension : mergedDimensions) {
VSizeIndexedWriter writer = new VSizeIndexedWriter(ioPeon, dimension, dimensionCardinalities.get(dimension));
writer.open();
forwardDimWriters.add(writer);
}
ArrayList<MetricColumnSerializer> metWriters = Lists.newArrayListWithCapacity(mergedMetrics.size());
for (String metric : mergedMetrics) {
ValueType type = valueTypes.get(metric);
switch (type) {
case LONG:
metWriters.add(new LongMetricColumnSerializer(metric, v8OutDir, ioPeon));
break;
case FLOAT:
metWriters.add(new FloatMetricColumnSerializer(metric, v8OutDir, ioPeon));
break;
case COMPLEX:
final String typeName = metricTypeNames.get(metric);
ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(typeName);
if (serde == null) {
throw new ISE("Unknown type[%s]", typeName);
}
metWriters.add(new ComplexMetricColumnSerializer(metric, v8OutDir, ioPeon, serde));
break;
default:
throw new ISE("Unknown type[%s]", type);
}
}
for (MetricColumnSerializer metWriter : metWriters) {
metWriter.open();
}
int rowCount = 0;
long time = System.currentTimeMillis();
List<IntBuffer> rowNumConversions = Lists.newArrayListWithCapacity(indexes.size());
for (IndexableAdapter index : indexes) {
int[] arr = new int[index.getNumRows()];
Arrays.fill(arr, INVALID_ROW);
rowNumConversions.add(IntBuffer.wrap(arr));
}
for (Rowboat theRow : theRows) {
progress.progress();
timeWriter.add(theRow.getTimestamp());
final Object[] metrics = theRow.getMetrics();
for (int i = 0; i < metrics.length; ++i) {
metWriters.get(i).serialize(metrics[i]);
}
int[][] dims = theRow.getDims();
for (int i = 0; i < dims.length; ++i) {
List<Integer> listToWrite = (i >= dims.length || dims[i] == null)
? null
: Ints.asList(dims[i]);
forwardDimWriters.get(i).write(listToWrite);
}
for (Map.Entry<Integer, TreeSet<Integer>> comprisedRow : theRow.getComprisedRows().entrySet()) {
final IntBuffer conversionBuffer = rowNumConversions.get(comprisedRow.getKey());
for (Integer rowNum : comprisedRow.getValue()) {
while (conversionBuffer.position() < rowNum) {
conversionBuffer.put(INVALID_ROW);
}
conversionBuffer.put(rowCount);
}
}
if ((++rowCount % 500000) == 0) {
log.info(
"outDir[%s] walked 500,000/%,d rows in %,d millis.", v8OutDir, rowCount, System.currentTimeMillis() - time
);
time = System.currentTimeMillis();
}
}
for (IntBuffer rowNumConversion : rowNumConversions) {
rowNumConversion.rewind();
}
final File timeFile = IndexIO.makeTimeFile(v8OutDir, IndexIO.BYTE_ORDER);
timeFile.delete();
OutputSupplier<FileOutputStream> out = Files.newOutputStreamSupplier(timeFile, true);
timeWriter.closeAndConsolidate(out);
IndexIO.checkFileSize(timeFile);
for (int i = 0; i < mergedDimensions.size(); ++i) {
forwardDimWriters.get(i).close();
ByteStreams.copy(forwardDimWriters.get(i).combineStreams(), dimOuts.get(i));
}
for (MetricColumnSerializer metWriter : metWriters) {
metWriter.close();
}
ioPeon.cleanup();
log.info(
"outDir[%s] completed walk through of %,d rows in %,d millis.",
v8OutDir,
rowCount,
System.currentTimeMillis() - startTime
);
startTime = System.currentTimeMillis();
final File invertedFile = new File(v8OutDir, "inverted.drd");
Files.touch(invertedFile);
out = Files.newOutputStreamSupplier(invertedFile, true);
final File geoFile = new File(v8OutDir, "spatial.drd");
Files.touch(geoFile);
OutputSupplier<FileOutputStream> spatialOut = Files.newOutputStreamSupplier(geoFile, true);
for (int i = 0; i < mergedDimensions.size(); ++i) {
long dimStartTime = System.currentTimeMillis();
String dimension = mergedDimensions.get(i);
File dimOutFile = dimOuts.get(i).getFile();
final MappedByteBuffer dimValsMapped = Files.map(dimOutFile);
if (!dimension.equals(serializerUtils.readString(dimValsMapped))) {
throw new ISE("dimensions[%s] didn't equate!? This is a major WTF moment.", dimension);
}
Indexed<String> dimVals = GenericIndexed.read(dimValsMapped, GenericIndexed.stringStrategy);
log.info("Starting dimension[%s] with cardinality[%,d]", dimension, dimVals.size());
GenericIndexedWriter<ImmutableBitmap> writer = new GenericIndexedWriter<>(
ioPeon, dimension, bitmapSerdeFactory.getObjectStrategy()
);
writer.open();
boolean isSpatialDim = columnCapabilities.get(dimension).hasSpatialIndexes();
ByteBufferWriter<ImmutableRTree> spatialWriter = null;
RTree tree = null;
IOPeon spatialIoPeon = new TmpFileIOPeon();
if (isSpatialDim) {
BitmapFactory bitmapFactory = bitmapSerdeFactory.getBitmapFactory();
spatialWriter = new ByteBufferWriter<ImmutableRTree>(
spatialIoPeon, dimension, new IndexedRTree.ImmutableRTreeObjectStrategy(bitmapFactory)
);
spatialWriter.open();
tree = new RTree(2, new LinearGutmanSplitStrategy(0, 50, bitmapFactory), bitmapFactory);
}
for (String dimVal : IndexedIterable.create(dimVals)) {
progress.progress();
List<Iterable<Integer>> convertedInverteds = Lists.newArrayListWithCapacity(indexes.size());
for (int j = 0; j < indexes.size(); ++j) {
convertedInverteds.add(
new ConvertingIndexedInts(
indexes.get(j).getBitmapIndex(dimension, dimVal), rowNumConversions.get(j)
)
);
}
MutableBitmap bitset = bitmapSerdeFactory.getBitmapFactory().makeEmptyMutableBitmap();
for (Integer row : CombiningIterable.createSplatted(
convertedInverteds,
Ordering.<Integer>natural().nullsFirst()
)) {
if (row != INVALID_ROW) {
bitset.add(row);
}
}
writer.write(
bitmapSerdeFactory.getBitmapFactory().makeImmutableBitmap(bitset)
);
if (isSpatialDim && dimVal != null) {
List<String> stringCoords = Lists.newArrayList(SPLITTER.split(dimVal));
float[] coords = new float[stringCoords.size()];
for (int j = 0; j < coords.length; j++) {
coords[j] = Float.valueOf(stringCoords.get(j));
}
tree.insert(coords, bitset);
}
}
writer.close();
serializerUtils.writeString(out, dimension);
ByteStreams.copy(writer.combineStreams(), out);
ioPeon.cleanup();
log.info("Completed dimension[%s] in %,d millis.", dimension, System.currentTimeMillis() - dimStartTime);
if (isSpatialDim) {
spatialWriter.write(ImmutableRTree.newImmutableFromMutable(tree));
spatialWriter.close();
serializerUtils.writeString(spatialOut, dimension);
ByteStreams.copy(spatialWriter.combineStreams(), spatialOut);
spatialIoPeon.cleanup();
}
}
log.info("outDir[%s] completed inverted.drd in %,d millis.", v8OutDir, System.currentTimeMillis() - startTime);
final ArrayList<String> expectedFiles = Lists.newArrayList(
Iterables.concat(
Arrays.asList(
"index.drd", "inverted.drd", "spatial.drd", String.format("time_%s.drd", IndexIO.BYTE_ORDER)
),
Iterables.transform(mergedDimensions, GuavaUtils.formatFunction("dim_%s.drd")),
Iterables.transform(
mergedMetrics, GuavaUtils.formatFunction(String.format("met_%%s_%s.drd", IndexIO.BYTE_ORDER))
)
)
);
Map<String, File> files = Maps.newLinkedHashMap();
for (String fileName : expectedFiles) {
files.put(fileName, new File(v8OutDir, fileName));
}
File smooshDir = new File(v8OutDir, "smoosher");
smooshDir.mkdir();
for (Map.Entry<String, File> entry : Smoosh.smoosh(v8OutDir, smooshDir, files).entrySet()) {
entry.getValue().delete();
}
for (File file : smooshDir.listFiles()) {
Files.move(file, new File(v8OutDir, file.getName()));
}
if (!smooshDir.delete()) {
log.info("Unable to delete temporary dir[%s], contains[%s]", smooshDir, Arrays.asList(smooshDir.listFiles()));
throw new IOException(String.format("Unable to delete temporary dir[%s]", smooshDir));
}
createIndexDrdFile(
IndexIO.V8_VERSION,
v8OutDir,
GenericIndexed.fromIterable(mergedDimensions, GenericIndexed.stringStrategy),
GenericIndexed.fromIterable(mergedMetrics, GenericIndexed.stringStrategy),
dataInterval
);
IndexIO.DefaultIndexIOHandler.convertV8toV9(v8OutDir, outDir);
FileUtils.deleteDirectory(v8OutDir);
return outDir;
}
private static <T extends Comparable> ArrayList<T> mergeIndexed(final List<Iterable<T>> indexedLists)
{
Set<T> retVal = Sets.newTreeSet(Ordering.<T>natural().nullsFirst());
for (Iterable<T> indexedList : indexedLists) {
for (T val : indexedList) {
retVal.add(val);
}
}
return Lists.newArrayList(retVal);
}
public static void createIndexDrdFile(
byte versionId,
File inDir,
GenericIndexed<String> availableDimensions,
GenericIndexed<String> availableMetrics,
Interval dataInterval
) throws IOException
{
File indexFile = new File(inDir, "index.drd");
FileChannel channel = null;
try {
channel = new FileOutputStream(indexFile).getChannel();
channel.write(ByteBuffer.wrap(new byte[]{versionId}));
availableDimensions.writeToChannel(channel);
availableMetrics.writeToChannel(channel);
serializerUtils.writeString(
channel, String.format("%s/%s", dataInterval.getStart(), dataInterval.getEnd())
);
serializerUtils.writeString(
channel, mapper.writeValueAsString(bitmapSerdeFactory)
);
}
finally {
CloseQuietly.close(channel);
channel = null;
}
IndexIO.checkFileSize(indexFile);
}
private static class DimValueConverter
{
private final Indexed<String> dimSet;
private final IntBuffer conversionBuf;
private int currIndex;
private String lastVal = null;
DimValueConverter(
Indexed<String> dimSet
)
{
this.dimSet = dimSet;
conversionBuf = ByteBuffer.allocateDirect(dimSet.size() * Ints.BYTES).asIntBuffer();
currIndex = 0;
}
public void convert(String value, int index)
{
if (dimSet.size() == 0) {
return;
}
if (lastVal != null) {
if (value.compareTo(lastVal) <= 0) {
throw new ISE("Value[%s] is less than the last value[%s] I have, cannot be.", value, lastVal);
}
return;
}
String currValue = dimSet.get(currIndex);
while (currValue == null) {
conversionBuf.position(conversionBuf.position() + 1);
++currIndex;
if (currIndex == dimSet.size()) {
lastVal = value;
return;
}
currValue = dimSet.get(currIndex);
}
if (Objects.equal(currValue, value)) {
conversionBuf.put(index);
++currIndex;
if (currIndex == dimSet.size()) {
lastVal = value;
}
} else if (currValue.compareTo(value) < 0) {
throw new ISE(
"Skipped currValue[%s], currIndex[%,d]; incoming value[%s], index[%,d]", currValue, currIndex, value, index
);
}
}
public IntBuffer getConversionBuffer()
{
if (currIndex != conversionBuf.limit() || conversionBuf.hasRemaining()) {
throw new ISE(
"Asked for incomplete buffer. currIndex[%,d] != buf.limit[%,d]", currIndex, conversionBuf.limit()
);
}
return (IntBuffer) conversionBuf.asReadOnlyBuffer().rewind();
}
}
private static class ConvertingIndexedInts implements Iterable<Integer>
{
private final IndexedInts baseIndex;
private final IntBuffer conversionBuffer;
public ConvertingIndexedInts(
IndexedInts baseIndex,
IntBuffer conversionBuffer
)
{
this.baseIndex = baseIndex;
this.conversionBuffer = conversionBuffer;
}
public int size()
{
return baseIndex.size();
}
public int get(int index)
{
return conversionBuffer.get(baseIndex.get(index));
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.transform(
baseIndex.iterator(),
new Function<Integer, Integer>()
{
@Override
public Integer apply(@Nullable Integer input)
{
return conversionBuffer.get(input);
}
}
);
}
}
private static class MMappedIndexRowIterable implements Iterable<Rowboat>
{
private final Iterable<Rowboat> index;
private final List<String> convertedDims;
private final Map<String, IntBuffer> converters;
private final int indexNumber;
MMappedIndexRowIterable(
Iterable<Rowboat> index,
List<String> convertedDims,
Map<String, IntBuffer> converters,
int indexNumber
)
{
this.index = index;
this.convertedDims = convertedDims;
this.converters = converters;
this.indexNumber = indexNumber;
}
public Iterable<Rowboat> getIndex()
{
return index;
}
public List<String> getConvertedDims()
{
return convertedDims;
}
public Map<String, IntBuffer> getConverters()
{
return converters;
}
public int getIndexNumber()
{
return indexNumber;
}
@Override
public Iterator<Rowboat> iterator()
{
return Iterators.transform(
index.iterator(),
new Function<Rowboat, Rowboat>()
{
int rowCount = 0;
@Override
public Rowboat apply(@Nullable Rowboat input)
{
int[][] dims = input.getDims();
int[][] newDims = new int[convertedDims.size()][];
for (int i = 0; i < convertedDims.size(); ++i) {
IntBuffer converter = converters.get(convertedDims.get(i));
if (converter == null) {
continue;
}
if (i >= dims.length || dims[i] == null) {
continue;
}
newDims[i] = new int[dims[i].length];
for (int j = 0; j < dims[i].length; ++j) {
if (!converter.hasRemaining()) {
log.error("Converter mismatch! wtfbbq!");
}
newDims[i][j] = converter.get(dims[i][j]);
}
}
final Rowboat retVal = new Rowboat(
input.getTimestamp(),
newDims,
input.getMetrics(),
input.getRowNum()
);
retVal.addRow(indexNumber, input.getRowNum());
return retVal;
}
}
);
}
}
private static class AggFactoryStringIndexed implements Indexed<String>
{
private final AggregatorFactory[] metricAggs;
public AggFactoryStringIndexed(AggregatorFactory[] metricAggs) {this.metricAggs = metricAggs;}
@Override
public Class<? extends String> getClazz()
{
return String.class;
}
@Override
public int size()
{
return metricAggs.length;
}
@Override
public String get(int index)
{
return metricAggs[index].getName();
}
@Override
public int indexOf(String value)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator()
{
return IndexedIterable.create(this).iterator();
}
}
private static class RowboatMergeFunction implements BinaryFn<Rowboat, Rowboat, Rowboat>
{
private final AggregatorFactory[] metricAggs;
public RowboatMergeFunction(AggregatorFactory[] metricAggs)
{
this.metricAggs = metricAggs;
}
@Override
public Rowboat apply(Rowboat lhs, Rowboat rhs)
{
if (lhs == null) {
return rhs;
}
if (rhs == null) {
return lhs;
}
Object[] metrics = new Object[metricAggs.length];
Object[] lhsMetrics = lhs.getMetrics();
Object[] rhsMetrics = rhs.getMetrics();
for (int i = 0; i < metrics.length; ++i) {
metrics[i] = metricAggs[i].combine(lhsMetrics[i], rhsMetrics[i]);
}
final Rowboat retVal = new Rowboat(
lhs.getTimestamp(),
lhs.getDims(),
metrics,
lhs.getRowNum()
);
for (Rowboat rowboat : Arrays.asList(lhs, rhs)) {
for (Map.Entry<Integer, TreeSet<Integer>> entry : rowboat.getComprisedRows().entrySet()) {
for (Integer rowNum : entry.getValue()) {
retVal.addRow(entry.getKey(), rowNum);
}
}
}
return retVal;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.