lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | error: pathspec 'src/main/java/no/westerdals/dbpedia_idx/Triple.java' did not match any file(s) known to git
| 84c3692be17ffbaafcb0eff212dbbf7a23e6ce17 | 1 | naimdjon/dbpedia-idx | package no.westerdals.dbpedia_idx;
public final class Triple {
public final String subject, predicate, object;
public Triple(String subject, String predicate, String object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
}
}
| src/main/java/no/westerdals/dbpedia_idx/Triple.java | triple object.
| src/main/java/no/westerdals/dbpedia_idx/Triple.java | triple object. |
|
Java | mit | error: pathspec 'src/org/usfirst/frc/team1699/robot/commands/Pickup.java' did not match any file(s) known to git
| e2da3feefb3a63f8fe3b9dc1224b9bda3d7b0bd2 | 1 | FIRST-Team-1699/2017-code | package org.usfirst.frc.team1699.robot.commands;
import org.usfirst.frc.team1699.utils.command.Command;
import org.usfirst.frc.team1699.utils.drive.XboxController;
import edu.wpi.first.wpilibj.SpeedController;
public class Pickup extends Command{
private XboxController controller;
private SpeedController motor;
public Pickup(String name, int id, XboxController controller, SpeedController motor) {
super(name, id);
this.controller = controller;
this.motor = motor;
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void run() {
if (controller.getA()){ //check to see if the button A is pressed
motor.set(1); //turns motor on
}
else if (controller.getB()){ //check to see if the button B is pressed
motor.set(0); //turns motor on
}
}
@Override
public void runAuto(double distance, double speed, boolean useSensor) {
// TODO Auto-generated method stub
}
@Override
public boolean autoCommandDone() {
// TODO Auto-generated method stub
return false;
}
@Override
public void outputToDashboard() {
// TODO Auto-generated method stub
}
@Override
public void zeroAllSensors() {
// TODO Auto-generated method stub
}}
| src/org/usfirst/frc/team1699/robot/commands/Pickup.java | added startpickup and stoppickup for the ball motor... | src/org/usfirst/frc/team1699/robot/commands/Pickup.java | added startpickup and stoppickup for the ball motor... |
|
Java | mit | error: pathspec 'src/com/haxademic/sketch/hardware/DmxUSBProMIDIFeet.java' did not match any file(s) known to git
| ff348ddc97f2f29e69bf0745535713db1eadf9c9 | 1 | cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic | package com.haxademic.sketch.hardware;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.draw.color.EasingColor;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.hardware.shared.InputTrigger;
import beads.AudioContext;
import beads.Gain;
import beads.Sample;
import beads.SampleManager;
import beads.SamplePlayer;
import dmxP512.DmxP512;
public class DmxUSBProMIDIFeet
extends PAppletHax {
public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
DmxP512 dmx;
// On Windows, port should be an actual serial port, and probably needs to be uppercase - something like "COM1"
// On OS X, port will likely be a virtual serial port via USB, looking like "/dev/tty.usbserial-EN158815"
// - To make this work, you need to install something like the Plugable driver:
// - https://plugable.com/2011/07/12/installing-a-usb-serial-adapter-on-mac-os-x/
String DMXPRO_PORT = "DMXPRO_PORT";
String DMXPRO_BAUDRATE = "DMXPRO_BAUDRATE";
String DMXPRO_UNIVERSE_SIZE = "DMXPRO_UNIVERSE_SIZE";
protected boolean audioActive = false;
AudioContext ac;
Sample sample01;
int sampleTime01 = 0;
Sample sample02;
int sampleTime02 = 0;
protected InputTrigger trigger1 = new InputTrigger(
new char[]{'1'},
null,
new Integer[]{43},
null,
null
);
protected EasingColor color1 = new EasingColor(0xff00ff00, 8);
protected InputTrigger trigger2 = new InputTrigger(
new char[]{'2'},
null,
new Integer[]{49},
null,
null
);
protected EasingColor color2 = new EasingColor(0xffff0000, 8);
protected void overridePropsFile() {
p.appConfig.setProperty(DMXPRO_PORT, "/dev/tty.usbserial-EN158815");
p.appConfig.setProperty(AppSettings.MIDI_DEVICE_IN_INDEX, 0 );
}
public void setupFirstFrame() {
dmx = new DmxP512(P.p, p.appConfig.getInt(DMXPRO_UNIVERSE_SIZE, 128), false);
dmx.setupDmxPro(p.appConfig.getString(DMXPRO_PORT, "COM1"), p.appConfig.getInt(DMXPRO_BAUDRATE, 115000));
ac = new AudioContext();
sample01 = SampleManager.sample(FileUtil.getFile("audio/kit808/kick.wav"));
sample02 = SampleManager.sample(FileUtil.getFile("audio/kit808/snare.wav"));
ac.start();
}
public void drawApp() {
background(0);
if(trigger1.triggered() && p.millis() > sampleTime01 + 200) {
sampleTime01 = p.millis();
color1.setCurrentInt(0xffffffff);
color1.setTargetInt(0xff005500);
SamplePlayer samplePlayer01 = new SamplePlayer(ac, sample01);
samplePlayer01.setKillOnEnd(true);
ac.out.addInput(samplePlayer01);
samplePlayer01.start();
}
if(trigger2.triggered() && p.millis() > sampleTime02 + 200) {
sampleTime02 = p.millis();
color2.setCurrentInt(0xffffffff);
color2.setTargetInt(0xff000055);
SamplePlayer samplePlayer02 = new SamplePlayer(ac, sample02);
samplePlayer02.setKillOnEnd(true);
ac.out.addInput(samplePlayer02);
samplePlayer02.start();
}
color1.update();
color2.update();
if(!audioActive) {
dmx.set(1, (int)color1.r());
dmx.set(2, (int)color1.g());
dmx.set(3, (int)color1.b());
dmx.set(4, (int)color2.r());
dmx.set(5, (int)color2.g());
dmx.set(6, (int)color2.b());
} else {
dmx.set(1, P.round(255 * p._audioInput.getFFT().spectrum[10]));
dmx.set(2, P.round(255 * p._audioInput.getFFT().spectrum[20]));
dmx.set(3, P.round(255 * p._audioInput.getFFT().spectrum[40]));
dmx.set(4, P.round(255 * p._audioInput.getFFT().spectrum[60]));
dmx.set(5, P.round(255 * p._audioInput.getFFT().spectrum[80]));
dmx.set(6, P.round(255 * p._audioInput.getFFT().spectrum[100]));
}
}
public void keyPressed() {
super.keyPressed();
if(p.key == ' ') audioActive = !audioActive;
}
}
| src/com/haxademic/sketch/hardware/DmxUSBProMIDIFeet.java | Feet drums w/lighting
| src/com/haxademic/sketch/hardware/DmxUSBProMIDIFeet.java | Feet drums w/lighting |
|
Java | mit | error: pathspec 'GHGEssentials/src/nl/gewoonhdgaming/ess/utils/ChatUtils.java' did not match any file(s) known to git
| 631e4375190072319940c567bf1828782444a843 | 1 | Jasperdoit/GHGEssentials | package nl.gewoonhdgaming.ess.utils;
public class ChatUtils {
}
| GHGEssentials/src/nl/gewoonhdgaming/ess/utils/ChatUtils.java | Package setup | GHGEssentials/src/nl/gewoonhdgaming/ess/utils/ChatUtils.java | Package setup |
|
Java | mit | error: pathspec 'DailyProgrammer/src/com/kristof/dailyprogrammer/DiceRoll.java' did not match any file(s) known to git
| 24bb2f0deaf44cdfbcc994b73cc51fc297c52933 | 1 | jkristof/daily-programmer | package com.kristof.dailyprogrammer;
import java.text.NumberFormat;
import java.util.Random;
public class DiceRoll {
public static void main( String[] args ) {
System.out.println( "# of Rolls\t1s\t2s\t3s\t4s\t5s\t6s" );
System.out.println( "==============================================================" );
NumberFormat pf = NumberFormat.getPercentInstance();
pf.setMaximumFractionDigits( 2 );
for ( int i = 10; i <= 100000; i = i * 10 ) {
float[] rolls = new float[6];
for ( int j = 0; j < i; j++ ) {
rolls[new Random().nextInt( 6 )]++;
}
System.out.printf( "%d\t\t%s\t%s\t%s\t%s\t%s\t%s\n", i, pf.format( rolls[0] / i ), pf.format( rolls[1] / i ), pf.format( rolls[2] / i ),
pf.format( rolls[3] / i ), pf.format( rolls[4] / i ), pf.format( rolls[5] / i ) );
}
}
}
| DailyProgrammer/src/com/kristof/dailyprogrammer/DiceRoll.java | Solution for #163 [Easy] Probability Distribution of a 6 Sided Di | DailyProgrammer/src/com/kristof/dailyprogrammer/DiceRoll.java | Solution for #163 [Easy] Probability Distribution of a 6 Sided Di |
|
Java | mit | error: pathspec 'src/main/java/com/github/sergueik/swet/JavaHotkeyManager.java' did not match any file(s) known to git
| 15a7d070d98bcb3c6d218b985d30d686f1c78fda | 1 | sergueik/SWET,sergueik/SWET,sergueik/SWET,sergueik/SWET | package com.github.sergueik.swet;
import java.awt.event.KeyEvent;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Pointer;
import com.sun.jna.win32.W32APIOptions;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
// based on: https://toster.ru/q/636535
public class JavaHotkeyManager extends Thread {
public static void register() {
User32.RegisterHotKey(null, 1, 0x000, KeyEvent.VK_F);
new JavaHotkeyManager().start();
}
public JavaHotkeyManager() {
}
public static void main(String[] args) {
register();
// run();
}
@Override
public void run() {
JavaHotkeyManager.MSG msg = new JavaHotkeyManager.MSG();
System.err.println("Running " + this.toString());
while (true) {
// register the key on the same thread as listening
User32.RegisterHotKey(null, 1, 0x000, KeyEvent.VK_F);
while (User32.PeekMessage(msg, null, 0, 0, User32.PM_REMOVE)) {
if (msg.message == User32.WM_HOTKEY) {
System.out.println("Hotkey pressed with id: " + msg.wParam);
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class User32 {
static {
Native.register(
NativeLibrary.getInstance("user32", W32APIOptions.DEFAULT_OPTIONS));
}
public static final int MOD_ALT = 0x0001;
public static final int MOD_CONTROL = 0x0002;
public static final int MOD_SHIFT = 0x0004;
public static final int MOD_WIN = 0x0008;
public static final int WM_HOTKEY = 0x0312;
public static final int PM_REMOVE = 0x0001;
public static native boolean RegisterHotKey(Pointer hWnd, int id,
int fsModifiers, int vk);
public static native boolean UnregisterHotKey(Pointer hWnd, int id);
public static native boolean PeekMessage(JavaHotkeyManager.MSG lpMsg,
Pointer hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);
}
public static class MSG extends Structure {
public Pointer hWnd;
public int lParam;
public int message;
public int time;
public int wParam;
public int x;
public int y;
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[] { "hWnd", "lParam", "message", "time",
"wParam", "x", "y" });
}
}
} | src/main/java/com/github/sergueik/swet/JavaHotkeyManager.java | initial snapshot
| src/main/java/com/github/sergueik/swet/JavaHotkeyManager.java | initial snapshot |
|
Java | mit | error: pathspec 'content-resources/src/main/java/flyway/oskari/V1_36_0__register_contenteditor_bundle.java' did not match any file(s) known to git
| a0c711c0975d2f381ad1605d6e29738523776123 | 1 | nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server | package flyway.oskari;
import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import java.sql.Connection;
import java.sql.SQLException;
public class V1_36_0__register_contenteditor_bundle implements JdbcMigration {
private static final String NAMESPACE = "tampere";
private static final String BUNDLE_ID = "content-editor";
private static final String BUNDLE_TITLE = "content-editor";
public void migrate(Connection connection) throws SQLException {
// BundleHelper checks if these bundles are already registered
Bundle bundle = new Bundle();
bundle.setName(BUNDLE_ID);
bundle.setStartup(BundleHelper.getDefaultBundleStartup(NAMESPACE, BUNDLE_ID, BUNDLE_TITLE));
BundleHelper.registerBundle(bundle, connection);
}
}
| content-resources/src/main/java/flyway/oskari/V1_36_0__register_contenteditor_bundle.java | Add flyway class to add bundle
| content-resources/src/main/java/flyway/oskari/V1_36_0__register_contenteditor_bundle.java | Add flyway class to add bundle |
|
Java | mpl-2.0 | 1b7890d0b979acf046cd91345072429ebfeccbfb | 0 | petercpg/MozStumbler,priyankvex/MozStumbler,petercpg/MozStumbler,cascheberg/MozStumbler,priyankvex/MozStumbler,MozillaCZ/MozStumbler,priyankvex/MozStumbler,crankycoder/MozStumbler,petercpg/MozStumbler,cascheberg/MozStumbler,hasadna/OpenTrainApp,hasadna/OpenTrainApp,garvankeeley/MozStumbler,crankycoder/MozStumbler,garvankeeley/MozStumbler,MozillaCZ/MozStumbler,crankycoder/MozStumbler,cascheberg/MozStumbler,garvankeeley/MozStumbler,dougt/MozStumbler,MozillaCZ/MozStumbler | package org.mozilla.mozstumbler;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public final class MainActivity extends Activity {
private static final String LOGTAG = MainActivity.class.getName();
private static final String LEADERBOARD_URL = "https://location.services.mozilla.com/stats";
private ScannerServiceInterface mConnectionRemote;
private ServiceConnection mConnection;
private ServiceBroadcastReceiver mReceiver;
private Prefs mPrefs;
private int mGpsFixes;
private class ServiceBroadcastReceiver extends BroadcastReceiver {
private boolean mReceiverIsRegistered;
public void register() {
if (!mReceiverIsRegistered) {
registerReceiver(this, new IntentFilter(ScannerService.MESSAGE_TOPIC));
mReceiverIsRegistered = true;
}
}
public void unregister() {
if (mReceiverIsRegistered) {
unregisterReceiver(this);
mReceiverIsRegistered = false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ScannerService.MESSAGE_TOPIC)) {
Log.e(LOGTAG, "Received an unknown intent");
return;
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject.equals("Notification")) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(getApplicationContext(), (CharSequence) text, Toast.LENGTH_SHORT).show();
Log.d(LOGTAG, "Received a notification intent and showing: " + text);
return;
} else if (subject.equals("Reporter")) {
updateUI();
Log.d(LOGTAG, "Received a reporter intent...");
return;
} else if (subject.equals("Scanner")) {
mGpsFixes = intent.getIntExtra("fixes", 0);
updateUI();
Log.d(LOGTAG, "Received a scanner intent...");
return;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableStrictMode();
setContentView(R.layout.activity_main);
mPrefs = new Prefs(this);
new NoticeDialog(this, mPrefs).show();
EditText nicknameEditor = (EditText) findViewById(R.id.edit_nickname);
String nickname = mPrefs.getNickname(); // FIXME: StrictMode violation?
if (nickname != null) {
nicknameEditor.setText(nickname);
}
nicknameEditor.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
String newNickname = v.getText().toString().trim();
String placeholderText = getResources().getString(R.string.enter_nickname);
if (!newNickname.equals(placeholderText)) {
mPrefs.setNickname(newNickname);
}
}
return false;
}
});
Log.d(LOGTAG, "onCreate");
}
@Override
protected void onStart() {
super.onStart();
mReceiver = new ServiceBroadcastReceiver();
mReceiver.register();
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
mConnectionRemote = ScannerServiceInterface.Stub.asInterface(binder);
Log.d(LOGTAG, "Service connected");
updateUI();
}
public void onServiceDisconnected(ComponentName className) {
mConnectionRemote = null;
Log.d(LOGTAG, "Service disconnected", new Exception());
}
};
Intent intent = new Intent(this, ScannerService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.d(LOGTAG, "onStart");
}
@Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mConnection = null;
mConnectionRemote = null;
mReceiver.unregister();
mReceiver = null;
Log.d(LOGTAG, "onStop");
}
protected void updateUI() {
// TODO time this to make sure we're not blocking too long on mConnectionRemote
// if we care, we can bundle this into one call -- or use android to remember
// the state before the rotation.
if (mConnectionRemote == null) {
return;
}
Log.d(LOGTAG, "Updating UI");
boolean scanning = false;
try {
scanning = mConnectionRemote.isScanning();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
Button scanningBtn = (Button) findViewById(R.id.toggle_scanning);
if (scanning) {
scanningBtn.setText(R.string.stop_scanning);
} else {
scanningBtn.setText(R.string.start_scanning);
}
int APs = 0;
try {
APs = mConnectionRemote.getAPCount();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
formatTextView(R.id.gps_satellites, R.string.gps_satellites, mGpsFixes);
formatTextView(R.id.wifi_access_points, R.string.wifi_access_points, APs);
}
public void onClick_ToggleScanning(View v) throws RemoteException {
if (mConnectionRemote == null) {
return;
}
boolean scanning = mConnectionRemote.isScanning();
Log.d(LOGTAG, "Connection remote return: isScanning() = " + scanning);
Button b = (Button) v;
if (scanning) {
mConnectionRemote.stopScanning();
b.setText(R.string.start_scanning);
} else {
mConnectionRemote.startScanning();
b.setText(R.string.stop_scanning);
}
}
public void onClick_ViewLeaderboard(View v) {
Intent openLeaderboard = new Intent(Intent.ACTION_VIEW, Uri.parse(LEADERBOARD_URL));
startActivity(openLeaderboard);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
@TargetApi(9)
private void enableStrictMode() {
if (Build.VERSION.SDK_INT < 9) {
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.permitDiskReads()
.permitDiskWrites()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog().build());
}
private void formatTextView(int textViewId, int stringId, Object... args) {
TextView textView = (TextView) findViewById(textViewId);
String str = getResources().getString(stringId);
str = String.format(str, args);
textView.setText(str);
}
}
| src/org/mozilla/mozstumbler/MainActivity.java | package org.mozilla.mozstumbler;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public final class MainActivity extends Activity {
private static final String LOGTAG = MainActivity.class.getName();
private static final String LEADERBOARD_URL = "https://location.services.mozilla.com/stats";
private ScannerServiceInterface mConnectionRemote;
private ServiceConnection mConnection;
private ServiceBroadcastReceiver mReceiver;
private Prefs mPrefs;
private int mGpsFixes;
private class ServiceBroadcastReceiver extends BroadcastReceiver {
private boolean mReceiverIsRegistered;
public void register() {
if (!mReceiverIsRegistered) {
registerReceiver(this, new IntentFilter(ScannerService.MESSAGE_TOPIC));
mReceiverIsRegistered = true;
}
}
public void unregister() {
if (mReceiverIsRegistered) {
unregisterReceiver(this);
mReceiverIsRegistered = false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ScannerService.MESSAGE_TOPIC)) {
Log.e(LOGTAG, "Received an unknown intent");
return;
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject.equals("Notification")) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(getApplicationContext(), (CharSequence) text, Toast.LENGTH_SHORT).show();
Log.d(LOGTAG, "Received a notification intent and showing: " + text);
return;
} else if (subject.equals("Reporter")) {
updateUI();
Log.d(LOGTAG, "Received a reporter intent...");
return;
} else if (subject.equals("Scanner")) {
mGpsFixes = intent.getIntExtra("fixes", 0);
updateUI();
Log.d(LOGTAG, "Received a scanner intent...");
return;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableStrictMode();
setContentView(R.layout.activity_main);
mPrefs = new Prefs(this);
new NoticeDialog(this, mPrefs).show();
EditText nicknameEditor = (EditText) findViewById(R.id.edit_nickname);
String nickname = mPrefs.getNickname(); // FIXME: StrictMode violation?
if (nickname != null) {
nicknameEditor.setText(nickname);
}
nicknameEditor.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
String newNickname = v.getText().toString().trim();
String placeholderText = getResources().getString(R.string.enter_nickname);
if (!newNickname.equals(placeholderText)) {
mPrefs.setNickname(newNickname);
}
}
return false;
}
});
Log.d(LOGTAG, "onCreate");
}
@Override
protected void onStart() {
super.onStart();
mReceiver = new ServiceBroadcastReceiver();
mReceiver.register();
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
mConnectionRemote = ScannerServiceInterface.Stub.asInterface(binder);
Log.d(LOGTAG, "Service connected");
updateUI();
}
public void onServiceDisconnected(ComponentName className) {
mConnectionRemote = null;
Log.d(LOGTAG, "Service disconnected", new Exception());
}
};
Intent intent = new Intent(this, ScannerService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.d(LOGTAG, "onStart");
}
@Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mConnection = null;
mConnectionRemote = null;
mReceiver.unregister();
mReceiver = null;
Log.d(LOGTAG, "onStop");
}
protected void updateUI() {
// TODO time this to make sure we're not blocking too long on mConnectionRemote
// if we care, we can bundle this into one call -- or use android to remember
// the state before the rotation.
if (mConnectionRemote == null) {
return;
}
Log.d(LOGTAG, "Updating UI");
boolean scanning = false;
try {
scanning = mConnectionRemote.isScanning();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
Button scanningBtn = (Button) findViewById(R.id.toggle_scanning);
if (scanning) {
scanningBtn.setText(R.string.stop_scanning);
} else {
scanningBtn.setText(R.string.start_scanning);
}
int APs = 0;
try {
APs = mConnectionRemote.getAPCount();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
String APsScannedString = getResources().getString(R.string.wifi_access_points);
APsScannedString = String.format(APsScannedString, APs);
TextView APsScanned = (TextView) findViewById(R.id.wifi_access_points);
APsScanned.setText(APsScannedString);
String fixesString = getResources().getString(R.string.gps_satellites);
fixesString = String.format(fixesString, mGpsFixes);
TextView fixesTextView = (TextView) findViewById(R.id.gps_satellites);
fixesTextView.setText(fixesString);
}
public void onClick_ToggleScanning(View v) throws RemoteException {
if (mConnectionRemote == null) {
return;
}
boolean scanning = mConnectionRemote.isScanning();
Log.d(LOGTAG, "Connection remote return: isScanning() = " + scanning);
Button b = (Button) v;
if (scanning) {
mConnectionRemote.stopScanning();
b.setText(R.string.start_scanning);
} else {
mConnectionRemote.startScanning();
b.setText(R.string.stop_scanning);
}
}
public void onClick_ViewLeaderboard(View v) {
Intent openLeaderboard = new Intent(Intent.ACTION_VIEW, Uri.parse(LEADERBOARD_URL));
startActivity(openLeaderboard);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
@TargetApi(9)
private void enableStrictMode() {
if (Build.VERSION.SDK_INT < 9) {
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.permitDiskReads()
.permitDiskWrites()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog().build());
}
}
| Extract formatTextView() helper method
| src/org/mozilla/mozstumbler/MainActivity.java | Extract formatTextView() helper method |
|
Java | agpl-3.0 | error: pathspec 'portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/jms/business/SyncFromBackOffice.java' did not match any file(s) known to git
| 3182c9a826714f56ff1b9a748447b2d903c91c78 | 1 | hltn/opencps,VietOpenCPS/opencps,hltn/opencps,VietOpenCPS/opencps,VietOpenCPS/opencps,hltn/opencps | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.jms.business;
import java.util.List;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.jms.message.body.SyncFromBackOfficeMsgBody;
import org.opencps.processmgt.model.WorkflowOutput;
import org.opencps.processmgt.service.WorkflowOutputLocalServiceUtil;
import org.opencps.util.PortletConstants;
/**
* @author trungnt
*/
public class SyncFromBackOffice {
public void syncDossier(SyncFromBackOfficeMsgBody syncFromBackOfficeMsgBody) {
boolean statusUpdate = false;
//String actor = _getActor(toBackOffice.getRequestCommand());
try {
/*statusUpdate =
DossierLocalServiceUtil.updateDossierStatus(
toBackOffice.getDossierId(), toBackOffice.getFileGroupId(),
toBackOffice.getDossierStatus(),
toBackOffice.getReceptionNo(),
toBackOffice.getEstimateDatetime(),
toBackOffice.getReceiveDatetime(),
toBackOffice.getFinishDatetime(), actor,
toBackOffice.getRequestCommand(),
toBackOffice.getActionInfo(), toBackOffice.getMessageInfo());
List<WorkflowOutput> workflowOutputs =
WorkflowOutputLocalServiceUtil.getByProcessWFPostback(
toBackOffice.getProcessWorkflowId(), true);
DossierLocalServiceUtil.updateDossierStatus(
0, toBackOffice.getDossierId(),
PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCSUCCESS,
workflowOutputs);*/
}
catch (Exception e) {
}
}
}
| portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/jms/business/SyncFromBackOffice.java | Add SyncFromBackend | portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/jms/business/SyncFromBackOffice.java | Add SyncFromBackend |
|
Java | apache-2.0 | 28ab378639e1717c3dccc5b91d84525108e68749 | 0 | emolsson/cassandra,pallavi510/cassandra,bpupadhyaya/cassandra,jasonstack/cassandra,bpupadhyaya/cassandra,pkdevbox/cassandra,driftx/cassandra,yonglehou/cassandra,miguel0afd/cassandra-cqlMod,aweisberg/cassandra,kangkot/stratio-cassandra,caidongyun/cassandra,instaclustr/cassandra,fengshao0907/Cassandra-Research,ejankan/cassandra,weipinghe/cassandra,WorksApplications/cassandra,Instagram/cassandra,WorksApplications/cassandra,christian-esken/cassandra,thelastpickle/cassandra,tommystendahl/cassandra,project-zerus/cassandra,taigetco/cassandra_read,nlalevee/cassandra,belliottsmith/cassandra,ibmsoe/cassandra,Jaumo/cassandra,leomrocha/cassandra,strapdata/cassandra,iamaleksey/cassandra,nitsanw/cassandra,Jaumo/cassandra,aureagle/cassandra,Imran-C/cassandra,shookari/cassandra,newrelic-forks/cassandra,snazy/cassandra,chaordic/cassandra,yonglehou/cassandra,adelapena/cassandra,nitsanw/cassandra,ptnapoleon/cassandra,mheffner/cassandra-1,scaledata/cassandra,sivikt/cassandra,spodkowinski/cassandra,mshuler/cassandra,JeremiahDJordan/cassandra,dkua/cassandra,tommystendahl/cassandra,guanxi55nba/key-value-store,fengshao0907/cassandra-1,miguel0afd/cassandra-cqlMod,fengshao0907/cassandra-1,asias/cassandra,xiongzheng/Cassandra-Research,mkjellman/cassandra,mshuler/cassandra,mheffner/cassandra-1,nutbunnies/cassandra,DavidHerzogTU-Berlin/cassandraToRun,LatencyUtils/cassandra-stress2,ptnapoleon/cassandra,exoscale/cassandra,joesiewert/cassandra,dkua/cassandra,guanxi55nba/db-improvement,pbailis/cassandra-pbs,yangzhe1991/cassandra,DavidHerzogTU-Berlin/cassandraToRun,jbellis/cassandra,scaledata/cassandra,DICL/cassandra,guanxi55nba/db-improvement,mgmuscari/cassandra-cdh4,Bj0rnen/cassandra,cooldoger/cassandra,juiceblender/cassandra,bcoverston/apache-hosted-cassandra,stef1927/cassandra,josh-mckenzie/cassandra,carlyeks/cassandra,regispl/cassandra,shawnkumar/cstargraph,instaclustr/cassandra,rmarchei/cassandra,bcoverston/cassandra,pkdevbox/cassandra,Stratio/stratio-cassandra,ibmsoe/cassandra,nvoron23/cassandra,iamaleksey/cassandra,darach/cassandra,aboudreault/cassandra,sluk3r/cassandra,likaiwalkman/cassandra,MasahikoSawada/cassandra,aweisberg/cassandra,WorksApplications/cassandra,dongjiaqiang/cassandra,clohfink/cassandra,vaibhi9/cassandra,mklew/mmp,DikangGu/cassandra,pkdevbox/cassandra,darach/cassandra,GabrielNicolasAvellaneda/cassandra,nakomis/cassandra,nitsanw/cassandra,mshuler/cassandra,rackerlabs/cloudmetrics-cassandra,blambov/cassandra,pauloricardomg/cassandra,sayanh/ViewMaintenanceSupport,jeffjirsa/cassandra,josh-mckenzie/cassandra,weipinghe/cassandra,exoscale/cassandra,tongjixianing/projects,likaiwalkman/cassandra,wreda/cassandra,whitepages/cassandra,ben-manes/cassandra,helena/cassandra,jbellis/cassandra,mgmuscari/cassandra-cdh4,adelapena/cassandra,mt0803/cassandra,gdusbabek/cassandra,sayanh/ViewMaintenanceSupport,jbellis/cassandra,pauloricardomg/cassandra,qinjin/mdtc-cassandra,yukim/cassandra,hhorii/cassandra,vramaswamy456/cassandra,michaelsembwever/cassandra,wreda/cassandra,michaelmior/cassandra,mkjellman/cassandra,sluk3r/cassandra,spodkowinski/cassandra,jrwest/cassandra,nlalevee/cassandra,krummas/cassandra,sedulam/CASSANDRA-12201,heiko-braun/cassandra,Jollyplum/cassandra,Jollyplum/cassandra,matthewtt/cassandra_read,ptuckey/cassandra,AtwooTM/cassandra,ifesdjeen/cassandra,sedulam/CASSANDRA-12201,rdio/cassandra,rackerlabs/cloudmetrics-cassandra,snazy/cassandra,aarushi12002/cassandra,taigetco/cassandra_read,bmel/cassandra,jasonwee/cassandra,christian-esken/cassandra,guard163/cassandra,jasonwee/cassandra,DavidHerzogTU-Berlin/cassandra,stef1927/cassandra,cooldoger/cassandra,HidemotoNakada/cassandra-udf,segfault/apache_cassandra,scylladb/scylla-tools-java,scylladb/scylla-tools-java,tommystendahl/cassandra,ejankan/cassandra,lalithsuresh/cassandra-c3,regispl/cassandra,ptuckey/cassandra,jeromatron/cassandra,mklew/mmp,blambov/cassandra,belliottsmith/cassandra,nvoron23/cassandra,sharvanath/cassandra,beobal/cassandra,aweisberg/cassandra,beobal/cassandra,guanxi55nba/key-value-store,mashuai/Cassandra-Research,pcmanus/cassandra,rmarchei/cassandra,xiongzheng/Cassandra-Research,cooldoger/cassandra,tjake/cassandra,jasobrown/cassandra,EnigmaCurry/cassandra,modempachev4/kassandra,heiko-braun/cassandra,codefollower/Cassandra-Research,Stratio/stratio-cassandra,swps/cassandra,helena/cassandra,jkni/cassandra,strapdata/cassandra,modempachev4/kassandra,bdeggleston/cassandra,jrwest/cassandra,iamaleksey/cassandra,dprguiuc/Cassandra-Wasef,michaelmior/cassandra,miguel0afd/cassandra-cqlMod,DavidHerzogTU-Berlin/cassandraToRun,instaclustr/cassandra,Stratio/stratio-cassandra,bcoverston/cassandra,fengshao0907/cassandra-1,MasahikoSawada/cassandra,nakomis/cassandra,aureagle/cassandra,thobbs/cassandra,yhnishi/cassandra,yukim/cassandra,nakomis/cassandra,Stratio/cassandra,wreda/cassandra,shookari/cassandra,jsanda/cassandra,bmel/cassandra,adejanovski/cassandra,rmarchei/cassandra,iburmistrov/Cassandra,kangkot/stratio-cassandra,DavidHerzogTU-Berlin/cassandra,phact/cassandra,thelastpickle/cassandra,bdeggleston/cassandra,pauloricardomg/cassandra,ifesdjeen/cassandra,vramaswamy456/cassandra,blambov/cassandra,guard163/cassandra,tommystendahl/cassandra,ifesdjeen/cassandra,blerer/cassandra,bcoverston/apache-hosted-cassandra,taigetco/cassandra_read,nvoron23/cassandra,kgreav/cassandra,iburmistrov/Cassandra,driftx/cassandra,iburmistrov/Cassandra,jeromatron/cassandra,bcoverston/apache-hosted-cassandra,Stratio/stratio-cassandra,DikangGu/cassandra,krummas/cassandra,newrelic-forks/cassandra,scaledata/cassandra,spodkowinski/cassandra,pcn/cassandra-1,mgmuscari/cassandra-cdh4,hengxin/cassandra,jasonstack/cassandra,mheffner/cassandra-1,nutbunnies/cassandra,mambocab/cassandra,pcmanus/cassandra,kgreav/cassandra,gdusbabek/cassandra,a-buck/cassandra,jasobrown/cassandra,macintoshio/cassandra,ibmsoe/cassandra,rdio/cassandra,a-buck/cassandra,pcn/cassandra-1,nlalevee/cassandra,qinjin/mdtc-cassandra,carlyeks/cassandra,asias/cassandra,vramaswamy456/cassandra,JeremiahDJordan/cassandra,kgreav/cassandra,kangkot/stratio-cassandra,juiceblender/cassandra,xiongzheng/Cassandra-Research,nutbunnies/cassandra,gdusbabek/cassandra,mambocab/cassandra,beobal/cassandra,ptnapoleon/cassandra,pcmanus/cassandra,rogerchina/cassandra,rdio/cassandra,sriki77/cassandra,dongjiaqiang/cassandra,mshuler/cassandra,boneill42/cassandra,hhorii/cassandra,fengshao0907/Cassandra-Research,jkni/cassandra,kangkot/stratio-cassandra,thelastpickle/cassandra,christian-esken/cassandra,pbailis/cassandra-pbs,thobbs/cassandra,knifewine/cassandra,strapdata/cassandra,scylladb/scylla-tools-java,apache/cassandra,project-zerus/cassandra,swps/cassandra,Imran-C/cassandra,sharvanath/cassandra,emolsson/cassandra,codefollower/Cassandra-Research,yangzhe1991/cassandra,RyanMagnusson/cassandra,sbtourist/cassandra,ifesdjeen/cassandra,Bj0rnen/cassandra,sayanh/ViewMaintenanceCassandra,phact/cassandra,swps/cassandra,knifewine/cassandra,whitepages/cassandra,belliottsmith/cassandra,pthomaid/cassandra,adejanovski/cassandra,thobbs/cassandra,segfault/apache_cassandra,HidemotoNakada/cassandra-udf,krummas/cassandra,mkjellman/cassandra,szhou1234/cassandra,scylladb/scylla-tools-java,mike-tr-adamson/cassandra,EnigmaCurry/cassandra,DICL/cassandra,pofallon/cassandra,tongjixianing/projects,mt0803/cassandra,clohfink/cassandra,bcoverston/cassandra,jsanda/cassandra,hengxin/cassandra,szhou1234/cassandra,sharvanath/cassandra,bcoverston/cassandra,iamaleksey/cassandra,stef1927/cassandra,kangkot/stratio-cassandra,pthomaid/cassandra,sbtourist/cassandra,codefollower/Cassandra-Research,juiceblender/cassandra,tjake/cassandra,dongjiaqiang/cassandra,JeremiahDJordan/cassandra,ollie314/cassandra,a-buck/cassandra,exoscale/cassandra,jeromatron/cassandra,pofallon/cassandra,Stratio/cassandra,mkjellman/cassandra,rogerchina/cassandra,jasobrown/cassandra,matthewtt/cassandra_read,likaiwalkman/cassandra,fengshao0907/Cassandra-Research,mashuai/Cassandra-Research,DavidHerzogTU-Berlin/cassandra,mike-tr-adamson/cassandra,lalithsuresh/cassandra-c3,heiko-braun/cassandra,jrwest/cassandra,vaibhi9/cassandra,pofallon/cassandra,blerer/cassandra,aboudreault/cassandra,jeffjirsa/cassandra,instaclustr/cassandra,mklew/mmp,ollie314/cassandra,matthewtt/cassandra_read,aarushi12002/cassandra,helena/cassandra,leomrocha/cassandra,szhou1234/cassandra,RyanMagnusson/cassandra,ben-manes/cassandra,mambocab/cassandra,aboudreault/cassandra,apache/cassandra,segfault/apache_cassandra,yhnishi/cassandra,shawnkumar/cstargraph,michaelsembwever/cassandra,sriki77/cassandra,rackerlabs/cloudmetrics-cassandra,modempachev4/kassandra,Bj0rnen/cassandra,yanbit/cassandra,LatencyUtils/cassandra-stress2,jasobrown/cassandra,chbatey/cassandra-1,apache/cassandra,Jollyplum/cassandra,Instagram/cassandra,pallavi510/cassandra,guanxi55nba/key-value-store,knifewine/cassandra,sivikt/cassandra,mike-tr-adamson/cassandra,apache/cassandra,pbailis/cassandra-pbs,WorksApplications/cassandra,ollie314/cassandra,driftx/cassandra,vaibhi9/cassandra,Stratio/stratio-cassandra,jeffjirsa/cassandra,guard163/cassandra,bpupadhyaya/cassandra,yanbit/cassandra,aweisberg/cassandra,caidongyun/cassandra,strapdata/cassandra,snazy/cassandra,adelapena/cassandra,bmel/cassandra,dprguiuc/Cassandra-Wasef,MasahikoSawada/cassandra,hhorii/cassandra,beobal/cassandra,blerer/cassandra,newrelic-forks/cassandra,blerer/cassandra,aureagle/cassandra,Jaumo/cassandra,lalithsuresh/cassandra-c3,sayanh/ViewMaintenanceCassandra,sayanh/ViewMaintenanceCassandra,darach/cassandra,mashuai/Cassandra-Research,aarushi12002/cassandra,yukim/cassandra,snazy/cassandra,regispl/cassandra,macintoshio/cassandra,dprguiuc/Cassandra-Wasef,thelastpickle/cassandra,caidongyun/cassandra,yanbit/cassandra,LatencyUtils/cassandra-stress2,spodkowinski/cassandra,jsanda/cassandra,ejankan/cassandra,rogerchina/cassandra,whitepages/cassandra,jasonwee/cassandra,yhnishi/cassandra,kgreav/cassandra,sriki77/cassandra,tongjixianing/projects,GabrielNicolasAvellaneda/cassandra,AtwooTM/cassandra,project-zerus/cassandra,tjake/cassandra,adelapena/cassandra,yonglehou/cassandra,michaelsembwever/cassandra,carlyeks/cassandra,chbatey/cassandra-1,jeffjirsa/cassandra,szhou1234/cassandra,DikangGu/cassandra,chaordic/cassandra,josh-mckenzie/cassandra,tjake/cassandra,michaelsembwever/cassandra,bdeggleston/cassandra,sivikt/cassandra,Instagram/cassandra,mt0803/cassandra,macintoshio/cassandra,weideng1/cassandra,Instagram/cassandra,phact/cassandra,qinjin/mdtc-cassandra,driftx/cassandra,pallavi510/cassandra,pthomaid/cassandra,boneill42/cassandra,adejanovski/cassandra,weideng1/cassandra,stef1927/cassandra,mike-tr-adamson/cassandra,krummas/cassandra,RyanMagnusson/cassandra,emolsson/cassandra,GabrielNicolasAvellaneda/cassandra,joesiewert/cassandra,sedulam/CASSANDRA-12201,clohfink/cassandra,shookari/cassandra,clohfink/cassandra,sluk3r/cassandra,weideng1/cassandra,EnigmaCurry/cassandra,ben-manes/cassandra,joesiewert/cassandra,dkua/cassandra,pauloricardomg/cassandra,shawnkumar/cstargraph,weipinghe/cassandra,jkni/cassandra,hengxin/cassandra,chaordic/cassandra,jrwest/cassandra,Imran-C/cassandra,michaelmior/cassandra,asias/cassandra,belliottsmith/cassandra,josh-mckenzie/cassandra,cooldoger/cassandra,Stratio/cassandra,boneill42/cassandra,yukim/cassandra,juiceblender/cassandra,bdeggleston/cassandra,DICL/cassandra,jasonstack/cassandra,blambov/cassandra,ptuckey/cassandra,sbtourist/cassandra,chbatey/cassandra-1,yangzhe1991/cassandra,guanxi55nba/db-improvement,AtwooTM/cassandra,HidemotoNakada/cassandra-udf,pcn/cassandra-1,leomrocha/cassandra | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cassandra.db;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.columniterator.IdentityQueryFilter;
import org.apache.cassandra.db.filter.IFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.BytesToken;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.IndexClause;
import org.apache.cassandra.thrift.IndexExpression;
import org.apache.cassandra.thrift.IndexOperator;
import org.apache.cassandra.utils.ByteBufferUtil;
public class CleanupTest extends CleanupHelper
{
public static final int LOOPS = 200;
public static final String TABLE1 = "Keyspace1";
public static final String CF1 = "Indexed1";
public static final String CF2 = "Standard1";
public static final ByteBuffer COLUMN = ByteBufferUtil.bytes("birthdate");
public static final ByteBuffer VALUE = ByteBuffer.allocate(8);
static
{
VALUE.putLong(20101229);
VALUE.flip();
}
@Test
public void testCleanup() throws IOException, ExecutionException, InterruptedException, ConfigurationException
{
StorageService.instance.initServer();
Table table = Table.open(TABLE1);
ColumnFamilyStore cfs = table.getColumnFamilyStore(CF2);
List<Row> rows;
// insert data and verify we get it back w/ range query
fillCF(cfs, LOOPS);
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
// with one token in the ring, owned by the local node, cleanup should be a no-op
CompactionManager.instance.performCleanup(cfs);
// check data is still there
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
}
@Test
public void testCleanupWithIndexes() throws IOException, ExecutionException, InterruptedException
{
Table table = Table.open(TABLE1);
ColumnFamilyStore cfs = table.getColumnFamilyStore(CF1);
assertEquals(cfs.getIndexedColumns().iterator().next(), COLUMN);
List<Row> rows;
// insert data and verify we get it back w/ range query
fillCF(cfs, LOOPS);
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
ColumnFamilyStore cfi = cfs.getIndexedColumnFamilyStore(COLUMN);
assertTrue(cfi.isIndexBuilt());
// verify we get it back w/ index query too
IndexExpression expr = new IndexExpression(COLUMN, IndexOperator.EQ, VALUE);
IndexClause clause = new IndexClause(Arrays.asList(expr), ByteBufferUtil.EMPTY_BYTE_BUFFER, Integer.MAX_VALUE);
IFilter filter = new IdentityQueryFilter();
IPartitioner p = StorageService.getPartitioner();
Range range = new Range(p.getMinimumToken(), p.getMinimumToken());
rows = table.getColumnFamilyStore(CF1).scan(clause, range, filter);
assertEquals(LOOPS, rows.size());
// we don't allow cleanup when the local host has no range to avoid wipping up all data when a node has not join the ring.
// So to make sure cleanup erase everything here, we give the localhost the tiniest possible range.
TokenMetadata tmd = StorageService.instance.getTokenMetadata();
byte[] tk1 = new byte[1], tk2 = new byte[1];
tk1[0] = 2;
tk2[0] = 1;
tmd.updateNormalToken(new BytesToken(tk1), InetAddress.getByName("127.0.0.1"));
tmd.updateNormalToken(new BytesToken(tk2), InetAddress.getByName("127.0.0.2"));
CompactionManager.instance.performCleanup(cfs);
// row data should be gone
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(0, rows.size());
// not only should it be gone but there should be no data on disk, not even tombstones
assert cfs.getSSTables().isEmpty();
// 2ary indexes should result in no results, too (although tombstones won't be gone until compacted)
rows = cfs.scan(clause, range, filter);
assertEquals(0, rows.size());
}
protected void fillCF(ColumnFamilyStore cfs, int rowsPerSSTable) throws ExecutionException, InterruptedException, IOException
{
CompactionManager.instance.disableAutoCompaction();
for (int i = 0; i < rowsPerSSTable; i++)
{
String key = String.valueOf(i);
// create a row and update the birthdate value, test that the index query fetches the new version
RowMutation rm;
rm = new RowMutation(TABLE1, ByteBufferUtil.bytes(key));
rm.add(new QueryPath(cfs.getColumnFamilyName(), null, COLUMN), VALUE, System.currentTimeMillis());
rm.applyUnsafe();
}
cfs.forceBlockingFlush();
}
}
| test/unit/org/apache/cassandra/db/CleanupTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cassandra.db;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.columniterator.IdentityQueryFilter;
import org.apache.cassandra.db.filter.IFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.IndexClause;
import org.apache.cassandra.thrift.IndexExpression;
import org.apache.cassandra.thrift.IndexOperator;
import org.apache.cassandra.utils.ByteBufferUtil;
public class CleanupTest extends CleanupHelper
{
public static final int LOOPS = 200;
public static final String TABLE1 = "Keyspace1";
public static final String CF1 = "Indexed1";
public static final String CF2 = "Standard1";
public static final ByteBuffer COLUMN = ByteBufferUtil.bytes("birthdate");
public static final ByteBuffer VALUE = ByteBuffer.allocate(8);
static
{
VALUE.putLong(20101229);
VALUE.flip();
}
@Test
public void testCleanup() throws IOException, ExecutionException, InterruptedException, ConfigurationException
{
StorageService.instance.initServer();
Table table = Table.open(TABLE1);
ColumnFamilyStore cfs = table.getColumnFamilyStore(CF2);
List<Row> rows;
// insert data and verify we get it back w/ range query
fillCF(cfs, LOOPS);
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
// with one token in the ring, owned by the local node, cleanup should be a no-op
CompactionManager.instance.performCleanup(cfs);
// check data is still there
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
}
@Test
public void testCleanupWithIndexes() throws IOException, ExecutionException, InterruptedException
{
Table table = Table.open(TABLE1);
ColumnFamilyStore cfs = table.getColumnFamilyStore(CF1);
assertEquals(cfs.getIndexedColumns().iterator().next(), COLUMN);
List<Row> rows;
// insert data and verify we get it back w/ range query
fillCF(cfs, LOOPS);
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(LOOPS, rows.size());
ColumnFamilyStore cfi = cfs.getIndexedColumnFamilyStore(COLUMN);
assertTrue(cfi.isIndexBuilt());
// verify we get it back w/ index query too
IndexExpression expr = new IndexExpression(COLUMN, IndexOperator.EQ, VALUE);
IndexClause clause = new IndexClause(Arrays.asList(expr), ByteBufferUtil.EMPTY_BYTE_BUFFER, Integer.MAX_VALUE);
IFilter filter = new IdentityQueryFilter();
IPartitioner p = StorageService.getPartitioner();
Range range = new Range(p.getMinimumToken(), p.getMinimumToken());
rows = table.getColumnFamilyStore(CF1).scan(clause, range, filter);
assertEquals(LOOPS, rows.size());
// nuke our token so cleanup will remove everything
TokenMetadata tmd = StorageService.instance.getTokenMetadata();
tmd.clearUnsafe();
assert StorageService.instance.getLocalRanges(TABLE1).isEmpty();
CompactionManager.instance.performCleanup(cfs);
// row data should be gone
rows = cfs.getRangeSlice(null, Util.range("", ""), 1000, new IdentityQueryFilter());
assertEquals(0, rows.size());
// not only should it be gone but there should be no data on disk, not even tombstones
assert cfs.getSSTables().isEmpty();
// 2ary indexes should result in no results, too (although tombstones won't be gone until compacted)
rows = cfs.scan(clause, range, filter);
assertEquals(0, rows.size());
}
protected void fillCF(ColumnFamilyStore cfs, int rowsPerSSTable) throws ExecutionException, InterruptedException, IOException
{
CompactionManager.instance.disableAutoCompaction();
for (int i = 0; i < rowsPerSSTable; i++)
{
String key = String.valueOf(i);
// create a row and update the birthdate value, test that the index query fetches the new version
RowMutation rm;
rm = new RowMutation(TABLE1, ByteBufferUtil.bytes(key));
rm.add(new QueryPath(cfs.getColumnFamilyName(), null, COLUMN), VALUE, System.currentTimeMillis());
rm.applyUnsafe();
}
cfs.forceBlockingFlush();
}
}
| Fix unit tests for CASSANDRA-2428
git-svn-id: 97f024e056bb8360c163ac9719c09bffda44c4d2@1090054 13f79535-47bb-0310-9956-ffa450edef68
| test/unit/org/apache/cassandra/db/CleanupTest.java | Fix unit tests for CASSANDRA-2428 |
|
Java | apache-2.0 | 124c25d39d70626f6e7a5cfd04bef214cd0f2c5d | 0 | linkedin/ambry,xiahome/ambry,pnarayanan/ambry,nsivabalan/ambry,vgkholla/ambry,cgtz/ambry,daniellitoc/ambry-Research,cgtz/ambry,pnarayanan/ambry,linkedin/ambry,linkedin/ambry,vgkholla/ambry,xiahome/ambry,linkedin/ambry,cgtz/ambry,cgtz/ambry,daniellitoc/ambry-Research,nsivabalan/ambry | package com.github.ambry.clustermap;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.network.Port;
import com.github.ambry.network.PortType;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Mock cluster map for unit tests. This sets up a three node cluster
* with 3 mount points in each. Each mount point has three partitions
* and each partition has 3 replicas on each node.
*/
public class MockClusterMap implements ClusterMap {
private final Map<Long, PartitionId> partitions;
private final List<MockDataNodeId> dataNodes;
private static int currentPlainTextPort = 50000;
private static int currentSSLPort = 60000;
public MockClusterMap()
throws IOException {
this(false);
}
public int getNextAvailablePlainTextPortNumber()
throws IOException {
return currentPlainTextPort++;
}
public int getNextAvailableSSLPortNumber()
throws IOException {
return currentSSLPort++;
}
public MockClusterMap(boolean enableSSLPorts)
throws IOException {
dataNodes = new ArrayList<MockDataNodeId>(9);
// create 3 nodes with each having 3 mount paths
if (enableSSLPorts) {
MockDataNodeId dataNodeId1 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC1");
MockDataNodeId dataNodeId2 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC1");
MockDataNodeId dataNodeId3 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC1");
MockDataNodeId dataNodeId4 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC2");
MockDataNodeId dataNodeId5 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC2");
MockDataNodeId dataNodeId6 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC2");
MockDataNodeId dataNodeId7 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC3");
MockDataNodeId dataNodeId8 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC3");
MockDataNodeId dataNodeId9 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber(), getNextAvailableSSLPortNumber()), "DC3");
dataNodes.add(dataNodeId1);
dataNodes.add(dataNodeId2);
dataNodes.add(dataNodeId3);
dataNodes.add(dataNodeId4);
dataNodes.add(dataNodeId5);
dataNodes.add(dataNodeId6);
dataNodes.add(dataNodeId7);
dataNodes.add(dataNodeId8);
dataNodes.add(dataNodeId9);
} else {
MockDataNodeId dataNodeId1 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC1");
MockDataNodeId dataNodeId2 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC1");
MockDataNodeId dataNodeId3 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC1");
MockDataNodeId dataNodeId4 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC2");
MockDataNodeId dataNodeId5 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC2");
MockDataNodeId dataNodeId6 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC2");
MockDataNodeId dataNodeId7 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC3");
MockDataNodeId dataNodeId8 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC3");
MockDataNodeId dataNodeId9 = createDataNode(getListOfPorts(getNextAvailablePlainTextPortNumber()), "DC3");
dataNodes.add(dataNodeId1);
dataNodes.add(dataNodeId2);
dataNodes.add(dataNodeId3);
dataNodes.add(dataNodeId4);
dataNodes.add(dataNodeId5);
dataNodes.add(dataNodeId6);
dataNodes.add(dataNodeId7);
dataNodes.add(dataNodeId8);
dataNodes.add(dataNodeId9);
}
partitions = new HashMap<Long, PartitionId>();
// create three partitions on each mount path
long partitionId = 0;
for (int i = 0; i < dataNodes.get(0).getMountPaths().size(); i++) {
for (int j = 0; j < 3; j++) {
PartitionId id = new MockPartitionId(partitionId, dataNodes, i);
partitions.put(partitionId, id);
partitionId++;
}
}
}
ArrayList<Port> getListOfPorts(int port) {
ArrayList<Port> ports = new ArrayList<Port>();
ports.add(new Port(port, PortType.PLAINTEXT));
return ports;
}
ArrayList<Port> getListOfPorts(int port, int sslPort) {
ArrayList<Port> ports = new ArrayList<Port>();
ports.add(new Port(port, PortType.PLAINTEXT));
ports.add(new Port(sslPort, PortType.SSL));
return ports;
}
private int getPlainTextPort(ArrayList<Port> ports) {
for (Port port : ports) {
if (port.getPortType() == PortType.PLAINTEXT) {
return port.getPort();
}
}
throw new IllegalArgumentException("No PlainText port found ");
}
private MockDataNodeId createDataNode(ArrayList<Port> ports, String datacenter)
throws IOException {
File f = null;
int port = getPlainTextPort(ports);
try {
List<String> mountPaths = new ArrayList<String>(3);
f = File.createTempFile("ambry", ".tmp");
File mountFile1 = new File(f.getParent(), "mountpathfile" + port + "0");
mountFile1.mkdir();
String mountPath1 = mountFile1.getAbsolutePath();
File mountFile2 = new File(f.getParent(), "mountpathfile" + port + "1");
mountFile2.mkdir();
String mountPath2 = mountFile2.getAbsolutePath();
File mountFile3 = new File(f.getParent(), "mountpathfile" + port + "2");
mountFile3.mkdir();
String mountPath3 = mountFile3.getAbsolutePath();
mountPaths.add(mountPath1);
mountPaths.add(mountPath2);
mountPaths.add(mountPath3);
MockDataNodeId dataNode = new MockDataNodeId(ports, mountPaths, datacenter);
return dataNode;
} finally {
if (f != null) {
f.delete();
}
}
}
@Override
public PartitionId getPartitionIdFromStream(DataInputStream stream)
throws IOException {
short version = stream.readShort();
long id = stream.readLong();
return partitions.get(id);
}
@Override
public List<PartitionId> getWritablePartitionIds() {
List<PartitionId> partitionIdList = new ArrayList<PartitionId>();
for (PartitionId partitionId : partitions.values()) {
partitionIdList.add(partitionId);
}
return partitionIdList;
}
@Override
public boolean hasDatacenter(String datacenterName) {
return true;
}
@Override
public DataNodeId getDataNodeId(String hostname, int port) {
for (DataNodeId dataNodeId : dataNodes) {
if (dataNodeId.getHostname().compareTo(hostname) == 0 && dataNodeId.getPort() == port) {
return dataNodeId;
}
}
return null;
}
@Override
public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId) {
ArrayList<ReplicaId> replicaIdsToReturn = new ArrayList<ReplicaId>();
for (PartitionId partitionId : partitions.values()) {
List<ReplicaId> replicaIds = partitionId.getReplicaIds();
for (ReplicaId replicaId : replicaIds) {
if (replicaId.getDataNodeId().getHostname().compareTo(dataNodeId.getHostname()) == 0
&& replicaId.getDataNodeId().getPort() == dataNodeId.getPort()) {
replicaIdsToReturn.add(replicaId);
}
}
}
return replicaIdsToReturn;
}
@Override
public List<DataNodeId> getDataNodeIds() {
return new ArrayList<DataNodeId>(dataNodes);
}
public List<MockDataNodeId> getDataNodes() {
return dataNodes;
}
@Override
public MetricRegistry getMetricRegistry() {
// Each server that calls this mocked interface needs its own metric registry.
return new MetricRegistry();
}
public void cleanup() {
for (PartitionId partitionId : partitions.values()) {
MockPartitionId mockPartition = (MockPartitionId) partitionId;
mockPartition.cleanUp();
}
for (DataNodeId dataNode : dataNodes) {
List<String> mountPaths = ((MockDataNodeId) dataNode).getMountPaths();
for (String mountPath : mountPaths) {
File mountPathDir = new File(mountPath);
for (File file : mountPathDir.listFiles()) {
file.delete();
}
mountPathDir.delete();
}
}
}
public void onReplicaEvent(ReplicaId replicaId, ReplicaEventType event) {
switch (event) {
case Disk_Error:
((MockDiskId) replicaId.getDiskId()).onDiskError();
break;
case Disk_Ok:
((MockDiskId) replicaId.getDiskId()).onDiskOk();
break;
case Node_Timeout:
((MockDataNodeId) replicaId.getDataNodeId()).onNodeTimeout();
break;
case Node_Response:
((MockDataNodeId) replicaId.getDataNodeId()).onNodeResponse();
break;
case Partition_ReadOnly:
((MockPartitionId) replicaId.getPartitionId()).onPartitionReadOnly();
break;
}
}
}
| ambry-clustermap/src/test/java/com.github.ambry.clustermap/MockClusterMap.java | package com.github.ambry.clustermap;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.network.Port;
import com.github.ambry.network.PortType;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Mock cluster map for unit tests. This sets up a three node cluster
* with 3 mount points in each. Each mount point has three partitions
* and each partition has 3 replicas on each node.
*/
public class MockClusterMap implements ClusterMap {
private final Map<Long, PartitionId> partitions;
private final List<MockDataNodeId> dataNodes;
private static int currentPlainTextPort = 50000;
private static int currentSSLPort = 60000;
public MockClusterMap()
throws IOException {
this(false);
}
public int getNextAvailablePlainTextPort()
throws IOException {
return currentPlainTextPort++;
}
public int getNextAvailableSSLPort()
throws IOException {
return currentSSLPort++;
}
public MockClusterMap(boolean enableSSLPorts)
throws IOException {
dataNodes = new ArrayList<MockDataNodeId>(9);
// create 3 nodes with each having 3 mount paths
if (enableSSLPorts) {
MockDataNodeId dataNodeId1 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC1");
MockDataNodeId dataNodeId2 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC1");
MockDataNodeId dataNodeId3 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC1");
MockDataNodeId dataNodeId4 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC2");
MockDataNodeId dataNodeId5 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC2");
MockDataNodeId dataNodeId6 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC2");
MockDataNodeId dataNodeId7 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC3");
MockDataNodeId dataNodeId8 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC3");
MockDataNodeId dataNodeId9 =
createDataNode(getListOfPorts(getNextAvailablePlainTextPort(), getNextAvailableSSLPort()), "DC3");
dataNodes.add(dataNodeId1);
dataNodes.add(dataNodeId2);
dataNodes.add(dataNodeId3);
dataNodes.add(dataNodeId4);
dataNodes.add(dataNodeId5);
dataNodes.add(dataNodeId6);
dataNodes.add(dataNodeId7);
dataNodes.add(dataNodeId8);
dataNodes.add(dataNodeId9);
} else {
MockDataNodeId dataNodeId1 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC1");
MockDataNodeId dataNodeId2 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC1");
MockDataNodeId dataNodeId3 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC1");
MockDataNodeId dataNodeId4 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC2");
MockDataNodeId dataNodeId5 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC2");
MockDataNodeId dataNodeId6 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC2");
MockDataNodeId dataNodeId7 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC3");
MockDataNodeId dataNodeId8 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC3");
MockDataNodeId dataNodeId9 = createDataNode(getListOfPorts(getNextAvailablePlainTextPort()), "DC3");
dataNodes.add(dataNodeId1);
dataNodes.add(dataNodeId2);
dataNodes.add(dataNodeId3);
dataNodes.add(dataNodeId4);
dataNodes.add(dataNodeId5);
dataNodes.add(dataNodeId6);
dataNodes.add(dataNodeId7);
dataNodes.add(dataNodeId8);
dataNodes.add(dataNodeId9);
}
partitions = new HashMap<Long, PartitionId>();
// create three partitions on each mount path
long partitionId = 0;
for (int i = 0; i < dataNodes.get(0).getMountPaths().size(); i++) {
for (int j = 0; j < 3; j++) {
PartitionId id = new MockPartitionId(partitionId, dataNodes, i);
partitions.put(partitionId, id);
partitionId++;
}
}
}
ArrayList<Port> getListOfPorts(int port) {
ArrayList<Port> ports = new ArrayList<Port>();
ports.add(new Port(port, PortType.PLAINTEXT));
return ports;
}
ArrayList<Port> getListOfPorts(int port, int sslPort) {
ArrayList<Port> ports = new ArrayList<Port>();
ports.add(new Port(port, PortType.PLAINTEXT));
ports.add(new Port(sslPort, PortType.SSL));
return ports;
}
private int getPlainTextPort(ArrayList<Port> ports) {
for (Port port : ports) {
if (port.getPortType() == PortType.PLAINTEXT) {
return port.getPort();
}
}
throw new IllegalArgumentException("No PlainText port found ");
}
private MockDataNodeId createDataNode(ArrayList<Port> ports, String datacenter)
throws IOException {
File f = null;
int port = getPlainTextPort(ports);
try {
List<String> mountPaths = new ArrayList<String>(3);
f = File.createTempFile("ambry", ".tmp");
File mountFile1 = new File(f.getParent(), "mountpathfile" + port + "0");
mountFile1.mkdir();
String mountPath1 = mountFile1.getAbsolutePath();
File mountFile2 = new File(f.getParent(), "mountpathfile" + port + "1");
mountFile2.mkdir();
String mountPath2 = mountFile2.getAbsolutePath();
File mountFile3 = new File(f.getParent(), "mountpathfile" + port + "2");
mountFile3.mkdir();
String mountPath3 = mountFile3.getAbsolutePath();
mountPaths.add(mountPath1);
mountPaths.add(mountPath2);
mountPaths.add(mountPath3);
MockDataNodeId dataNode = new MockDataNodeId(ports, mountPaths, datacenter);
return dataNode;
} finally {
if (f != null) {
f.delete();
}
}
}
@Override
public PartitionId getPartitionIdFromStream(DataInputStream stream)
throws IOException {
short version = stream.readShort();
long id = stream.readLong();
return partitions.get(id);
}
@Override
public List<PartitionId> getWritablePartitionIds() {
List<PartitionId> partitionIdList = new ArrayList<PartitionId>();
for (PartitionId partitionId : partitions.values()) {
partitionIdList.add(partitionId);
}
return partitionIdList;
}
@Override
public boolean hasDatacenter(String datacenterName) {
return true;
}
@Override
public DataNodeId getDataNodeId(String hostname, int port) {
for (DataNodeId dataNodeId : dataNodes) {
if (dataNodeId.getHostname().compareTo(hostname) == 0 && dataNodeId.getPort() == port) {
return dataNodeId;
}
}
return null;
}
@Override
public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId) {
ArrayList<ReplicaId> replicaIdsToReturn = new ArrayList<ReplicaId>();
for (PartitionId partitionId : partitions.values()) {
List<ReplicaId> replicaIds = partitionId.getReplicaIds();
for (ReplicaId replicaId : replicaIds) {
if (replicaId.getDataNodeId().getHostname().compareTo(dataNodeId.getHostname()) == 0
&& replicaId.getDataNodeId().getPort() == dataNodeId.getPort()) {
replicaIdsToReturn.add(replicaId);
}
}
}
return replicaIdsToReturn;
}
@Override
public List<DataNodeId> getDataNodeIds() {
return new ArrayList<DataNodeId>(dataNodes);
}
public List<MockDataNodeId> getDataNodes() {
return dataNodes;
}
@Override
public MetricRegistry getMetricRegistry() {
// Each server that calls this mocked interface needs its own metric registry.
return new MetricRegistry();
}
public void cleanup() {
for (PartitionId partitionId : partitions.values()) {
MockPartitionId mockPartition = (MockPartitionId) partitionId;
mockPartition.cleanUp();
}
for (DataNodeId dataNode : dataNodes) {
List<String> mountPaths = ((MockDataNodeId) dataNode).getMountPaths();
for (String mountPath : mountPaths) {
File mountPathDir = new File(mountPath);
for (File file : mountPathDir.listFiles()) {
file.delete();
}
mountPathDir.delete();
}
}
}
public void onReplicaEvent(ReplicaId replicaId, ReplicaEventType event) {
switch (event) {
case Disk_Error:
((MockDiskId) replicaId.getDiskId()).onDiskError();
break;
case Disk_Ok:
((MockDiskId) replicaId.getDiskId()).onDiskOk();
break;
case Node_Timeout:
((MockDataNodeId) replicaId.getDataNodeId()).onNodeTimeout();
break;
case Node_Response:
((MockDataNodeId) replicaId.getDataNodeId()).onNodeResponse();
break;
case Partition_ReadOnly:
((MockPartitionId) replicaId.getPartitionId()).onPartitionReadOnly();
break;
}
}
}
| Fixing name convention
| ambry-clustermap/src/test/java/com.github.ambry.clustermap/MockClusterMap.java | Fixing name convention |
|
Java | apache-2.0 | 1522e1ec8d4c71c2a7e1037c48f91b26fd16e3d1 | 0 | qingsong-xu/picasso,sbp5151/picasso,phileo/picasso,v7lin/picasso,hgl888/picasso,iamyuiwong/picasso,Pannarrow/picasso,myroid/picasso,joansmith/picasso,Gary111/picasso,Jalsoncc/picasso,sephiroth74/picasso,fromsatellite/picasso,tha022/picasso,2017398956/picasso,y97524027/picasso,david-wei/picasso,riezkykenzie/picasso,janzoner/picasso,chwnFlyPig/picasso,Gary111/picasso,MaiMohamedMahmoud/picasso,MaTriXy/picasso,recoilme/picasso,tha022/picasso,jrlinforce/picasso,phileo/picasso,hw-beijing/picasso,huihui4045/picasso,kaoree/picasso,phileo/picasso,laysionqet/picasso,Fablic/picasso,lnylny/picasso,zmywly8866/picasso,chRyNaN/PicassoBase64,RobertHale/picasso,lncosie/picasso,b-cuts/picasso,lypdemo/picasso,longshun/picasso,yauma/picasso,gkmbinh/picasso,chwnFlyPig/picasso,pacificIT/picasso,hw-beijing/picasso,fromsatellite/picasso,lxhxhlw/picasso,jrlinforce/picasso,msandroid/picasso,msandroid/picasso,gkmbinh/picasso,B-A-Ismail/picasso,msandroid/picasso,309746069/picasso,tikiet/picasso,MaiMohamedMahmoud/picasso,recoilme/picasso,NightlyNexus/picasso,zcwk/picasso,xubuhang/picasso,sahilk2579/picasso,sahilk2579/picasso,juner122king/picasso,zmywly8866/picasso,futurobot/picasso,chRyNaN/PicassoBase64,Faner007/picasso,xubuhang/picasso,totomac/picasso,lixiaoyu/picasso,jiasonwang/picasso,ribbon-xx/picasso,zhenguo/picasso,MaTriXy/picasso,sahilk2579/picasso,Pannarrow/picasso,zmywly8866/picasso,BinGoBinBin/picasso,liuguangli/picasso,JGeovani/picasso,lgx0955/picasso,lncosie/picasso,falcon2010/picasso,siwangqishiq/picasso,sephiroth74/picasso,kaoree/picasso,v7lin/picasso,MaTriXy/picasso,y97524027/picasso,litl/picasso,qingsong-xu/picasso,siwangqishiq/picasso,bossvn/picasso,joansmith/picasso,Shinelw/picasso,falcon2010/picasso,zhenguo/picasso,Yestioured/picasso,ribbon-xx/picasso,ruhaly/picasso,wanyueLei/picasso,xgame92/picasso,juner122king/picasso,longshun/picasso,squadrun/picasso,riezkykenzie/picasso,jonathan-caryl/picasso,yauma/picasso,y97524027/picasso,libinbensin/picasso,02110917/picasso,Gary111/picasso,andyao/picasso,junenn/picasso,HossainKhademian/Picasso,Jalsoncc/picasso,HasanAliKaraca/picasso,Fablic/picasso,lichblitz/picasso,JGeovani/picasso,huihui4045/picasso,ackimwilliams/picasso,david-wei/picasso,JohnTsaiAndroid/picasso,litl/picasso,pacificIT/picasso,tikiet/picasso,liuguangli/picasso,amikey/picasso,futurobot/picasso,renatohsc/picasso,BinGoBinBin/picasso,riezkykenzie/picasso,libinbensin/picasso,2017398956/picasso,amikey/picasso,square/picasso,3meters/picasso,paras23brahimi/picasso,viacheslavokolitiy/picasso,tanyixiu/picasso,jonathan-caryl/picasso,thangtc/picasso,Groxx/picasso,zcwk/picasso,3meters/picasso,fhchina/picasso,Fablic/picasso,AKiniyalocts/picasso,bossvn/picasso,lgx0955/picasso,lixiaoyu/picasso,renatohsc/picasso,wangziqiang/picasso,yauma/picasso,lypdemo/picasso,309746069/picasso,Groxx/picasso,longshun/picasso,paras23brahimi/picasso,yulongxiao/picasso,yoube/picasso,B-A-Ismail/picasso,yulongxiao/picasso,ouyangfeng/picasso,colonsong/picasso,jiasonwang/picasso,Algarode/picasso,xubuhang/picasso,Shinelw/picasso,RobertHale/picasso,ribbon-xx/picasso,tikiet/picasso,ackimwilliams/picasso,square/picasso,sowrabh/picasso,qingsong-xu/picasso,JohnTsaiAndroid/picasso,huanting/picasso,squadrun/picasso,wanjingyan001/picasso,shenyiyangvip/picasso,RobertHale/picasso,amikey/picasso,n0x3u5/picasso,Papuh/picasso,CJstar/picasso,chwnFlyPig/picasso,stateofzhao/picasso,v7lin/picasso,viacheslavokolitiy/picasso,bossvn/picasso,wanjingyan001/picasso,ajju4455/picasso,hgl888/picasso,lnylny/picasso,lxhxhlw/picasso,jrlinforce/picasso,309746069/picasso,fromsatellite/picasso,siwangqishiq/picasso,JGeovani/picasso,laysionqet/picasso,junenn/picasso,n0x3u5/picasso,perrystreetsoftware/picasso,HasanAliKaraca/picasso,totomac/picasso,viacheslavokolitiy/picasso,ajju4455/picasso,thangtc/picasso,tha022/picasso,B-A-Ismail/picasso,chRyNaN/PicassoBase64,laysionqet/picasso,ackimwilliams/picasso,lypdemo/picasso,yoube/picasso,jiasonwang/picasso,CJstar/picasso,szucielgp/picasso,fhchina/picasso,pacificIT/picasso,MaiMohamedMahmoud/picasso,lixiaoyu/picasso,sbp5151/picasso,gkmbinh/picasso,wangziqiang/picasso,lnylny/picasso,lgx0955/picasso,ouyangfeng/picasso,b-cuts/picasso,recoilme/picasso,stateofzhao/picasso,yulongxiao/picasso,huihui4045/picasso,iamyuiwong/picasso,joansmith/picasso,2017398956/picasso,Jalsoncc/picasso,sowrabh/picasso,perrystreetsoftware/picasso,Yestioured/picasso,Papuh/picasso,stateofzhao/picasso,renatohsc/picasso,HasanAliKaraca/picasso,lichblitz/picasso,xgame92/picasso,lncosie/picasso,b-cuts/picasso,Algarode/picasso,JohnTsaiAndroid/picasso,mullender/picasso,janzoner/picasso,square/picasso,andyao/picasso,sowrabh/picasso,szucielgp/picasso,shenyiyangvip/picasso,wangjun/picasso,fhchina/picasso,sbp5151/picasso,HossainKhademian/Picasso,lichblitz/picasso,falcon2010/picasso,colonsong/picasso,Shinelw/picasso,Pixate/picasso,3meters/picasso,Pannarrow/picasso,shenyiyangvip/picasso,NightlyNexus/picasso,hw-beijing/picasso,juner122king/picasso,tanyixiu/picasso,AKiniyalocts/picasso,squadrun/picasso,CJstar/picasso,iamyuiwong/picasso,hgl888/picasso,NightlyNexus/picasso,wangjun/picasso,huanting/picasso,mullender/picasso,tomerweller/picasso-debug,square/picasso,szucielgp/picasso,janzoner/picasso,Algarode/picasso,Faner007/picasso,andyao/picasso,tuenti/picasso,junenn/picasso,wanjingyan001/picasso,yoyoyohamapi/picasso,mullender/picasso,AKiniyalocts/picasso,wangziqiang/picasso,thangtc/picasso,tanyixiu/picasso,myroid/picasso,wanyueLei/picasso,yoube/picasso,ouyangfeng/picasso,Yestioured/picasso,liuguangli/picasso,xgame92/picasso,Papuh/picasso,myroid/picasso,huanting/picasso,litl/picasso,BinGoBinBin/picasso,paras23brahimi/picasso,ruhaly/picasso,zhenguo/picasso,david-wei/picasso,ajju4455/picasso,wangjun/picasso,libinbensin/picasso,perrystreetsoftware/picasso,tomerweller/picasso-debug,Faner007/picasso,totomac/picasso,kaoree/picasso,colonsong/picasso,lxhxhlw/picasso,yoyoyohamapi/picasso,wanyueLei/picasso,n0x3u5/picasso,02110917/picasso,yoyoyohamapi/picasso,Pixate/picasso,zcwk/picasso,tuenti/picasso,sephiroth74/picasso,ruhaly/picasso | package com.squareup.picasso;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.squareup.picasso.Loader.Response;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_DISK;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_MEM;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_NETWORK;
public class Picasso {
private static final int RETRY_DELAY = 500;
private static final int REQUEST_COMPLETE = 1;
private static final int REQUEST_RETRY = 2;
// TODO This should be static.
private final Handler handler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
Request request = (Request) msg.obj;
if (request.future.isCancelled()) {
return;
}
switch (msg.what) {
case REQUEST_COMPLETE:
request.complete();
break;
case REQUEST_RETRY:
request.picasso.retry(request);
break;
default:
throw new IllegalArgumentException(
String.format("Unknown handler message received! %d", msg.what));
}
}
};
static Picasso singleton = null;
final Loader loader;
final ExecutorService service;
final Cache memoryCache;
final Map<Object, Request> targetsToRequests;
final boolean debugging;
private Picasso(Loader loader, ExecutorService service, Cache memoryCache, boolean debugging) {
this.loader = loader;
this.service = service;
this.memoryCache = memoryCache;
this.debugging = debugging;
this.targetsToRequests = new WeakHashMap<Object, Request>();
}
public Request.Builder load(String path) {
return new Request.Builder(this, path);
}
void submit(Request request) {
Object target = request.getTarget();
if (target == null) return;
cancelExistingRequest(target);
targetsToRequests.put(target, request);
request.future = service.submit(request);
}
Bitmap run(Request request) {
Bitmap bitmap = loadFromCache(request);
if (bitmap == null) {
bitmap = loadFromStream(request);
}
return bitmap;
}
Bitmap quickMemoryCacheCheck(Object target, String path) {
Bitmap cached = null;
if (memoryCache != null) {
cached = memoryCache.get(path);
}
cancelExistingRequest(target);
return cached;
}
void retry(Request request) {
if (request.retryCancelled) return;
if (request.retryCount > 0) {
request.retryCount--;
submit(request);
} else {
request.error();
}
}
Bitmap decodeStream(InputStream stream, BitmapFactory.Options bitmapOptions) {
if (stream == null) return null;
return BitmapFactory.decodeStream(stream, null, bitmapOptions);
}
private void cancelExistingRequest(Object target) {
Request existing = targetsToRequests.remove(target);
if (existing != null) {
if (!existing.future.isDone()) {
existing.future.cancel(true);
} else if (target != existing.getTarget()) {
existing.retryCancelled = true;
}
}
}
private Bitmap loadFromCache(Request request) {
if (request == null || (TextUtils.isEmpty(request.path))) return null;
String path = request.path;
Bitmap cached = null;
if (memoryCache != null) {
cached = memoryCache.get(path);
if (cached != null) {
if (debugging && request.metrics != null) {
request.metrics.loadedFrom = LOADED_FROM_MEM;
}
request.result = cached;
handler.sendMessage(handler.obtainMessage(REQUEST_COMPLETE, request));
}
}
return cached;
}
private Bitmap loadFromStream(Request request) {
if (request == null || (TextUtils.isEmpty(request.path))) return null;
Bitmap result = null;
Response response = null;
try {
response = loader.load(request.path, request.retryCount == 0);
if (response == null) {
return null;
}
result = decodeStream(response.stream, request.bitmapOptions);
result = transformResult(request, result);
if (debugging) {
if (request.metrics != null) {
request.metrics.loadedFrom = response.cached ? LOADED_FROM_DISK : LOADED_FROM_NETWORK;
}
}
if (result != null && memoryCache != null) {
memoryCache.set(request.key, result);
}
request.result = result;
handler.sendMessage(handler.obtainMessage(REQUEST_COMPLETE, request));
} catch (IOException e) {
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY, request), RETRY_DELAY);
} finally {
if (response != null && response.stream != null) {
try {
response.stream.close();
} catch (IOException ignored) {
}
}
}
return result;
}
private Bitmap transformResult(Request request, Bitmap result) {
List<Transformation> transformations = request.transformations;
if (!transformations.isEmpty()) {
if (transformations.size() == 1) {
result = transformations.get(0).transform(result);
} else {
for (Transformation transformation : transformations) {
result = transformation.transform(result);
}
}
}
return result;
}
public static Picasso with(Context context) {
if (singleton == null) {
singleton = new Builder().loader(new DefaultHttpLoader(context))
.executor(Executors.newFixedThreadPool(3, new PicassoThreadFactory()))
.memoryCache(new LruMemoryCache(context))
.debug()
.build();
}
return singleton;
}
public static class Builder {
private Loader loader;
private ExecutorService service;
private Cache memoryCache;
private boolean debugging;
public Builder loader(Loader loader) {
if (loader == null) {
throw new IllegalArgumentException("Loader may not be null.");
}
if (this.loader != null) {
throw new IllegalStateException("Loader already set.");
}
this.loader = loader;
return this;
}
public Builder executor(ExecutorService executorService) {
if (executorService == null) {
throw new IllegalArgumentException("Executor service may not be null.");
}
if (this.service != null) {
throw new IllegalStateException("Executor service already set.");
}
this.service = executorService;
return this;
}
public Builder memoryCache(Cache memoryCache) {
if (memoryCache == null) {
throw new IllegalArgumentException("Memory cache may not be null.");
}
if (this.memoryCache != null) {
throw new IllegalStateException("Memory cache already set.");
}
this.memoryCache = memoryCache;
return this;
}
public Builder debug() {
debugging = true;
return this;
}
public Picasso build() {
if (loader == null || service == null) {
throw new IllegalStateException("Must provide a Loader and an ExecutorService.");
}
return new Picasso(loader, service, memoryCache, debugging);
}
}
static class PicassoThreadFactory implements ThreadFactory {
private static final AtomicInteger id = new AtomicInteger();
@SuppressWarnings("NullableProblems") public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("picasso-" + id.getAndIncrement());
t.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
return t;
}
}
}
| picasso/src/main/java/com/squareup/picasso/Picasso.java | package com.squareup.picasso;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.squareup.picasso.Loader.Response;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_DISK;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_MEM;
import static com.squareup.picasso.RequestMetrics.LOADED_FROM_NETWORK;
public class Picasso {
private static final int RETRY_DELAY = 500;
private static final int REQUEST_COMPLETE = 1;
private static final int REQUEST_RETRY = 2;
// TODO This should be static.
private final Handler handler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
Request request = (Request) msg.obj;
if (request.future.isCancelled()) {
return;
}
switch (msg.what) {
case REQUEST_COMPLETE:
request.complete();
break;
case REQUEST_RETRY:
request.picasso.retry(request);
break;
default:
throw new IllegalArgumentException(
String.format("Unknown handler message received! %d", msg.what));
}
}
};
static Picasso singleton = null;
final Loader loader;
final ExecutorService service;
final Cache memoryCache;
final Map<Object, Request> targetsToRequests;
final boolean debugging;
private Picasso(Loader loader, ExecutorService service, Cache memoryCache, boolean debugging) {
this.loader = loader;
this.service = service;
this.memoryCache = memoryCache;
this.debugging = debugging;
this.targetsToRequests = new WeakHashMap<Object, Request>();
}
public Request.Builder load(String path) {
return new Request.Builder(this, path);
}
void submit(Request request) {
Object target = request.getTarget();
if (target == null) return;
cancelExistingRequest(target);
targetsToRequests.put(target, request);
request.future = service.submit(request);
}
Bitmap run(Request request) {
Bitmap bitmap = loadFromCache(request);
if (bitmap == null) {
bitmap = loadFromStream(request);
}
return bitmap;
}
Bitmap quickMemoryCacheCheck(Object target, String path) {
Bitmap cached = null;
if (memoryCache != null) {
cached = memoryCache.get(path);
}
cancelExistingRequest(target);
return cached;
}
void retry(Request request) {
if (request.retryCancelled) return;
if (request.retryCount > 0) {
request.retryCount--;
submit(request);
} else {
request.error();
}
}
Bitmap decodeStream(InputStream stream, BitmapFactory.Options bitmapOptions) {
if (stream == null) return null;
return BitmapFactory.decodeStream(stream, null, bitmapOptions);
}
private void cancelExistingRequest(Object target) {
Request existing = targetsToRequests.remove(target);
if (existing != null) {
if (!existing.future.isDone()) {
existing.future.cancel(true);
} else if (target != existing.getTarget()) {
existing.retryCancelled = true;
}
}
}
private Bitmap loadFromCache(Request request) {
if (request == null || (TextUtils.isEmpty(request.path))) return null;
String path = request.path;
Bitmap cached = null;
if (memoryCache != null) {
cached = memoryCache.get(path);
if (cached != null) {
if (debugging && request.metrics != null) {
request.metrics.loadedFrom = LOADED_FROM_MEM;
}
request.result = cached;
handler.sendMessage(handler.obtainMessage(REQUEST_COMPLETE, request));
}
}
return cached;
}
private Bitmap loadFromStream(Request request) {
if (request == null || (TextUtils.isEmpty(request.path))) return null;
Bitmap result = null;
Response response = null;
try {
response = loader.load(request.path, request.retryCount == 0);
if (response == null) {
return null;
}
result = decodeStream(response.stream, request.bitmapOptions);
result = transformResult(request, result);
if (debugging) {
if (request.metrics != null) {
request.metrics.loadedFrom = response.cached ? LOADED_FROM_DISK : LOADED_FROM_NETWORK;
}
}
if (result != null && memoryCache != null) {
memoryCache.set(request.key, result);
}
request.result = result;
handler.sendMessage(handler.obtainMessage(REQUEST_COMPLETE, request));
} catch (IOException e) {
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY, request), RETRY_DELAY);
} finally {
if (response != null && response.stream != null) {
try {
response.stream.close();
} catch (IOException ignored) {
}
}
}
return result;
}
private Bitmap transformResult(Request request, Bitmap result) {
List<Transformation> transformations = request.transformations;
if (!transformations.isEmpty()) {
if (transformations.size() == 1) {
result = transformations.get(0).transform(result);
} else {
for (Transformation transformation : transformations) {
result = transformation.transform(result);
}
}
}
return result;
}
public static Picasso with(Context context) {
if (singleton == null) {
singleton = new Builder().loader(new DefaultHttpLoader(context))
.executor(Executors.newFixedThreadPool(3, new PicassoThreadFactory()))
.memoryCache(new LruMemoryCache(context))
.debug()
.build();
}
return singleton;
}
public static class Builder {
private Loader loader;
private ExecutorService service;
private Cache memoryCache;
private boolean debugging;
public Builder loader(Loader loader) {
if (loader == null) {
throw new IllegalArgumentException("Loader may not be null.");
}
if (this.loader != null) {
throw new IllegalStateException("Loader already set.");
}
this.loader = loader;
return this;
}
public Builder executor(ExecutorService executorService) {
if (executorService == null) {
throw new IllegalArgumentException("Executor service may not be null.");
}
if (this.service != null) {
throw new IllegalStateException("Exector service already set.");
}
this.service = executorService;
return this;
}
public Builder memoryCache(Cache memoryCache) {
if (memoryCache == null) {
throw new IllegalArgumentException("Memory cache may not be null.");
}
if (this.memoryCache != null) {
throw new IllegalStateException("Memory cache already set.");
}
this.memoryCache = memoryCache;
return this;
}
public Builder debug() {
debugging = true;
return this;
}
public Picasso build() {
if (loader == null || service == null) {
throw new IllegalStateException("Must provide a Loader and an ExecutorService.");
}
return new Picasso(loader, service, memoryCache, debugging);
}
}
static class PicassoThreadFactory implements ThreadFactory {
private static final AtomicInteger id = new AtomicInteger();
@SuppressWarnings("NullableProblems") public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("picasso-" + id.getAndIncrement());
t.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
return t;
}
}
}
| Fix typo.
| picasso/src/main/java/com/squareup/picasso/Picasso.java | Fix typo. |
|
Java | apache-2.0 | d126558dec790f5d1bd06b13806fba723336869b | 0 | pranavraman/elasticsearch,lmtwga/elasticsearch,onegambler/elasticsearch,Widen/elasticsearch,djschny/elasticsearch,masaruh/elasticsearch,fekaputra/elasticsearch,hechunwen/elasticsearch,cnfire/elasticsearch-1,qwerty4030/elasticsearch,vvcephei/elasticsearch,Liziyao/elasticsearch,polyfractal/elasticsearch,jw0201/elastic,coding0011/elasticsearch,hanswang/elasticsearch,brwe/elasticsearch,brwe/elasticsearch,scorpionvicky/elasticsearch,mute/elasticsearch,luiseduardohdbackup/elasticsearch,nazarewk/elasticsearch,iacdingping/elasticsearch,likaiwalkman/elasticsearch,sjohnr/elasticsearch,Ansh90/elasticsearch,mohsinh/elasticsearch,martinstuga/elasticsearch,Kakakakakku/elasticsearch,AleksKochev/elasticsearch,huanzhong/elasticsearch,elasticdog/elasticsearch,codebunt/elasticsearch,dataduke/elasticsearch,wittyameta/elasticsearch,kcompher/elasticsearch,wayeast/elasticsearch,smflorentino/elasticsearch,janmejay/elasticsearch,queirozfcom/elasticsearch,awislowski/elasticsearch,bawse/elasticsearch,IanvsPoplicola/elasticsearch,a2lin/elasticsearch,Kakakakakku/elasticsearch,ThalaivaStars/OrgRepo1,vroyer/elassandra,Helen-Zhao/elasticsearch,skearns64/elasticsearch,dongjoon-hyun/elasticsearch,caengcjd/elasticsearch,Siddartha07/elasticsearch,EasonYi/elasticsearch,djschny/elasticsearch,Siddartha07/elasticsearch,vingupta3/elasticsearch,AshishThakur/elasticsearch,Stacey-Gammon/elasticsearch,jango2015/elasticsearch,khiraiwa/elasticsearch,chrismwendt/elasticsearch,scorpionvicky/elasticsearch,Flipkart/elasticsearch,jsgao0/elasticsearch,Siddartha07/elasticsearch,mohsinh/elasticsearch,koxa29/elasticsearch,rajanm/elasticsearch,javachengwc/elasticsearch,elasticdog/elasticsearch,mm0/elasticsearch,henakamaMSFT/elasticsearch,F0lha/elasticsearch,jchampion/elasticsearch,rlugojr/elasticsearch,SergVro/elasticsearch,SergVro/elasticsearch,franklanganke/elasticsearch,spiegela/elasticsearch,episerver/elasticsearch,hydro2k/elasticsearch,skearns64/elasticsearch,JackyMai/elasticsearch,knight1128/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,nezirus/elasticsearch,gmarz/elasticsearch,janmejay/elasticsearch,golubev/elasticsearch,martinstuga/elasticsearch,kevinkluge/elasticsearch,dataduke/elasticsearch,mrorii/elasticsearch,iamjakob/elasticsearch,mohit/elasticsearch,fooljohnny/elasticsearch,markwalkom/elasticsearch,btiernay/elasticsearch,truemped/elasticsearch,amaliujia/elasticsearch,jeteve/elasticsearch,Fsero/elasticsearch,ajhalani/elasticsearch,nilabhsagar/elasticsearch,rento19962/elasticsearch,salyh/elasticsearch,jpountz/elasticsearch,phani546/elasticsearch,lzo/elasticsearch-1,myelin/elasticsearch,boliza/elasticsearch,wbowling/elasticsearch,phani546/elasticsearch,ajhalani/elasticsearch,codebunt/elasticsearch,Ansh90/elasticsearch,kevinkluge/elasticsearch,vrkansagara/elasticsearch,jango2015/elasticsearch,PhaedrusTheGreek/elasticsearch,raishiv/elasticsearch,humandb/elasticsearch,pranavraman/elasticsearch,markharwood/elasticsearch,kimimj/elasticsearch,opendatasoft/elasticsearch,javachengwc/elasticsearch,mohsinh/elasticsearch,mjhennig/elasticsearch,winstonewert/elasticsearch,Collaborne/elasticsearch,KimTaehee/elasticsearch,gingerwizard/elasticsearch,hirdesh2008/elasticsearch,yynil/elasticsearch,kenshin233/elasticsearch,mikemccand/elasticsearch,sauravmondallive/elasticsearch,StefanGor/elasticsearch,chrismwendt/elasticsearch,snikch/elasticsearch,alexkuk/elasticsearch,ImpressTV/elasticsearch,mnylen/elasticsearch,xuzha/elasticsearch,gmarz/elasticsearch,maddin2016/elasticsearch,likaiwalkman/elasticsearch,achow/elasticsearch,markharwood/elasticsearch,vietlq/elasticsearch,MisterAndersen/elasticsearch,aglne/elasticsearch,sauravmondallive/elasticsearch,caengcjd/elasticsearch,brandonkearby/elasticsearch,glefloch/elasticsearch,smflorentino/elasticsearch,winstonewert/elasticsearch,easonC/elasticsearch,koxa29/elasticsearch,LewayneNaidoo/elasticsearch,henakamaMSFT/elasticsearch,vroyer/elassandra,wbowling/elasticsearch,LeoYao/elasticsearch,sjohnr/elasticsearch,kkirsche/elasticsearch,luiseduardohdbackup/elasticsearch,djschny/elasticsearch,pozhidaevak/elasticsearch,kevinkluge/elasticsearch,zhaocloud/elasticsearch,KimTaehee/elasticsearch,sauravmondallive/elasticsearch,ImpressTV/elasticsearch,hirdesh2008/elasticsearch,sdauletau/elasticsearch,zhaocloud/elasticsearch,andrestc/elasticsearch,MisterAndersen/elasticsearch,jpountz/elasticsearch,masaruh/elasticsearch,mbrukman/elasticsearch,wittyameta/elasticsearch,martinstuga/elasticsearch,uschindler/elasticsearch,javachengwc/elasticsearch,mjhennig/elasticsearch,Clairebi/ElasticsearchClone,overcome/elasticsearch,alexkuk/elasticsearch,libosu/elasticsearch,drewr/elasticsearch,wuranbo/elasticsearch,kalburgimanjunath/elasticsearch,markllama/elasticsearch,pozhidaevak/elasticsearch,ESamir/elasticsearch,uschindler/elasticsearch,micpalmia/elasticsearch,infusionsoft/elasticsearch,Rygbee/elasticsearch,fred84/elasticsearch,tahaemin/elasticsearch,uboness/elasticsearch,jimhooker2002/elasticsearch,spiegela/elasticsearch,alexksikes/elasticsearch,himanshuag/elasticsearch,hanst/elasticsearch,sc0ttkclark/elasticsearch,humandb/elasticsearch,lzo/elasticsearch-1,iantruslove/elasticsearch,lmenezes/elasticsearch,TonyChai24/ESSource,petabytedata/elasticsearch,kalimatas/elasticsearch,yynil/elasticsearch,naveenhooda2000/elasticsearch,andrestc/elasticsearch,apepper/elasticsearch,AshishThakur/elasticsearch,MaineC/elasticsearch,MichaelLiZhou/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,JervyShi/elasticsearch,linglaiyao1314/elasticsearch,milodky/elasticsearch,zhaocloud/elasticsearch,Charlesdong/elasticsearch,martinstuga/elasticsearch,boliza/elasticsearch,gmarz/elasticsearch,beiske/elasticsearch,infusionsoft/elasticsearch,MjAbuz/elasticsearch,Liziyao/elasticsearch,dongjoon-hyun/elasticsearch,yynil/elasticsearch,pritishppai/elasticsearch,rmuir/elasticsearch,dongjoon-hyun/elasticsearch,jango2015/elasticsearch,VukDukic/elasticsearch,franklanganke/elasticsearch,micpalmia/elasticsearch,jaynblue/elasticsearch,StefanGor/elasticsearch,hanswang/elasticsearch,jw0201/elastic,pranavraman/elasticsearch,petmit/elasticsearch,adrianbk/elasticsearch,ivansun1010/elasticsearch,gfyoung/elasticsearch,LeoYao/elasticsearch,snikch/elasticsearch,smflorentino/elasticsearch,jchampion/elasticsearch,kimimj/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,amit-shar/elasticsearch,liweinan0423/elasticsearch,jimhooker2002/elasticsearch,uschindler/elasticsearch,rhoml/elasticsearch,javachengwc/elasticsearch,JackyMai/elasticsearch,MisterAndersen/elasticsearch,mikemccand/elasticsearch,iacdingping/elasticsearch,rlugojr/elasticsearch,boliza/elasticsearch,pablocastro/elasticsearch,amaliujia/elasticsearch,mjhennig/elasticsearch,ThiagoGarciaAlves/elasticsearch,sposam/elasticsearch,PhaedrusTheGreek/elasticsearch,likaiwalkman/elasticsearch,diendt/elasticsearch,nilabhsagar/elasticsearch,LeoYao/elasticsearch,HonzaKral/elasticsearch,hafkensite/elasticsearch,alexkuk/elasticsearch,clintongormley/elasticsearch,mbrukman/elasticsearch,djschny/elasticsearch,hafkensite/elasticsearch,chrismwendt/elasticsearch,weipinghe/elasticsearch,AndreKR/elasticsearch,caengcjd/elasticsearch,abibell/elasticsearch,sposam/elasticsearch,rlugojr/elasticsearch,mm0/elasticsearch,btiernay/elasticsearch,socialrank/elasticsearch,AndreKR/elasticsearch,palecur/elasticsearch,Collaborne/elasticsearch,yongminxia/elasticsearch,liweinan0423/elasticsearch,VukDukic/elasticsearch,areek/elasticsearch,MjAbuz/elasticsearch,socialrank/elasticsearch,spiegela/elasticsearch,nrkkalyan/elasticsearch,Shepard1212/elasticsearch,bestwpw/elasticsearch,abibell/elasticsearch,artnowo/elasticsearch,avikurapati/elasticsearch,ulkas/elasticsearch,kkirsche/elasticsearch,Rygbee/elasticsearch,i-am-Nathan/elasticsearch,strapdata/elassandra5-rc,wayeast/elasticsearch,elancom/elasticsearch,zeroctu/elasticsearch,lydonchandra/elasticsearch,huanzhong/elasticsearch,shreejay/elasticsearch,sposam/elasticsearch,strapdata/elassandra-test,sjohnr/elasticsearch,HarishAtGitHub/elasticsearch,polyfractal/elasticsearch,mcku/elasticsearch,kalimatas/elasticsearch,sneivandt/elasticsearch,karthikjaps/elasticsearch,markwalkom/elasticsearch,raishiv/elasticsearch,vrkansagara/elasticsearch,MjAbuz/elasticsearch,Helen-Zhao/elasticsearch,kimchy/elasticsearch,rajanm/elasticsearch,strapdata/elassandra,vietlq/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,tcucchietti/elasticsearch,Uiho/elasticsearch,strapdata/elassandra,davidvgalbraith/elasticsearch,areek/elasticsearch,nknize/elasticsearch,palecur/elasticsearch,socialrank/elasticsearch,vingupta3/elasticsearch,EasonYi/elasticsearch,wimvds/elasticsearch,dongaihua/highlight-elasticsearch,aparo/elasticsearch,acchen97/elasticsearch,nellicus/elasticsearch,dataduke/elasticsearch,robin13/elasticsearch,PhaedrusTheGreek/elasticsearch,s1monw/elasticsearch,obourgain/elasticsearch,SergVro/elasticsearch,jpountz/elasticsearch,Helen-Zhao/elasticsearch,bawse/elasticsearch,combinatorist/elasticsearch,Rygbee/elasticsearch,mnylen/elasticsearch,vvcephei/elasticsearch,zkidkid/elasticsearch,sarwarbhuiyan/elasticsearch,jango2015/elasticsearch,JSCooke/elasticsearch,ImpressTV/elasticsearch,thecocce/elasticsearch,ydsakyclguozi/elasticsearch,vroyer/elasticassandra,Widen/elasticsearch,combinatorist/elasticsearch,opendatasoft/elasticsearch,tkssharma/elasticsearch,golubev/elasticsearch,Clairebi/ElasticsearchClone,mnylen/elasticsearch,bestwpw/elasticsearch,janmejay/elasticsearch,nezirus/elasticsearch,JervyShi/elasticsearch,fubuki/elasticsearch,artnowo/elasticsearch,humandb/elasticsearch,janmejay/elasticsearch,NBSW/elasticsearch,bestwpw/elasticsearch,mortonsykes/elasticsearch,queirozfcom/elasticsearch,masterweb121/elasticsearch,YosuaMichael/elasticsearch,feiqitian/elasticsearch,onegambler/elasticsearch,peschlowp/elasticsearch,himanshuag/elasticsearch,weipinghe/elasticsearch,bestwpw/elasticsearch,vietlq/elasticsearch,yongminxia/elasticsearch,mrorii/elasticsearch,ivansun1010/elasticsearch,anti-social/elasticsearch,achow/elasticsearch,tkssharma/elasticsearch,MjAbuz/elasticsearch,trangvh/elasticsearch,adrianbk/elasticsearch,micpalmia/elasticsearch,jimczi/elasticsearch,tkssharma/elasticsearch,MichaelLiZhou/elasticsearch,skearns64/elasticsearch,huanzhong/elasticsearch,Siddartha07/elasticsearch,wuranbo/elasticsearch,drewr/elasticsearch,dataduke/elasticsearch,MisterAndersen/elasticsearch,smflorentino/elasticsearch,ricardocerq/elasticsearch,zhaocloud/elasticsearch,btiernay/elasticsearch,myelin/elasticsearch,alexbrasetvik/elasticsearch,uboness/elasticsearch,ivansun1010/elasticsearch,mnylen/elasticsearch,himanshuag/elasticsearch,alexkuk/elasticsearch,chirilo/elasticsearch,huypx1292/elasticsearch,mikemccand/elasticsearch,xuzha/elasticsearch,lchennup/elasticsearch,kunallimaye/elasticsearch,wayeast/elasticsearch,LeoYao/elasticsearch,Charlesdong/elasticsearch,easonC/elasticsearch,nazarewk/elasticsearch,PhaedrusTheGreek/elasticsearch,dongaihua/highlight-elasticsearch,s1monw/elasticsearch,snikch/elasticsearch,jbertouch/elasticsearch,kcompher/elasticsearch,ThalaivaStars/OrgRepo1,JSCooke/elasticsearch,rmuir/elasticsearch,koxa29/elasticsearch,sc0ttkclark/elasticsearch,gmarz/elasticsearch,luiseduardohdbackup/elasticsearch,yongminxia/elasticsearch,loconsolutions/elasticsearch,LeoYao/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,umeshdangat/elasticsearch,schonfeld/elasticsearch,markharwood/elasticsearch,fekaputra/elasticsearch,Stacey-Gammon/elasticsearch,ajhalani/elasticsearch,rento19962/elasticsearch,Charlesdong/elasticsearch,mmaracic/elasticsearch,kcompher/elasticsearch,lzo/elasticsearch-1,tkssharma/elasticsearch,pritishppai/elasticsearch,tebriel/elasticsearch,linglaiyao1314/elasticsearch,KimTaehee/elasticsearch,JSCooke/elasticsearch,peschlowp/elasticsearch,rmuir/elasticsearch,elancom/elasticsearch,qwerty4030/elasticsearch,mm0/elasticsearch,gingerwizard/elasticsearch,kunallimaye/elasticsearch,ImpressTV/elasticsearch,zeroctu/elasticsearch,humandb/elasticsearch,davidvgalbraith/elasticsearch,strapdata/elassandra-test,peschlowp/elasticsearch,wangyuxue/elasticsearch,Chhunlong/elasticsearch,nellicus/elasticsearch,scottsom/elasticsearch,wangtuo/elasticsearch,infusionsoft/elasticsearch,queirozfcom/elasticsearch,pritishppai/elasticsearch,milodky/elasticsearch,amaliujia/elasticsearch,winstonewert/elasticsearch,kaneshin/elasticsearch,maddin2016/elasticsearch,Brijeshrpatel9/elasticsearch,abibell/elasticsearch,yuy168/elasticsearch,MjAbuz/elasticsearch,fred84/elasticsearch,kevinkluge/elasticsearch,mute/elasticsearch,AleksKochev/elasticsearch,nazarewk/elasticsearch,dantuffery/elasticsearch,onegambler/elasticsearch,zhiqinghuang/elasticsearch,cwurm/elasticsearch,schonfeld/elasticsearch,onegambler/elasticsearch,fekaputra/elasticsearch,Ansh90/elasticsearch,hirdesh2008/elasticsearch,hanswang/elasticsearch,hydro2k/elasticsearch,TonyChai24/ESSource,knight1128/elasticsearch,s1monw/elasticsearch,schonfeld/elasticsearch,khiraiwa/elasticsearch,henakamaMSFT/elasticsearch,fforbeck/elasticsearch,szroland/elasticsearch,areek/elasticsearch,opendatasoft/elasticsearch,MetSystem/elasticsearch,jimhooker2002/elasticsearch,kaneshin/elasticsearch,masterweb121/elasticsearch,achow/elasticsearch,Rygbee/elasticsearch,MichaelLiZhou/elasticsearch,davidvgalbraith/elasticsearch,amit-shar/elasticsearch,boliza/elasticsearch,gfyoung/elasticsearch,thecocce/elasticsearch,robin13/elasticsearch,truemped/elasticsearch,nellicus/elasticsearch,fekaputra/elasticsearch,libosu/elasticsearch,ricardocerq/elasticsearch,Chhunlong/elasticsearch,mohsinh/elasticsearch,Widen/elasticsearch,wuranbo/elasticsearch,mcku/elasticsearch,pritishppai/elasticsearch,Stacey-Gammon/elasticsearch,markwalkom/elasticsearch,obourgain/elasticsearch,wittyameta/elasticsearch,lchennup/elasticsearch,ricardocerq/elasticsearch,jeteve/elasticsearch,Stacey-Gammon/elasticsearch,nezirus/elasticsearch,sjohnr/elasticsearch,fekaputra/elasticsearch,Brijeshrpatel9/elasticsearch,lks21c/elasticsearch,mohit/elasticsearch,rlugojr/elasticsearch,jaynblue/elasticsearch,uschindler/elasticsearch,mm0/elasticsearch,IanvsPoplicola/elasticsearch,Kakakakakku/elasticsearch,F0lha/elasticsearch,thecocce/elasticsearch,Clairebi/ElasticsearchClone,sreeramjayan/elasticsearch,dpursehouse/elasticsearch,elancom/elasticsearch,davidvgalbraith/elasticsearch,xuzha/elasticsearch,PhaedrusTheGreek/elasticsearch,sneivandt/elasticsearch,mikemccand/elasticsearch,ESamir/elasticsearch,jimhooker2002/elasticsearch,naveenhooda2000/elasticsearch,LeoYao/elasticsearch,NBSW/elasticsearch,episerver/elasticsearch,iacdingping/elasticsearch,apepper/elasticsearch,obourgain/elasticsearch,mbrukman/elasticsearch,nilabhsagar/elasticsearch,Brijeshrpatel9/elasticsearch,skearns64/elasticsearch,abhijitiitr/es,adrianbk/elasticsearch,mapr/elasticsearch,clintongormley/elasticsearch,gingerwizard/elasticsearch,jsgao0/elasticsearch,sneivandt/elasticsearch,brandonkearby/elasticsearch,naveenhooda2000/elasticsearch,alexshadow007/elasticsearch,strapdata/elassandra,kalburgimanjunath/elasticsearch,kalburgimanjunath/elasticsearch,wangyuxue/elasticsearch,maddin2016/elasticsearch,cnfire/elasticsearch-1,yanjunh/elasticsearch,hechunwen/elasticsearch,AndreKR/elasticsearch,dantuffery/elasticsearch,kcompher/elasticsearch,mjhennig/elasticsearch,nellicus/elasticsearch,dylan8902/elasticsearch,gingerwizard/elasticsearch,lmtwga/elasticsearch,yynil/elasticsearch,alexkuk/elasticsearch,henakamaMSFT/elasticsearch,franklanganke/elasticsearch,pranavraman/elasticsearch,Asimov4/elasticsearch,tebriel/elasticsearch,ajhalani/elasticsearch,winstonewert/elasticsearch,vroyer/elassandra,lzo/elasticsearch-1,alexshadow007/elasticsearch,fubuki/elasticsearch,marcuswr/elasticsearch-dateline,masaruh/elasticsearch,bawse/elasticsearch,ZTE-PaaS/elasticsearch,ouyangkongtong/elasticsearch,ivansun1010/elasticsearch,NBSW/elasticsearch,lightslife/elasticsearch,petmit/elasticsearch,andrejserafim/elasticsearch,a2lin/elasticsearch,clintongormley/elasticsearch,nomoa/elasticsearch,fernandozhu/elasticsearch,Flipkart/elasticsearch,geidies/elasticsearch,sauravmondallive/elasticsearch,btiernay/elasticsearch,mute/elasticsearch,amaliujia/elasticsearch,glefloch/elasticsearch,xpandan/elasticsearch,acchen97/elasticsearch,andrewvc/elasticsearch,truemped/elasticsearch,ckclark/elasticsearch,tsohil/elasticsearch,zhiqinghuang/elasticsearch,avikurapati/elasticsearch,MetSystem/elasticsearch,libosu/elasticsearch,SergVro/elasticsearch,Brijeshrpatel9/elasticsearch,milodky/elasticsearch,caengcjd/elasticsearch,martinstuga/elasticsearch,vroyer/elasticassandra,Fsero/elasticsearch,elasticdog/elasticsearch,shreejay/elasticsearch,codebunt/elasticsearch,karthikjaps/elasticsearch,lzo/elasticsearch-1,gmarz/elasticsearch,MetSystem/elasticsearch,PhaedrusTheGreek/elasticsearch,AleksKochev/elasticsearch,iantruslove/elasticsearch,KimTaehee/elasticsearch,C-Bish/elasticsearch,sposam/elasticsearch,winstonewert/elasticsearch,raishiv/elasticsearch,pablocastro/elasticsearch,Chhunlong/elasticsearch,ESamir/elasticsearch,socialrank/elasticsearch,yanjunh/elasticsearch,snikch/elasticsearch,yynil/elasticsearch,xingguang2013/elasticsearch,fooljohnny/elasticsearch,janmejay/elasticsearch,jaynblue/elasticsearch,mute/elasticsearch,kalburgimanjunath/elasticsearch,himanshuag/elasticsearch,fernandozhu/elasticsearch,Shekharrajak/elasticsearch,masterweb121/elasticsearch,petabytedata/elasticsearch,jimczi/elasticsearch,nomoa/elasticsearch,LewayneNaidoo/elasticsearch,ivansun1010/elasticsearch,anti-social/elasticsearch,camilojd/elasticsearch,geidies/elasticsearch,hechunwen/elasticsearch,salyh/elasticsearch,thecocce/elasticsearch,andrejserafim/elasticsearch,Uiho/elasticsearch,combinatorist/elasticsearch,vrkansagara/elasticsearch,overcome/elasticsearch,scorpionvicky/elasticsearch,jprante/elasticsearch,adrianbk/elasticsearch,lightslife/elasticsearch,wayeast/elasticsearch,vorce/es-metrics,strapdata/elassandra-test,szroland/elasticsearch,overcome/elasticsearch,trangvh/elasticsearch,kalburgimanjunath/elasticsearch,PhaedrusTheGreek/elasticsearch,opendatasoft/elasticsearch,fubuki/elasticsearch,HarishAtGitHub/elasticsearch,iamjakob/elasticsearch,sdauletau/elasticsearch,hanst/elasticsearch,hirdesh2008/elasticsearch,Brijeshrpatel9/elasticsearch,jw0201/elastic,alexbrasetvik/elasticsearch,markwalkom/elasticsearch,andrestc/elasticsearch,weipinghe/elasticsearch,truemped/elasticsearch,anti-social/elasticsearch,tahaemin/elasticsearch,markllama/elasticsearch,Flipkart/elasticsearch,yuy168/elasticsearch,njlawton/elasticsearch,loconsolutions/elasticsearch,jpountz/elasticsearch,pranavraman/elasticsearch,wayeast/elasticsearch,AshishThakur/elasticsearch,springning/elasticsearch,s1monw/elasticsearch,nrkkalyan/elasticsearch,mcku/elasticsearch,aglne/elasticsearch,polyfractal/elasticsearch,amit-shar/elasticsearch,abhijitiitr/es,jeteve/elasticsearch,C-Bish/elasticsearch,wittyameta/elasticsearch,fforbeck/elasticsearch,tahaemin/elasticsearch,MetSystem/elasticsearch,andrewvc/elasticsearch,nomoa/elasticsearch,apepper/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,easonC/elasticsearch,fubuki/elasticsearch,truemped/elasticsearch,markllama/elasticsearch,AleksKochev/elasticsearch,lmtwga/elasticsearch,btiernay/elasticsearch,abibell/elasticsearch,jango2015/elasticsearch,ulkas/elasticsearch,ouyangkongtong/elasticsearch,kcompher/elasticsearch,gfyoung/elasticsearch,abhijitiitr/es,ckclark/elasticsearch,infusionsoft/elasticsearch,iacdingping/elasticsearch,queirozfcom/elasticsearch,AleksKochev/elasticsearch,zhiqinghuang/elasticsearch,djschny/elasticsearch,robin13/elasticsearch,rajanm/elasticsearch,vvcephei/elasticsearch,Asimov4/elasticsearch,thecocce/elasticsearch,jchampion/elasticsearch,jpountz/elasticsearch,Liziyao/elasticsearch,fooljohnny/elasticsearch,janmejay/elasticsearch,abhijitiitr/es,Widen/elasticsearch,sreeramjayan/elasticsearch,trangvh/elasticsearch,cnfire/elasticsearch-1,onegambler/elasticsearch,sarwarbhuiyan/elasticsearch,qwerty4030/elasticsearch,kevinkluge/elasticsearch,TonyChai24/ESSource,jbertouch/elasticsearch,GlenRSmith/elasticsearch,mjason3/elasticsearch,elancom/elasticsearch,nilabhsagar/elasticsearch,wenpos/elasticsearch,lmenezes/elasticsearch,linglaiyao1314/elasticsearch,marcuswr/elasticsearch-dateline,jeteve/elasticsearch,Shepard1212/elasticsearch,kalburgimanjunath/elasticsearch,nknize/elasticsearch,phani546/elasticsearch,aglne/elasticsearch,Liziyao/elasticsearch,StefanGor/elasticsearch,JackyMai/elasticsearch,martinstuga/elasticsearch,sdauletau/elasticsearch,overcome/elasticsearch,StefanGor/elasticsearch,MjAbuz/elasticsearch,hirdesh2008/elasticsearch,cwurm/elasticsearch,milodky/elasticsearch,achow/elasticsearch,VukDukic/elasticsearch,fubuki/elasticsearch,alexshadow007/elasticsearch,wayeast/elasticsearch,awislowski/elasticsearch,mrorii/elasticsearch,markllama/elasticsearch,Shekharrajak/elasticsearch,overcome/elasticsearch,heng4fun/elasticsearch,slavau/elasticsearch,wimvds/elasticsearch,mkis-/elasticsearch,Asimov4/elasticsearch,linglaiyao1314/elasticsearch,mkis-/elasticsearch,aparo/elasticsearch,Asimov4/elasticsearch,Widen/elasticsearch,aglne/elasticsearch,Chhunlong/elasticsearch,amit-shar/elasticsearch,umeshdangat/elasticsearch,sdauletau/elasticsearch,HarishAtGitHub/elasticsearch,dpursehouse/elasticsearch,hafkensite/elasticsearch,ckclark/elasticsearch,heng4fun/elasticsearch,mjhennig/elasticsearch,jw0201/elastic,polyfractal/elasticsearch,schonfeld/elasticsearch,apepper/elasticsearch,strapdata/elassandra5-rc,YosuaMichael/elasticsearch,kubum/elasticsearch,LeoYao/elasticsearch,scottsom/elasticsearch,F0lha/elasticsearch,tcucchietti/elasticsearch,easonC/elasticsearch,mjason3/elasticsearch,aparo/elasticsearch,18098924759/elasticsearch,kevinkluge/elasticsearch,abibell/elasticsearch,likaiwalkman/elasticsearch,nrkkalyan/elasticsearch,beiske/elasticsearch,dpursehouse/elasticsearch,franklanganke/elasticsearch,MetSystem/elasticsearch,weipinghe/elasticsearch,alexksikes/elasticsearch,hafkensite/elasticsearch,amaliujia/elasticsearch,combinatorist/elasticsearch,Ansh90/elasticsearch,mkis-/elasticsearch,lmtwga/elasticsearch,sarwarbhuiyan/elasticsearch,kingaj/elasticsearch,cwurm/elasticsearch,kimchy/elasticsearch,umeshdangat/elasticsearch,wenpos/elasticsearch,javachengwc/elasticsearch,scottsom/elasticsearch,mgalushka/elasticsearch,18098924759/elasticsearch,hafkensite/elasticsearch,pablocastro/elasticsearch,kubum/elasticsearch,Shekharrajak/elasticsearch,luiseduardohdbackup/elasticsearch,wbowling/elasticsearch,liweinan0423/elasticsearch,slavau/elasticsearch,Ansh90/elasticsearch,18098924759/elasticsearch,pablocastro/elasticsearch,mmaracic/elasticsearch,jw0201/elastic,sreeramjayan/elasticsearch,sc0ttkclark/elasticsearch,JSCooke/elasticsearch,mm0/elasticsearch,MichaelLiZhou/elasticsearch,Flipkart/elasticsearch,mkis-/elasticsearch,lzo/elasticsearch-1,xingguang2013/elasticsearch,kunallimaye/elasticsearch,yuy168/elasticsearch,petabytedata/elasticsearch,lydonchandra/elasticsearch,andrejserafim/elasticsearch,alexbrasetvik/elasticsearch,nilabhsagar/elasticsearch,awislowski/elasticsearch,dongjoon-hyun/elasticsearch,lks21c/elasticsearch,luiseduardohdbackup/elasticsearch,zeroctu/elasticsearch,himanshuag/elasticsearch,kaneshin/elasticsearch,huanzhong/elasticsearch,truemped/elasticsearch,combinatorist/elasticsearch,codebunt/elasticsearch,cnfire/elasticsearch-1,springning/elasticsearch,petabytedata/elasticsearch,acchen97/elasticsearch,sreeramjayan/elasticsearch,elasticdog/elasticsearch,dataduke/elasticsearch,sscarduzio/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,dataduke/elasticsearch,Brijeshrpatel9/elasticsearch,slavau/elasticsearch,chirilo/elasticsearch,hydro2k/elasticsearch,F0lha/elasticsearch,zhiqinghuang/elasticsearch,TonyChai24/ESSource,hanst/elasticsearch,libosu/elasticsearch,gfyoung/elasticsearch,Chhunlong/elasticsearch,apepper/elasticsearch,lchennup/elasticsearch,strapdata/elassandra,ouyangkongtong/elasticsearch,avikurapati/elasticsearch,ydsakyclguozi/elasticsearch,kenshin233/elasticsearch,xingguang2013/elasticsearch,18098924759/elasticsearch,Ansh90/elasticsearch,hafkensite/elasticsearch,petabytedata/elasticsearch,dataduke/elasticsearch,szroland/elasticsearch,AndreKR/elasticsearch,drewr/elasticsearch,ulkas/elasticsearch,ydsakyclguozi/elasticsearch,smflorentino/elasticsearch,springning/elasticsearch,fubuki/elasticsearch,VukDukic/elasticsearch,polyfractal/elasticsearch,likaiwalkman/elasticsearch,wangtuo/elasticsearch,YosuaMichael/elasticsearch,yanjunh/elasticsearch,MichaelLiZhou/elasticsearch,nrkkalyan/elasticsearch,AshishThakur/elasticsearch,dylan8902/elasticsearch,xuzha/elasticsearch,mgalushka/elasticsearch,vorce/es-metrics,kunallimaye/elasticsearch,chrismwendt/elasticsearch,ZTE-PaaS/elasticsearch,jsgao0/elasticsearch,vietlq/elasticsearch,obourgain/elasticsearch,andrestc/elasticsearch,wbowling/elasticsearch,Siddartha07/elasticsearch,geidies/elasticsearch,wimvds/elasticsearch,JervyShi/elasticsearch,kkirsche/elasticsearch,mm0/elasticsearch,sposam/elasticsearch,Kakakakakku/elasticsearch,rhoml/elasticsearch,jw0201/elastic,Uiho/elasticsearch,truemped/elasticsearch,jbertouch/elasticsearch,coding0011/elasticsearch,hydro2k/elasticsearch,wenpos/elasticsearch,xpandan/elasticsearch,ydsakyclguozi/elasticsearch,wbowling/elasticsearch,Ansh90/elasticsearch,areek/elasticsearch,rento19962/elasticsearch,C-Bish/elasticsearch,wittyameta/elasticsearch,gingerwizard/elasticsearch,ajhalani/elasticsearch,fooljohnny/elasticsearch,acchen97/elasticsearch,salyh/elasticsearch,Fsero/elasticsearch,drewr/elasticsearch,kimimj/elasticsearch,StefanGor/elasticsearch,nrkkalyan/elasticsearch,sdauletau/elasticsearch,tsohil/elasticsearch,wangyuxue/elasticsearch,dantuffery/elasticsearch,linglaiyao1314/elasticsearch,sdauletau/elasticsearch,F0lha/elasticsearch,SergVro/elasticsearch,tkssharma/elasticsearch,MisterAndersen/elasticsearch,Fsero/elasticsearch,iamjakob/elasticsearch,dylan8902/elasticsearch,wittyameta/elasticsearch,shreejay/elasticsearch,tahaemin/elasticsearch,mohit/elasticsearch,linglaiyao1314/elasticsearch,iantruslove/elasticsearch,kunallimaye/elasticsearch,yuy168/elasticsearch,apepper/elasticsearch,codebunt/elasticsearch,petabytedata/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,xpandan/elasticsearch,TonyChai24/ESSource,vietlq/elasticsearch,karthikjaps/elasticsearch,ImpressTV/elasticsearch,Fsero/elasticsearch,lchennup/elasticsearch,umeshdangat/elasticsearch,wangtuo/elasticsearch,sscarduzio/elasticsearch,kkirsche/elasticsearch,mikemccand/elasticsearch,mcku/elasticsearch,ulkas/elasticsearch,libosu/elasticsearch,knight1128/elasticsearch,knight1128/elasticsearch,Collaborne/elasticsearch,zhiqinghuang/elasticsearch,Collaborne/elasticsearch,sdauletau/elasticsearch,NBSW/elasticsearch,thecocce/elasticsearch,golubev/elasticsearch,LewayneNaidoo/elasticsearch,robin13/elasticsearch,tahaemin/elasticsearch,mkis-/elasticsearch,masterweb121/elasticsearch,szroland/elasticsearch,Kakakakakku/elasticsearch,kalburgimanjunath/elasticsearch,xuzha/elasticsearch,coding0011/elasticsearch,tcucchietti/elasticsearch,elancom/elasticsearch,wimvds/elasticsearch,huanzhong/elasticsearch,slavau/elasticsearch,lmtwga/elasticsearch,mapr/elasticsearch,opendatasoft/elasticsearch,weipinghe/elasticsearch,huypx1292/elasticsearch,Chhunlong/elasticsearch,ricardocerq/elasticsearch,vrkansagara/elasticsearch,ThalaivaStars/OrgRepo1,myelin/elasticsearch,ZTE-PaaS/elasticsearch,wimvds/elasticsearch,masterweb121/elasticsearch,wimvds/elasticsearch,MichaelLiZhou/elasticsearch,petmit/elasticsearch,franklanganke/elasticsearch,HonzaKral/elasticsearch,vvcephei/elasticsearch,cnfire/elasticsearch-1,Fsero/elasticsearch,kkirsche/elasticsearch,hanst/elasticsearch,ThiagoGarciaAlves/elasticsearch,hechunwen/elasticsearch,javachengwc/elasticsearch,heng4fun/elasticsearch,petmit/elasticsearch,njlawton/elasticsearch,lmtwga/elasticsearch,hydro2k/elasticsearch,Shepard1212/elasticsearch,masaruh/elasticsearch,nellicus/elasticsearch,btiernay/elasticsearch,linglaiyao1314/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,mcku/elasticsearch,peschlowp/elasticsearch,milodky/elasticsearch,ulkas/elasticsearch,xingguang2013/elasticsearch,wangtuo/elasticsearch,Charlesdong/elasticsearch,yongminxia/elasticsearch,alexshadow007/elasticsearch,artnowo/elasticsearch,mgalushka/elasticsearch,cnfire/elasticsearch-1,xuzha/elasticsearch,Microsoft/elasticsearch,IanvsPoplicola/elasticsearch,mapr/elasticsearch,tebriel/elasticsearch,lmtwga/elasticsearch,brwe/elasticsearch,mute/elasticsearch,KimTaehee/elasticsearch,huypx1292/elasticsearch,vorce/es-metrics,ThalaivaStars/OrgRepo1,aglne/elasticsearch,GlenRSmith/elasticsearch,Rygbee/elasticsearch,petmit/elasticsearch,areek/elasticsearch,ouyangkongtong/elasticsearch,NBSW/elasticsearch,codebunt/elasticsearch,loconsolutions/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,AshishThakur/elasticsearch,iamjakob/elasticsearch,tsohil/elasticsearch,ouyangkongtong/elasticsearch,kenshin233/elasticsearch,MaineC/elasticsearch,Collaborne/elasticsearch,mgalushka/elasticsearch,maddin2016/elasticsearch,iacdingping/elasticsearch,anti-social/elasticsearch,vingupta3/elasticsearch,phani546/elasticsearch,xingguang2013/elasticsearch,a2lin/elasticsearch,Uiho/elasticsearch,skearns64/elasticsearch,jeteve/elasticsearch,caengcjd/elasticsearch,dongjoon-hyun/elasticsearch,xpandan/elasticsearch,jimczi/elasticsearch,scottsom/elasticsearch,Uiho/elasticsearch,ESamir/elasticsearch,dylan8902/elasticsearch,brandonkearby/elasticsearch,episerver/elasticsearch,jsgao0/elasticsearch,mbrukman/elasticsearch,karthikjaps/elasticsearch,kubum/elasticsearch,wuranbo/elasticsearch,djschny/elasticsearch,nellicus/elasticsearch,camilojd/elasticsearch,wangtuo/elasticsearch,huypx1292/elasticsearch,JervyShi/elasticsearch,springning/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,luiseduardohdbackup/elasticsearch,pranavraman/elasticsearch,davidvgalbraith/elasticsearch,salyh/elasticsearch,acchen97/elasticsearch,camilojd/elasticsearch,jaynblue/elasticsearch,milodky/elasticsearch,clintongormley/elasticsearch,andrestc/elasticsearch,acchen97/elasticsearch,andrestc/elasticsearch,girirajsharma/elasticsearch,aparo/elasticsearch,markharwood/elasticsearch,umeshdangat/elasticsearch,palecur/elasticsearch,sreeramjayan/elasticsearch,mgalushka/elasticsearch,scorpionvicky/elasticsearch,tcucchietti/elasticsearch,diendt/elasticsearch,heng4fun/elasticsearch,TonyChai24/ESSource,loconsolutions/elasticsearch,i-am-Nathan/elasticsearch,fforbeck/elasticsearch,easonC/elasticsearch,maddin2016/elasticsearch,kubum/elasticsearch,pozhidaevak/elasticsearch,wbowling/elasticsearch,knight1128/elasticsearch,girirajsharma/elasticsearch,zkidkid/elasticsearch,peschlowp/elasticsearch,fernandozhu/elasticsearch,btiernay/elasticsearch,jimczi/elasticsearch,marcuswr/elasticsearch-dateline,LewayneNaidoo/elasticsearch,strapdata/elassandra-test,zkidkid/elasticsearch,artnowo/elasticsearch,lchennup/elasticsearch,kubum/elasticsearch,a2lin/elasticsearch,yongminxia/elasticsearch,socialrank/elasticsearch,iantruslove/elasticsearch,clintongormley/elasticsearch,Asimov4/elasticsearch,sarwarbhuiyan/elasticsearch,nrkkalyan/elasticsearch,zeroctu/elasticsearch,mortonsykes/elasticsearch,mmaracic/elasticsearch,yongminxia/elasticsearch,Stacey-Gammon/elasticsearch,wenpos/elasticsearch,Siddartha07/elasticsearch,rlugojr/elasticsearch,vietlq/elasticsearch,beiske/elasticsearch,hanswang/elasticsearch,kcompher/elasticsearch,khiraiwa/elasticsearch,dylan8902/elasticsearch,myelin/elasticsearch,salyh/elasticsearch,obourgain/elasticsearch,tsohil/elasticsearch,dylan8902/elasticsearch,SergVro/elasticsearch,mortonsykes/elasticsearch,pritishppai/elasticsearch,mbrukman/elasticsearch,pritishppai/elasticsearch,franklanganke/elasticsearch,kevinkluge/elasticsearch,sc0ttkclark/elasticsearch,kenshin233/elasticsearch,aparo/elasticsearch,markllama/elasticsearch,apepper/elasticsearch,opendatasoft/elasticsearch,MichaelLiZhou/elasticsearch,jimczi/elasticsearch,jango2015/elasticsearch,hafkensite/elasticsearch,hechunwen/elasticsearch,elancom/elasticsearch,beiske/elasticsearch,avikurapati/elasticsearch,slavau/elasticsearch,MetSystem/elasticsearch,scottsom/elasticsearch,weipinghe/elasticsearch,kingaj/elasticsearch,phani546/elasticsearch,Clairebi/ElasticsearchClone,pranavraman/elasticsearch,Microsoft/elasticsearch,nknize/elasticsearch,hechunwen/elasticsearch,jprante/elasticsearch,alexksikes/elasticsearch,Collaborne/elasticsearch,jchampion/elasticsearch,rhoml/elasticsearch,huanzhong/elasticsearch,kingaj/elasticsearch,rmuir/elasticsearch,aglne/elasticsearch,golubev/elasticsearch,fforbeck/elasticsearch,MaineC/elasticsearch,andrejserafim/elasticsearch,mcku/elasticsearch,kimchy/elasticsearch,Shekharrajak/elasticsearch,kimimj/elasticsearch,strapdata/elassandra-test,Microsoft/elasticsearch,mnylen/elasticsearch,yuy168/elasticsearch,liweinan0423/elasticsearch,vvcephei/elasticsearch,rajanm/elasticsearch,mkis-/elasticsearch,jeteve/elasticsearch,jsgao0/elasticsearch,C-Bish/elasticsearch,masaruh/elasticsearch,rmuir/elasticsearch,elancom/elasticsearch,zhiqinghuang/elasticsearch,sjohnr/elasticsearch,nomoa/elasticsearch,lzo/elasticsearch-1,franklanganke/elasticsearch,Widen/elasticsearch,vietlq/elasticsearch,mjason3/elasticsearch,YosuaMichael/elasticsearch,caengcjd/elasticsearch,zeroctu/elasticsearch,nezirus/elasticsearch,kingaj/elasticsearch,pozhidaevak/elasticsearch,Microsoft/elasticsearch,spiegela/elasticsearch,andrestc/elasticsearch,vrkansagara/elasticsearch,brandonkearby/elasticsearch,mjhennig/elasticsearch,lightslife/elasticsearch,vrkansagara/elasticsearch,jimhooker2002/elasticsearch,easonC/elasticsearch,ouyangkongtong/elasticsearch,phani546/elasticsearch,jprante/elasticsearch,fernandozhu/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,markllama/elasticsearch,kubum/elasticsearch,mmaracic/elasticsearch,yuy168/elasticsearch,NBSW/elasticsearch,iacdingping/elasticsearch,slavau/elasticsearch,diendt/elasticsearch,njlawton/elasticsearch,fred84/elasticsearch,markwalkom/elasticsearch,feiqitian/elasticsearch,hanst/elasticsearch,Microsoft/elasticsearch,camilojd/elasticsearch,Flipkart/elasticsearch,ydsakyclguozi/elasticsearch,Asimov4/elasticsearch,robin13/elasticsearch,amit-shar/elasticsearch,brwe/elasticsearch,naveenhooda2000/elasticsearch,kcompher/elasticsearch,vingupta3/elasticsearch,raishiv/elasticsearch,ckclark/elasticsearch,tebriel/elasticsearch,i-am-Nathan/elasticsearch,mbrukman/elasticsearch,jbertouch/elasticsearch,sarwarbhuiyan/elasticsearch,nknize/elasticsearch,geidies/elasticsearch,ulkas/elasticsearch,cnfire/elasticsearch-1,snikch/elasticsearch,njlawton/elasticsearch,KimTaehee/elasticsearch,HarishAtGitHub/elasticsearch,Rygbee/elasticsearch,weipinghe/elasticsearch,abibell/elasticsearch,bestwpw/elasticsearch,tahaemin/elasticsearch,i-am-Nathan/elasticsearch,EasonYi/elasticsearch,ESamir/elasticsearch,acchen97/elasticsearch,nazarewk/elasticsearch,kenshin233/elasticsearch,jbertouch/elasticsearch,yanjunh/elasticsearch,dylan8902/elasticsearch,khiraiwa/elasticsearch,fernandozhu/elasticsearch,achow/elasticsearch,beiske/elasticsearch,MaineC/elasticsearch,socialrank/elasticsearch,khiraiwa/elasticsearch,micpalmia/elasticsearch,tcucchietti/elasticsearch,anti-social/elasticsearch,marcuswr/elasticsearch-dateline,HarishAtGitHub/elasticsearch,rento19962/elasticsearch,sc0ttkclark/elasticsearch,mute/elasticsearch,sjohnr/elasticsearch,pablocastro/elasticsearch,jango2015/elasticsearch,nrkkalyan/elasticsearch,areek/elasticsearch,szroland/elasticsearch,fekaputra/elasticsearch,Kakakakakku/elasticsearch,lydonchandra/elasticsearch,hanswang/elasticsearch,smflorentino/elasticsearch,mbrukman/elasticsearch,zhaocloud/elasticsearch,nazarewk/elasticsearch,beiske/elasticsearch,wbowling/elasticsearch,YosuaMichael/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,ThalaivaStars/OrgRepo1,snikch/elasticsearch,diendt/elasticsearch,rajanm/elasticsearch,kalimatas/elasticsearch,NBSW/elasticsearch,springning/elasticsearch,iantruslove/elasticsearch,tsohil/elasticsearch,kkirsche/elasticsearch,hydro2k/elasticsearch,hanswang/elasticsearch,zeroctu/elasticsearch,jchampion/elasticsearch,feiqitian/elasticsearch,petabytedata/elasticsearch,rhoml/elasticsearch,fooljohnny/elasticsearch,karthikjaps/elasticsearch,drewr/elasticsearch,strapdata/elassandra5-rc,boliza/elasticsearch,palecur/elasticsearch,YosuaMichael/elasticsearch,ThiagoGarciaAlves/elasticsearch,GlenRSmith/elasticsearch,camilojd/elasticsearch,zhiqinghuang/elasticsearch,bestwpw/elasticsearch,hanswang/elasticsearch,Charlesdong/elasticsearch,kalimatas/elasticsearch,yanjunh/elasticsearch,coding0011/elasticsearch,Uiho/elasticsearch,mcku/elasticsearch,njlawton/elasticsearch,rhoml/elasticsearch,kingaj/elasticsearch,kenshin233/elasticsearch,hanst/elasticsearch,karthikjaps/elasticsearch,EasonYi/elasticsearch,golubev/elasticsearch,heng4fun/elasticsearch,strapdata/elassandra-test,HonzaKral/elasticsearch,kaneshin/elasticsearch,anti-social/elasticsearch,sreeramjayan/elasticsearch,kenshin233/elasticsearch,s1monw/elasticsearch,feiqitian/elasticsearch,EasonYi/elasticsearch,iantruslove/elasticsearch,VukDukic/elasticsearch,lydonchandra/elasticsearch,avikurapati/elasticsearch,iamjakob/elasticsearch,loconsolutions/elasticsearch,hirdesh2008/elasticsearch,trangvh/elasticsearch,artnowo/elasticsearch,alexkuk/elasticsearch,dpursehouse/elasticsearch,tsohil/elasticsearch,girirajsharma/elasticsearch,mapr/elasticsearch,tahaemin/elasticsearch,Liziyao/elasticsearch,kingaj/elasticsearch,sposam/elasticsearch,henakamaMSFT/elasticsearch,wenpos/elasticsearch,masterweb121/elasticsearch,jaynblue/elasticsearch,mortonsykes/elasticsearch,drewr/elasticsearch,alexksikes/elasticsearch,xpandan/elasticsearch,pablocastro/elasticsearch,ThiagoGarciaAlves/elasticsearch,AndreKR/elasticsearch,queirozfcom/elasticsearch,amit-shar/elasticsearch,Helen-Zhao/elasticsearch,xingguang2013/elasticsearch,MetSystem/elasticsearch,dpursehouse/elasticsearch,markharwood/elasticsearch,HarishAtGitHub/elasticsearch,iacdingping/elasticsearch,hydro2k/elasticsearch,golubev/elasticsearch,feiqitian/elasticsearch,rmuir/elasticsearch,kubum/elasticsearch,ckclark/elasticsearch,vorce/es-metrics,girirajsharma/elasticsearch,ThiagoGarciaAlves/elasticsearch,gingerwizard/elasticsearch,libosu/elasticsearch,ZTE-PaaS/elasticsearch,kingaj/elasticsearch,koxa29/elasticsearch,polyfractal/elasticsearch,Widen/elasticsearch,huypx1292/elasticsearch,schonfeld/elasticsearch,achow/elasticsearch,lightslife/elasticsearch,vorce/es-metrics,clintongormley/elasticsearch,geidies/elasticsearch,jsgao0/elasticsearch,chirilo/elasticsearch,Liziyao/elasticsearch,mnylen/elasticsearch,masterweb121/elasticsearch,hirdesh2008/elasticsearch,glefloch/elasticsearch,ydsakyclguozi/elasticsearch,geidies/elasticsearch,episerver/elasticsearch,jeteve/elasticsearch,likaiwalkman/elasticsearch,lydonchandra/elasticsearch,LewayneNaidoo/elasticsearch,dantuffery/elasticsearch,uschindler/elasticsearch,chirilo/elasticsearch,girirajsharma/elasticsearch,shreejay/elasticsearch,areek/elasticsearch,spiegela/elasticsearch,kalimatas/elasticsearch,shreejay/elasticsearch,tsohil/elasticsearch,fred84/elasticsearch,nomoa/elasticsearch,davidvgalbraith/elasticsearch,cwurm/elasticsearch,kimimj/elasticsearch,lks21c/elasticsearch,mapr/elasticsearch,huanzhong/elasticsearch,bawse/elasticsearch,marcuswr/elasticsearch-dateline,nezirus/elasticsearch,mohit/elasticsearch,himanshuag/elasticsearch,coding0011/elasticsearch,chirilo/elasticsearch,andrejserafim/elasticsearch,Liziyao/elasticsearch,awislowski/elasticsearch,sauravmondallive/elasticsearch,sarwarbhuiyan/elasticsearch,18098924759/elasticsearch,Charlesdong/elasticsearch,luiseduardohdbackup/elasticsearch,infusionsoft/elasticsearch,bestwpw/elasticsearch,iamjakob/elasticsearch,fforbeck/elasticsearch,qwerty4030/elasticsearch,sc0ttkclark/elasticsearch,jchampion/elasticsearch,vingupta3/elasticsearch,sneivandt/elasticsearch,beiske/elasticsearch,markllama/elasticsearch,glefloch/elasticsearch,F0lha/elasticsearch,Clairebi/ElasticsearchClone,kimimj/elasticsearch,mnylen/elasticsearch,IanvsPoplicola/elasticsearch,Uiho/elasticsearch,rhoml/elasticsearch,infusionsoft/elasticsearch,18098924759/elasticsearch,camilojd/elasticsearch,himanshuag/elasticsearch,alexshadow007/elasticsearch,jimhooker2002/elasticsearch,mortonsykes/elasticsearch,qwerty4030/elasticsearch,springning/elasticsearch,elasticdog/elasticsearch,Charlesdong/elasticsearch,karthikjaps/elasticsearch,mohsinh/elasticsearch,zkidkid/elasticsearch,amaliujia/elasticsearch,diendt/elasticsearch,overcome/elasticsearch,fooljohnny/elasticsearch,mjason3/elasticsearch,iamjakob/elasticsearch,mgalushka/elasticsearch,18098924759/elasticsearch,sscarduzio/elasticsearch,koxa29/elasticsearch,ckclark/elasticsearch,ivansun1010/elasticsearch,onegambler/elasticsearch,tkssharma/elasticsearch,abibell/elasticsearch,strapdata/elassandra-test,lightslife/elasticsearch,kunallimaye/elasticsearch,HarishAtGitHub/elasticsearch,queirozfcom/elasticsearch,kimimj/elasticsearch,a2lin/elasticsearch,AshishThakur/elasticsearch,markwalkom/elasticsearch,drewr/elasticsearch,caengcjd/elasticsearch,markharwood/elasticsearch,cwurm/elasticsearch,knight1128/elasticsearch,pablocastro/elasticsearch,mohit/elasticsearch,kaneshin/elasticsearch,raishiv/elasticsearch,jbertouch/elasticsearch,rento19962/elasticsearch,rento19962/elasticsearch,mm0/elasticsearch,mjhennig/elasticsearch,uboness/elasticsearch,ESamir/elasticsearch,humandb/elasticsearch,mrorii/elasticsearch,JervyShi/elasticsearch,strapdata/elassandra,alexksikes/elasticsearch,ZTE-PaaS/elasticsearch,springning/elasticsearch,alexbrasetvik/elasticsearch,rajanm/elasticsearch,alexbrasetvik/elasticsearch,jimhooker2002/elasticsearch,vingupta3/elasticsearch,wimvds/elasticsearch,mgalushka/elasticsearch,liweinan0423/elasticsearch,Shekharrajak/elasticsearch,GlenRSmith/elasticsearch,loconsolutions/elasticsearch,Flipkart/elasticsearch,gfyoung/elasticsearch,lightslife/elasticsearch,Chhunlong/elasticsearch,sauravmondallive/elasticsearch,Rygbee/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,mrorii/elasticsearch,scorpionvicky/elasticsearch,sposam/elasticsearch,sscarduzio/elasticsearch,vvcephei/elasticsearch,pritishppai/elasticsearch,C-Bish/elasticsearch,Shekharrajak/elasticsearch,achow/elasticsearch,infusionsoft/elasticsearch,skearns64/elasticsearch,aparo/elasticsearch,glefloch/elasticsearch,pozhidaevak/elasticsearch,sscarduzio/elasticsearch,szroland/elasticsearch,diendt/elasticsearch,mrorii/elasticsearch,ThalaivaStars/OrgRepo1,ImpressTV/elasticsearch,huypx1292/elasticsearch,Fsero/elasticsearch,strapdata/elassandra5-rc,lchennup/elasticsearch,JackyMai/elasticsearch,lks21c/elasticsearch,tebriel/elasticsearch,mmaracic/elasticsearch,xpandan/elasticsearch,schonfeld/elasticsearch,Siddartha07/elasticsearch,Shekharrajak/elasticsearch,dantuffery/elasticsearch,HonzaKral/elasticsearch,Shepard1212/elasticsearch,tkssharma/elasticsearch,sneivandt/elasticsearch,ImpressTV/elasticsearch,Brijeshrpatel9/elasticsearch,lydonchandra/elasticsearch,mapr/elasticsearch,YosuaMichael/elasticsearch,ouyangkongtong/elasticsearch,mmaracic/elasticsearch,jprante/elasticsearch,amit-shar/elasticsearch,jaynblue/elasticsearch,kunallimaye/elasticsearch,socialrank/elasticsearch,zeroctu/elasticsearch,ThiagoGarciaAlves/elasticsearch,jpountz/elasticsearch,ckclark/elasticsearch,palecur/elasticsearch,lydonchandra/elasticsearch,brandonkearby/elasticsearch,likaiwalkman/elasticsearch,adrianbk/elasticsearch,brwe/elasticsearch,episerver/elasticsearch,knight1128/elasticsearch,myelin/elasticsearch,lks21c/elasticsearch,wittyameta/elasticsearch,queirozfcom/elasticsearch,vroyer/elasticassandra,micpalmia/elasticsearch,wayeast/elasticsearch,wuranbo/elasticsearch,iantruslove/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,chirilo/elasticsearch,yuy168/elasticsearch,tebriel/elasticsearch,EasonYi/elasticsearch,abhijitiitr/es,djschny/elasticsearch,IanvsPoplicola/elasticsearch,alexbrasetvik/elasticsearch,TonyChai24/ESSource,zkidkid/elasticsearch,i-am-Nathan/elasticsearch,schonfeld/elasticsearch,adrianbk/elasticsearch,yongminxia/elasticsearch,fred84/elasticsearch,naveenhooda2000/elasticsearch,Shepard1212/elasticsearch,andrejserafim/elasticsearch,EasonYi/elasticsearch,vingupta3/elasticsearch,trangvh/elasticsearch,humandb/elasticsearch,rento19962/elasticsearch,uboness/elasticsearch,bawse/elasticsearch,mute/elasticsearch,sarwarbhuiyan/elasticsearch,awislowski/elasticsearch,slavau/elasticsearch,sc0ttkclark/elasticsearch,andrewvc/elasticsearch,nellicus/elasticsearch,Collaborne/elasticsearch,JackyMai/elasticsearch,MaineC/elasticsearch,girirajsharma/elasticsearch,GlenRSmith/elasticsearch,fekaputra/elasticsearch,ricardocerq/elasticsearch,jprante/elasticsearch,JervyShi/elasticsearch,chrismwendt/elasticsearch,ulkas/elasticsearch,strapdata/elassandra5-rc,Clairebi/ElasticsearchClone,humandb/elasticsearch,onegambler/elasticsearch,mjason3/elasticsearch,JSCooke/elasticsearch,yynil/elasticsearch,feiqitian/elasticsearch,kaneshin/elasticsearch,KimTaehee/elasticsearch,zhaocloud/elasticsearch,lightslife/elasticsearch,AndreKR/elasticsearch,koxa29/elasticsearch,khiraiwa/elasticsearch,lchennup/elasticsearch,xingguang2013/elasticsearch,adrianbk/elasticsearch,Helen-Zhao/elasticsearch,MjAbuz/elasticsearch | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.test.integration.indices.store;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.node.internal.InternalNode;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import static org.elasticsearch.client.Requests.clusterHealthRequest;
import static org.elasticsearch.client.Requests.createIndexRequest;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
*
*/
public class IndicesStoreTests extends AbstractNodesTests {
protected Client client1;
@BeforeClass
public void startNodes() {
// The default (none) gateway cleans the shards on closing
putDefaultSettings(settingsBuilder().put("gateway.type", "local"));
startNode("server1");
startNode("server2");
client1 = getClient1();
}
@AfterClass
public void closeNodes() {
client1.close();
closeAllNodes();
}
protected Client getClient1() {
return client("server1");
}
@Test
public void shardsCleanup() throws Exception {
try {
client1.admin().indices().prepareDelete("test").execute().actionGet();
} catch (Exception ex) {
// Ignore
}
logger.info("--> creating index [test] with one shard and on replica");
client1.admin().indices().create(createIndexRequest("test")
.setSettings(settingsBuilder().put("index.numberOfReplicas", 1).put("index.numberOfShards", 1))).actionGet();
logger.info("--> running cluster_health");
ClusterHealthResponse clusterHealth = client1.admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus()).actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica are allocated on server1 and server2");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(shardDirectory("server2", "test", 0).exists(), equalTo(true));
logger.info("--> starting node server3");
startNode("server3");
logger.info("--> making sure that shard is not allocated on server3");
assertThat(waitForShardDeletion(TimeValue.timeValueSeconds(1), "server3", "test", 0), equalTo(false));
File server2Shard = shardDirectory("server2", "test", 0);
logger.info("--> stopping node server2");
closeNode("server2");
assertThat(server2Shard.exists(), equalTo(true));
logger.info("--> running cluster_health");
clusterHealth = client1.admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus().setWaitForNodes("2")).actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica exist on server1, server2 and server3");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(server2Shard.exists(), equalTo(true));
assertThat(shardDirectory("server3", "test", 0).exists(), equalTo(true));
logger.info("--> starting node server2");
startNode("server2");
logger.info("--> running cluster_health");
clusterHealth = client("server2").admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus()).actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica are allocated on server1 and server3 but not on server2");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(shardDirectory("server3", "test", 0).exists(), equalTo(true));
assertThat(waitForShardDeletion(TimeValue.timeValueSeconds(1), "server2", "test", 0), equalTo(false));
}
private File shardDirectory(String server, String index, int shard) {
InternalNode node = ((InternalNode) node(server));
NodeEnvironment env = node.injector().getInstance(NodeEnvironment.class);
return env.shardLocations(new ShardId(index, shard))[0];
}
private boolean waitForShardDeletion(TimeValue timeout, String server, String index, int shard) throws InterruptedException {
long start = System.currentTimeMillis();
boolean shardExists;
do {
shardExists = shardDirectory(server, index, shard).exists();
}
while (shardExists && (System.currentTimeMillis() - start) < timeout.millis());
return shardExists;
}
}
| src/test/java/org/elasticsearch/test/integration/indices/store/IndicesStoreTests.java | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.test.integration.indices.store;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.node.internal.InternalNode;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import static org.elasticsearch.client.Requests.clusterHealthRequest;
import static org.elasticsearch.client.Requests.createIndexRequest;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
*
*/
public class IndicesStoreTests extends AbstractNodesTests {
protected Client client1;
@BeforeClass
public void startNodes() {
// The default (none) gateway cleans the shards on closing
putDefaultSettings(settingsBuilder().put("gateway.type", "local"));
startNode("server1");
startNode("server2");
client1 = getClient1();
}
@AfterClass
public void closeNodes() {
client1.close();
closeAllNodes();
}
protected Client getClient1() {
return client("server1");
}
@Test
public void shardsCleanup() throws Exception {
try {
client1.admin().indices().prepareDelete("test").execute().actionGet();
} catch (Exception ex) {
// Ignore
}
logger.info("--> creating index [test] with one shard and on replica");
client1.admin().indices().create(createIndexRequest("test")
.setSettings(settingsBuilder().put("index.numberOfReplicas", 1).put("index.numberOfShards", 1))).actionGet();
logger.info("--> running cluster_health");
ClusterHealthResponse clusterHealth = client1.admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus()).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica are allocated on server1 and server2");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(shardDirectory("server2", "test", 0).exists(), equalTo(true));
logger.info("--> starting node server3");
startNode("server3");
logger.info("--> making sure that shard is not allocated on server3");
assertThat(waitForShardDeletion(TimeValue.timeValueSeconds(1), "server3", "test", 0), equalTo(false));
File server2Shard = shardDirectory("server2", "test", 0);
logger.info("--> stopping node server2");
closeNode("server2");
assertThat(server2Shard.exists(), equalTo(true));
logger.info("--> running cluster_health");
clusterHealth = client1.admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus().setWaitForNodes("2")).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica exist on server1, server2 and server3");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(server2Shard.exists(), equalTo(true));
assertThat(shardDirectory("server3", "test", 0).exists(), equalTo(true));
logger.info("--> starting node server2");
startNode("server2");
logger.info("--> running cluster_health");
clusterHealth = client("server2").admin().cluster().health(clusterHealthRequest().setWaitForGreenStatus()).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
logger.info("--> making sure that shard and it's replica are allocated on server1 and server3 but not on server2");
assertThat(shardDirectory("server1", "test", 0).exists(), equalTo(true));
assertThat(shardDirectory("server3", "test", 0).exists(), equalTo(true));
assertThat(waitForShardDeletion(TimeValue.timeValueSeconds(1), "server2", "test", 0), equalTo(false));
}
private File shardDirectory(String server, String index, int shard) {
InternalNode node = ((InternalNode) node(server));
NodeEnvironment env = node.injector().getInstance(NodeEnvironment.class);
return env.shardLocations(new ShardId(index, shard))[0];
}
private boolean waitForShardDeletion(TimeValue timeout, String server, String index, int shard) throws InterruptedException {
long start = System.currentTimeMillis();
boolean shardExists;
do {
shardExists = shardDirectory(server, index, shard).exists();
}
while (shardExists && (System.currentTimeMillis() - start) < timeout.millis());
return shardExists;
}
}
| Add check for health timeout to shardCleanup test
| src/test/java/org/elasticsearch/test/integration/indices/store/IndicesStoreTests.java | Add check for health timeout to shardCleanup test |
|
Java | apache-2.0 | f757db63d5c601cc8fc8ae05400ee2a1783324cd | 0 | ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,hurricup/intellij-community,da1z/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fitermay/intellij-community,signed/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,signed/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,xfournet/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,signed/intellij-community,xfournet/intellij-community,signed/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,fitermay/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,hurricup/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,hurricup/intellij-community,da1z/intellij-community,allotria/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,hurricup/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,semonte/intellij-community,vvv1559/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,signed/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,retomerz/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,lucafavatella/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,allotria/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,fitermay/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ibinti/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.ui.branch;
import com.intellij.dvcs.branch.DvcsMultiRootBranchConfig;
import com.intellij.util.containers.ContainerUtil;
import git4idea.GitLocalBranch;
import git4idea.GitRemoteBranch;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitBranchTrackInfo;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* @author Kirill Likhodedov
*/
public class GitMultiRootBranchConfig extends DvcsMultiRootBranchConfig<GitRepository> {
public GitMultiRootBranchConfig(@NotNull Collection<GitRepository> repositories) {
super(repositories);
}
@Override
@NotNull
public Collection<String> getLocalBranchNames() {
return GitBranchUtil.getCommonBranches(myRepositories, true);
}
@NotNull
Collection<String> getRemoteBranches() {
return GitBranchUtil.getCommonBranches(myRepositories, false);
}
/**
* If there is a common remote branch which is commonly tracked by the given branch in all repositories,
* returns the name of this remote branch. Otherwise returns null. <br/>
* For one repository just returns the tracked branch or null if there is no tracked branch.
*/
@Nullable
public String getTrackedBranch(@NotNull String branch) {
String trackedName = null;
for (GitRepository repository : myRepositories) {
GitRemoteBranch tracked = getTrackedBranch(repository, branch);
if (tracked == null) {
return null;
}
if (trackedName == null) {
trackedName = tracked.getNameForLocalOperations();
}
else if (!trackedName.equals(tracked.getNameForLocalOperations())) {
return null;
}
}
return trackedName;
}
/**
* Returns local branches which track the given remote branch. Usually there is 0 or 1 such branches.
*/
@NotNull
public Collection<String> getTrackingBranches(@NotNull String remoteBranch) {
Collection<String> trackingBranches = null;
for (GitRepository repository : myRepositories) {
Collection<String> tb = getTrackingBranches(repository, remoteBranch);
if (trackingBranches == null) {
trackingBranches = tb;
}
else {
trackingBranches = ContainerUtil.intersection(trackingBranches, tb);
}
}
return trackingBranches == null ? Collections.<String>emptyList() : trackingBranches;
}
@NotNull
public static Collection<String> getTrackingBranches(@NotNull GitRepository repository, @NotNull String remoteBranch) {
Collection<String> trackingBranches = new ArrayList<String>(1);
for (GitBranchTrackInfo trackInfo : repository.getBranchTrackInfos()) {
if (remoteBranch.equals(trackInfo.getRemoteBranch().getNameForLocalOperations())) {
trackingBranches.add(trackInfo.getLocalBranch().getName());
}
}
return trackingBranches;
}
@Nullable
private static GitRemoteBranch getTrackedBranch(@NotNull GitRepository repository, @NotNull String branchName) {
GitLocalBranch branch = repository.getBranches().findLocalBranch(branchName);
return branch == null ? null : branch.findTrackedBranch(repository);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (GitRepository repository : myRepositories) {
sb.append(repository.getPresentableUrl()).append(":").append(repository.getCurrentBranch()).append(":").append(repository.getState());
}
return sb.toString();
}
}
| plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.ui.branch;
import com.intellij.dvcs.branch.DvcsMultiRootBranchConfig;
import com.intellij.util.containers.ContainerUtil;
import git4idea.GitLocalBranch;
import git4idea.GitRemoteBranch;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitBranchTrackInfo;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* @author Kirill Likhodedov
*/
public class GitMultiRootBranchConfig extends DvcsMultiRootBranchConfig<GitRepository> {
public GitMultiRootBranchConfig(@NotNull Collection<GitRepository> repositories) {
super(repositories);
}
@Override
@NotNull
public Collection<String> getLocalBranchNames() {
return GitBranchUtil.getCommonBranches(myRepositories, true);
}
@NotNull
Collection<String> getRemoteBranches() {
return GitBranchUtil.getCommonBranches(myRepositories, false);
}
/**
* If there is a common remote branch which is commonly tracked by the given branch in all repositories,
* returns the name of this remote branch. Otherwise returns null. <br/>
* For one repository just returns the tracked branch or null if there is no tracked branch.
*/
@Nullable
public String getTrackedBranch(@NotNull String branch) {
String trackedName = null;
for (GitRepository repository : myRepositories) {
GitRemoteBranch tracked = getTrackedBranch(repository, branch);
if (tracked == null) {
return null;
}
if (trackedName == null) {
trackedName = tracked.getNameForLocalOperations();
}
else if (!trackedName.equals(tracked.getNameForLocalOperations())) {
return null;
}
}
return trackedName;
}
/**
* Returns local branches which track the given remote branch. Usually there is 0 or 1 such branches.
*/
@NotNull
public Collection<String> getTrackingBranches(@NotNull String remoteBranch) {
Collection<String> trackingBranches = null;
for (GitRepository repository : myRepositories) {
Collection<String> tb = getTrackingBranches(repository, remoteBranch);
if (trackingBranches == null) {
trackingBranches = tb;
}
else {
trackingBranches = ContainerUtil.intersection(trackingBranches, tb);
}
}
return trackingBranches == null ? Collections.<String>emptyList() : trackingBranches;
}
@NotNull
public static Collection<String> getTrackingBranches(@NotNull GitRepository repository, @NotNull String remoteBranch) {
Collection<String> trackingBranches = new ArrayList<String>(1);
for (GitBranchTrackInfo trackInfo : repository.getBranchTrackInfos()) {
if (remoteBranch.equals(trackInfo.getRemote().getName() + "/" + trackInfo.getRemoteBranch())) {
trackingBranches.add(trackInfo.getLocalBranch().getName());
}
}
return trackingBranches;
}
@Nullable
private static GitRemoteBranch getTrackedBranch(@NotNull GitRepository repository, @NotNull String branchName) {
GitLocalBranch branch = repository.getBranches().findLocalBranch(branchName);
return branch == null ? null : branch.findTrackedBranch(repository);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (GitRepository repository : myRepositories) {
sb.append(repository.getPresentableUrl()).append(":").append(repository.getCurrentBranch()).append(":").append(repository.getState());
}
return sb.toString();
}
}
| git: IDEA-152430 Removing remote branch should offer to delete tracking branch
This used to work, but was broken a while ago, during some
refactoring related to using of GitRemoteBranch objects.
| plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java | git: IDEA-152430 Removing remote branch should offer to delete tracking branch |
|
Java | apache-2.0 | 368fc2f6cc4fcd5269c57c486a1c90170d8ee829 | 0 | UweTrottmann/SeriesGuide,0359xiaodong/SeriesGuide,UweTrottmann/SeriesGuide,epiphany27/SeriesGuide,r00t-user/SeriesGuide,artemnikitin/SeriesGuide,hoanganhx86/SeriesGuide | /*
* Copyright 2012 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.battlelancer.seriesguide.ui;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.battlelancer.seriesguide.provider.SeriesContract.ListItems;
import com.battlelancer.seriesguide.provider.SeriesContract.Lists;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.ui.ShowsFragment.ViewHolder;
import com.battlelancer.seriesguide.util.ImageProvider;
import com.battlelancer.seriesguide.util.Utils;
import com.uwetrottmann.seriesguide.R;
/**
* Displays one user created list which includes a mixture of shows, seasons and
* episodes.
*/
public class ListsFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
private static final int LOADER_ID = R.layout.lists_fragment;
private static final int CONTEXT_REMOVE_ID = 300;
public static ListsFragment newInstance(String list_id) {
ListsFragment f = new ListsFragment();
Bundle args = new Bundle();
args.putString(InitBundle.LIST_ID, list_id);
f.setArguments(args);
return f;
}
interface InitBundle {
String LIST_ID = "list_id";
}
private ListItemAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.lists_fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new ListItemAdapter(getActivity(), null, 0);
// setup grid view
GridView list = (GridView) getView().findViewById(android.R.id.list);
list.setAdapter(mAdapter);
list.setOnItemClickListener(this);
list.setEmptyView(getView().findViewById(android.R.id.empty));
registerForContextMenu(list);
getLoaderManager().initLoader(LOADER_ID, getArguments(), this);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REMOVE_ID, 0, R.string.list_item_remove);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REMOVE_ID: {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String itemId = ((Cursor) mAdapter.getItem(info.position))
.getString(ListItemsQuery.LIST_ITEM_ID);
getActivity().getContentResolver().delete(ListItems.buildListItemUri(itemId), null,
null);
getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI,
null);
return true;
}
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Cursor listItem = (Cursor) mAdapter.getItem(position);
int itemType = listItem.getInt(ListItemsQuery.ITEM_TYPE);
String itemRefId = listItem.getString(ListItemsQuery.ITEM_REF_ID);
switch (itemType) {
case 1: {
// display show overview
Intent intent = new Intent(getActivity(), OverviewActivity.class);
intent.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
case 2: {
// display episodes of season
Intent intent = new Intent(getActivity(), EpisodesActivity.class);
intent.putExtra(EpisodesActivity.InitBundle.SEASON_TVDBID,
Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
case 3: {
// display episode details
Intent intent = new Intent(getActivity(), EpisodesActivity.class);
intent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String listId = args.getString(InitBundle.LIST_ID);
return new CursorLoader(getActivity(), ListItems.CONTENT_WITH_DETAILS_URI,
ListItemsQuery.PROJECTION,
Lists.LIST_ID + "=?",
new String[] {
listId
}, ListItemsQuery.SORTING);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
private class ListItemAdapter extends CursorAdapter {
private LayoutInflater mInflater;
private SharedPreferences mPrefs;
public ListItemAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mInflater = LayoutInflater.from(context);
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (!mDataValid) {
throw new IllegalStateException(
"this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
final ViewHolder viewHolder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.shows_row, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname);
viewHolder.timeAndNetwork = (TextView) convertView
.findViewById(R.id.textViewShowsTimeAndNetwork);
viewHolder.episode = (TextView) convertView
.findViewById(R.id.TextViewShowListNextEpisode);
viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime);
viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter);
viewHolder.favorited = (ImageView) convertView.findViewById(R.id.favoritedLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// show title
viewHolder.name.setText(mCursor.getString(ListItemsQuery.SHOW_TITLE));
// favorite star
final boolean isFavorited = mCursor.getInt(ListItemsQuery.SHOW_FAVORITE) == 1;
viewHolder.favorited.setVisibility(isFavorited ? View.VISIBLE : View.GONE);
// item title
int itemType = mCursor.getInt(ListItemsQuery.ITEM_TYPE);
switch (itemType) {
default:
case 1:
// shows
// air time and network
final String[] values = Utils.parseMillisecondsToTime(
mCursor.getLong(ListItemsQuery.AIRSTIME),
mCursor.getString(ListItemsQuery.SHOW_AIRSDAY), mContext);
if (getResources().getBoolean(R.bool.isLargeTablet)) {
// network first, then time, one line
viewHolder.timeAndNetwork.setText(mCursor
.getString(ListItemsQuery.SHOW_NETWORK) + " / "
+ values[1] + " " + values[0]);
} else {
// smaller screen, time first, network second line
viewHolder.timeAndNetwork.setText(values[1] + " " + values[0] + "\n"
+ mCursor.getString(ListItemsQuery.SHOW_NETWORK));
}
// next episode info
String fieldValue = mCursor.getString(ListItemsQuery.SHOW_NEXTTEXT);
if (TextUtils.isEmpty(fieldValue)) {
// show show status if there are currently no more
// episodes
int status = mCursor.getInt(ListItemsQuery.SHOW_STATUS);
// Continuing == 1 and Ended == 0
if (status == 1) {
viewHolder.episodeTime.setText(getString(R.string.show_isalive));
} else if (status == 0) {
viewHolder.episodeTime.setText(getString(R.string.show_isnotalive));
} else {
viewHolder.episodeTime.setText("");
}
viewHolder.episode.setText("");
} else {
viewHolder.episode.setText(fieldValue);
fieldValue = mCursor.getString(ListItemsQuery.SHOW_NEXTAIRDATETEXT);
viewHolder.episodeTime.setText(fieldValue);
}
break;
case 2:
// seasons
viewHolder.timeAndNetwork.setText(R.string.season);
viewHolder.episode.setText(Utils.getSeasonString(mContext,
mCursor.getInt(ListItemsQuery.ITEM_TITLE)));
viewHolder.episodeTime.setText("");
break;
case 3:
// episodes
viewHolder.timeAndNetwork.setText(R.string.episode);
viewHolder.episode.setText(Utils.getNextEpisodeString(mPrefs,
mCursor.getInt(ListItemsQuery.SHOW_NEXTTEXT),
mCursor.getInt(ListItemsQuery.SHOW_NEXTAIRDATETEXT),
mCursor.getString(ListItemsQuery.ITEM_TITLE)));
long airtime = mCursor.getLong(ListItemsQuery.AIRSTIME);
if (airtime != -1) {
final String[] dayAndTime = Utils
.formatToTimeAndDay(airtime, getActivity());
viewHolder.episodeTime.setText(new StringBuilder().append(dayAndTime[2])
.append(" (")
.append(dayAndTime[1])
.append(")"));
}
break;
}
// poster
final String imagePath = mCursor.getString(ListItemsQuery.SHOW_POSTER);
ImageProvider.getInstance(mContext).loadPosterThumb(viewHolder.poster, imagePath);
return convertView;
}
@Override
public void bindView(View arg0, Context arg1, Cursor arg2) {
// do nothing here
}
@Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
return null;
}
}
interface ListItemsQuery {
String[] PROJECTION = new String[] {
ListItems._ID, ListItems.LIST_ITEM_ID, ListItems.ITEM_REF_ID, ListItems.TYPE,
Shows.REF_SHOW_ID, Shows.TITLE, Shows.OVERVIEW, Shows.POSTER, Shows.NETWORK,
Shows.AIRSTIME, Shows.AIRSDAYOFWEEK, Shows.STATUS, Shows.NEXTTEXT,
Shows.NEXTAIRDATETEXT, Shows.FAVORITE
};
String SORTING = Shows.TITLE + " COLLATE NOCASE ASC, " + ListItems.TYPE + " ASC";
int LIST_ITEM_ID = 1;
int ITEM_REF_ID = 2;
int ITEM_TYPE = 3;
int SHOW_ID = 4;
int SHOW_TITLE = 5;
int ITEM_TITLE = 6;
int SHOW_POSTER = 7;
int SHOW_NETWORK = 8;
int AIRSTIME = 9;
int SHOW_AIRSDAY = 10;
int SHOW_STATUS = 11;
int SHOW_NEXTTEXT = 12;
int SHOW_NEXTAIRDATETEXT = 13;
int SHOW_FAVORITE = 14;
}
}
| SeriesGuide/src/com/battlelancer/seriesguide/ui/ListsFragment.java | /*
* Copyright 2012 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.battlelancer.seriesguide.ui;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.battlelancer.seriesguide.provider.SeriesContract.ListItems;
import com.battlelancer.seriesguide.provider.SeriesContract.Lists;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.ui.ShowsFragment.ViewHolder;
import com.battlelancer.seriesguide.util.ImageProvider;
import com.battlelancer.seriesguide.util.Utils;
import com.uwetrottmann.seriesguide.R;
/**
* Displays one user created list which includes a mixture of shows, seasons and
* episodes.
*/
public class ListsFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
private static final int LOADER_ID = R.layout.lists_fragment;
private static final int CONTEXT_REMOVE_ID = 300;
public static ListsFragment newInstance(String list_id) {
ListsFragment f = new ListsFragment();
Bundle args = new Bundle();
args.putString(InitBundle.LIST_ID, list_id);
f.setArguments(args);
return f;
}
interface InitBundle {
String LIST_ID = "list_id";
}
private ListItemAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.lists_fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new ListItemAdapter(getActivity(), null, 0);
// setup grid view
GridView list = (GridView) getView().findViewById(android.R.id.list);
list.setAdapter(mAdapter);
list.setOnItemClickListener(this);
list.setEmptyView(getView().findViewById(android.R.id.empty));
registerForContextMenu(list);
getLoaderManager().initLoader(LOADER_ID, getArguments(), this);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REMOVE_ID, 0, R.string.list_item_remove);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REMOVE_ID: {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String itemId = ((Cursor) mAdapter.getItem(info.position))
.getString(ListItemsQuery.LIST_ITEM_ID);
getActivity().getContentResolver().delete(ListItems.buildListItemUri(itemId), null,
null);
getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI,
null);
return true;
}
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Cursor listItem = (Cursor) mAdapter.getItem(position);
int itemType = listItem.getInt(ListItemsQuery.ITEM_TYPE);
String itemRefId = listItem.getString(ListItemsQuery.ITEM_REF_ID);
switch (itemType) {
case 1: {
// display show overview
Intent intent = new Intent(getActivity(), OverviewActivity.class);
intent.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
case 2: {
// display episodes of season
Intent intent = new Intent(getActivity(), EpisodesActivity.class);
intent.putExtra(EpisodesActivity.InitBundle.SEASON_TVDBID,
Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
case 3: {
// display episode details
Intent intent = new Intent(getActivity(), EpisodesActivity.class);
intent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
Integer.valueOf(itemRefId));
startActivity(intent);
break;
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String listId = args.getString(InitBundle.LIST_ID);
return new CursorLoader(getActivity(), ListItems.CONTENT_WITH_DETAILS_URI,
ListItemsQuery.PROJECTION,
Lists.LIST_ID + "=?",
new String[] {
listId
}, ListItemsQuery.SORTING);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
private class ListItemAdapter extends CursorAdapter {
private LayoutInflater mInflater;
private SharedPreferences mPrefs;
public ListItemAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mInflater = LayoutInflater.from(context);
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (!mDataValid) {
throw new IllegalStateException(
"this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
final ViewHolder viewHolder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.shows_row, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname);
viewHolder.timeAndNetwork = (TextView) convertView
.findViewById(R.id.textViewShowsTimeAndNetwork);
viewHolder.episode = (TextView) convertView
.findViewById(R.id.TextViewShowListNextEpisode);
viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime);
viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// show title
viewHolder.name.setText(mCursor.getString(ListItemsQuery.SHOW_TITLE));
// item title
int itemType = mCursor.getInt(ListItemsQuery.ITEM_TYPE);
switch (itemType) {
default:
case 1:
// shows
// air time and network
final String[] values = Utils.parseMillisecondsToTime(
mCursor.getLong(ListItemsQuery.AIRSTIME),
mCursor.getString(ListItemsQuery.SHOW_AIRSDAY), mContext);
if (getResources().getBoolean(R.bool.isLargeTablet)) {
// network first, then time, one line
viewHolder.timeAndNetwork.setText(mCursor
.getString(ListItemsQuery.SHOW_NETWORK) + " / "
+ values[1] + " " + values[0]);
} else {
// smaller screen, time first, network second line
viewHolder.timeAndNetwork.setText(values[1] + " " + values[0] + "\n"
+ mCursor.getString(ListItemsQuery.SHOW_NETWORK));
}
// next episode info
String fieldValue = mCursor.getString(ListItemsQuery.SHOW_NEXTTEXT);
if (TextUtils.isEmpty(fieldValue)) {
// show show status if there are currently no more
// episodes
int status = mCursor.getInt(ListItemsQuery.SHOW_STATUS);
// Continuing == 1 and Ended == 0
if (status == 1) {
viewHolder.episodeTime.setText(getString(R.string.show_isalive));
} else if (status == 0) {
viewHolder.episodeTime.setText(getString(R.string.show_isnotalive));
} else {
viewHolder.episodeTime.setText("");
}
viewHolder.episode.setText("");
} else {
viewHolder.episode.setText(fieldValue);
fieldValue = mCursor.getString(ListItemsQuery.SHOW_NEXTAIRDATETEXT);
viewHolder.episodeTime.setText(fieldValue);
}
break;
case 2:
// seasons
viewHolder.timeAndNetwork.setText(R.string.season);
viewHolder.episode.setText(Utils.getSeasonString(mContext,
mCursor.getInt(ListItemsQuery.ITEM_TITLE)));
viewHolder.episodeTime.setText("");
break;
case 3:
// episodes
viewHolder.timeAndNetwork.setText(R.string.episode);
viewHolder.episode.setText(Utils.getNextEpisodeString(mPrefs,
mCursor.getInt(ListItemsQuery.SHOW_NEXTTEXT),
mCursor.getInt(ListItemsQuery.SHOW_NEXTAIRDATETEXT),
mCursor.getString(ListItemsQuery.ITEM_TITLE)));
long airtime = mCursor.getLong(ListItemsQuery.AIRSTIME);
if (airtime != -1) {
final String[] dayAndTime = Utils
.formatToTimeAndDay(airtime, getActivity());
viewHolder.episodeTime.setText(new StringBuilder().append(dayAndTime[2])
.append(" (")
.append(dayAndTime[1])
.append(")"));
}
break;
}
// poster
final String imagePath = mCursor.getString(ListItemsQuery.SHOW_POSTER);
ImageProvider.getInstance(mContext).loadPosterThumb(viewHolder.poster, imagePath);
return convertView;
}
@Override
public void bindView(View arg0, Context arg1, Cursor arg2) {
// do nothing here
}
@Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
return null;
}
}
interface ListItemsQuery {
String[] PROJECTION = new String[] {
ListItems._ID, ListItems.LIST_ITEM_ID, ListItems.ITEM_REF_ID, ListItems.TYPE,
Shows.REF_SHOW_ID, Shows.TITLE, Shows.OVERVIEW, Shows.POSTER, Shows.NETWORK,
Shows.AIRSTIME, Shows.AIRSDAYOFWEEK, Shows.STATUS, Shows.NEXTTEXT,
Shows.NEXTAIRDATETEXT
};
String SORTING = Shows.TITLE + " COLLATE NOCASE ASC, " + ListItems.TYPE + " ASC";
int LIST_ITEM_ID = 1;
int ITEM_REF_ID = 2;
int ITEM_TYPE = 3;
int SHOW_ID = 4;
int SHOW_TITLE = 5;
int ITEM_TITLE = 6;
int SHOW_POSTER = 7;
int SHOW_NETWORK = 8;
int AIRSTIME = 9;
int SHOW_AIRSDAY = 10;
int SHOW_STATUS = 11;
int SHOW_NEXTTEXT = 12;
int SHOW_NEXTAIRDATETEXT = 13;
}
}
| Display stars in lists fragment only if the show is really starred.
| SeriesGuide/src/com/battlelancer/seriesguide/ui/ListsFragment.java | Display stars in lists fragment only if the show is really starred. |
|
Java | apache-2.0 | error: pathspec 'code/src/exm/stc/common/lang/CompileTimeArgs.java' did not match any file(s) known to git
| 3544ce42c83d8dc5d01c70b41b47fc8a03d05273 | 1 | JohnPJenkins/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,basheersubei/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,blue42u/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,basheersubei/swift-t,swift-lang/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,blue42u/swift-t,basheersubei/swift-t,swift-lang/swift-t,basheersubei/swift-t,basheersubei/swift-t,swift-lang/swift-t,swift-lang/swift-t,blue42u/swift-t,JohnPJenkins/swift-t | package exm.stc.common.lang;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import exm.stc.common.Logging;
/**
* Store bindings for argv that are specified at compile time
*/
public class CompileTimeArgs {
/** Store in sorted order as nicety */
private static final Map<String, String> compileTimeArgs =
new TreeMap<String, String>();
public static void addCompileTimeArg(String key, String value) {
String prev = compileTimeArgs.put(key, value);
if (prev != null) {
Logging.getSTCLogger().warn("Overwriting old value of \"" + key + "\"."
+ " Replaced \"" + prev + "\" with \"" + value + "\"");
}
}
public static String lookup(String key) {
return compileTimeArgs.get(key);
}
public static Map<String, String> getCompileTimeArgs() {
return Collections.unmodifiableMap(compileTimeArgs);
}
}
| code/src/exm/stc/common/lang/CompileTimeArgs.java | Add support to turbine for adding additional keyword arguments
git-svn-id: 47705994653588c662f4ea400dfe88107361c0e2@7203 dc4e9af1-7f46-4ead-bba6-71afc04862de
| code/src/exm/stc/common/lang/CompileTimeArgs.java | Add support to turbine for adding additional keyword arguments |
|
Java | apache-2.0 | error: pathspec 'src/com/theah64/mock_api/servlets/UploadImageServlet.java' did not match any file(s) known to git
| e27cc3548a1f6ec31fff6e7fbb83a2d6f88f0e65 | 1 | theapache64/Mock-API,theapache64/Mock-API,theapache64/Mock-API | package com.theah64.mock_api.servlets;
import com.theah64.mock_api.database.Projects;
import com.theah64.webengine.utils.*;
import org.json.JSONException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
@WebServlet(urlPatterns = {AdvancedBaseServlet.VERSION_CODE + "/upload_image"})
@MultipartConfig
public class UploadImageServlet extends AdvancedBaseServlet {
private static final String KEY_IMAGE = "image";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
setGETMethodNotSupported(resp);
}
@Override
protected boolean isSecureServlet() {
return true;
}
@Override
protected String[] getRequiredParameters() {
return new String[]{
};
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void doAdvancedPost() throws IOException, JSONException, Request.RequestException {
try {
//Yes,it's a valid data type
final Part dataFilePart = getHttpServletRequest().getPart(KEY_IMAGE);
if (dataFilePart != null) {
//Saving file
final Part filePart = getHttpServletRequest().getPart(KEY_IMAGE);
String fileDownloadPath = null;
if (filePart != null) {
FilePart fp = new FilePart(filePart);
final String ext = fp.getFileExtensionFromContentType();
if (ext.equals(FilePart.FILE_EXTENSION_JPG) || ext.equals(FilePart.FILE_EXTENSION_PNG)) {
//Double check if it's an image
if (ImageIO.read(filePart.getInputStream()) == null) {
throw new Request.RequestException("Invalid image : double check");
}
final File dataDir = new File("/var/www/html/mock_api_data");
if (!dataDir.exists()) {
dataDir.mkdirs();
dataDir.setReadable(true, false);
dataDir.setExecutable(true, false);
dataDir.setWritable(true, false);
}
final File imageFile = new File(dataDir.getAbsolutePath() + File.separator + fp.getRandomFileName());
final InputStream is = filePart.getInputStream();
final FileOutputStream fos = new FileOutputStream(imageFile);
int read = 0;
final byte[] buffer = new byte[1024];
while ((read = is.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
is.close();
imageFile.setReadable(true, false);
imageFile.setExecutable(true, false);
imageFile.setWritable(true, false);
fileDownloadPath = imageFile.getAbsolutePath().split("/html")[1];
getWriter().write(new Response("File uploaded", "download_link", WebEngineConfig.getBaseURL() + fileDownloadPath).getResponse());
} else {
throw new Request.RequestException("Invalid image type: " + filePart.getContentType() + ":" + ext);
}
}
} else {
throw new Request.RequestException("image missing from request");
}
} catch (javax.servlet.ServletException e) {
e.printStackTrace();
throw new Request.RequestException(e.getMessage());
}
}
}
| src/com/theah64/mock_api/servlets/UploadImageServlet.java | Got to do compression
| src/com/theah64/mock_api/servlets/UploadImageServlet.java | Got to do compression |
|
Java | apache-2.0 | error: pathspec 'app/src/main/java/com/github/keaume/amigo/export/CsvExport.java' did not match any file(s) known to git
| 018c5d0e85cd9217818766cf4ff59a96590b4500 | 1 | keaume/ProjetAmigo | package com.github.keaume.amigo.export;
import android.os.Environment;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.github.zeroxfelix.obd2fun.sql.ObdData;
import timber.log.Timber;
public class CsvExport{
private static final String EXTERNAL_STORAGE_EXPORT_DIRECTORY = "export";
private static final String EXTERNAL_STORAGE_MAIN_DIRECTORY = "obd2fun";
private final String fileName;
private final ArrayList<ObdData> obdDataList;
public CsvExport(ArrayList<ObdData> obdDataList, Date startDate, Date endDate){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd_MM_yyyy_HHmm", Locale.GERMANY);
String startDateString = dateFormat.format(startDate);
String endDateString = dateFormat.format(endDate);
this.fileName = startDateString + "-" + endDateString + ".csv";
this.obdDataList = obdDataList;
}
public CsvExport(ArrayList<ObdData> obdDataList, String sessionId){
long sessionLong = Long.parseLong(sessionId);
Date date = new Date(sessionLong);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd_MM_yyyy_HHmm", Locale.GERMANY);
this.fileName = dateFormat.format(date) + ".csv";
this.obdDataList = obdDataList;
}
public void writeFileToExternalStorage() {
List<String> csvData = new ArrayList<>();
csvData.add("SessionId;Date;ObdCommand;Result;Unit;VIN");
for(ObdData obdData : this.obdDataList){
csvData.add(obdData.getSessionId() + ";" + obdData.getRecordingDate().toString() + ";" + obdData.getObdCommandType().getNameForValue() + ";" + obdData.getCalculatedResult() + ";" + obdData.getResultUnit() + ";" + obdData.getVin());
}
Timber.d("Writing file to external storage");
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File externalStorageSaveDirectory = new File(externalStorageDirectory.getAbsolutePath() + "/" + EXTERNAL_STORAGE_MAIN_DIRECTORY + "/" + EXTERNAL_STORAGE_EXPORT_DIRECTORY);
//noinspection ResultOfMethodCallIgnored
externalStorageSaveDirectory.mkdirs();
if (externalStorageSaveDirectory.isDirectory()) {
File file = new File(externalStorageSaveDirectory, this.fileName);
try {
FileWriter fileWriter = new FileWriter(file);
for (int i = 0; i < csvData.size(); i++) {
fileWriter.write( csvData.get(i) + "\n");
}
fileWriter.close();
} catch (Exception e) {
Timber.e(e, "Writing to file %s failed", file.getAbsolutePath());
}
} else {
Timber.e("Failed to create directory %s", externalStorageSaveDirectory.getAbsolutePath());
}
}
}
| app/src/main/java/com/github/keaume/amigo/export/CsvExport.java | Create CsvExport.java | app/src/main/java/com/github/keaume/amigo/export/CsvExport.java | Create CsvExport.java |
|
Java | apache-2.0 | error: pathspec 'com/planet_ink/coffee_mud/Abilities/Properties/Prop_ReqEntry.java' did not match any file(s) known to git
| 4c08f269294fba504446db07975d0aa9b0428f61 | 1 | sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud | package com.planet_ink.coffee_mud.Abilities.Properties;
public class Prop_ReqEntry
{
}
| com/planet_ink/coffee_mud/Abilities/Properties/Prop_ReqEntry.java |
git-svn-id: svn://192.168.1.10/public/CoffeeMud@1700 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Abilities/Properties/Prop_ReqEntry.java | ||
Java | apache-2.0 | error: pathspec 'frontcache-core/src/main/java/org/frontcache/hystrix/FC_Total.java' did not match any file(s) known to git
| 3ffc01c5a8e86ca067045e9a7a6cc64794285289 | 1 | frontcache/frontcache,frontcache/frontcache | package org.frontcache.hystrix;
import org.frontcache.FrontCacheEngine;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
/**
*
* All requests through Frontcache engine
* Must use SEMAPHORE to access the same thread
*
*/
public class FC_Total extends HystrixCommand<Object> {
private final FrontCacheEngine frontCacheEngine;
public FC_Total(FrontCacheEngine frontCacheEngine) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Frontcache"))
.andCommandKey(HystrixCommandKey.Factory.asKey("FC_Total"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))
// .andCommandPropertiesDefaults(
// HystrixCommandProperties.Setter()
// .withExecutionTimeoutInMilliseconds(2000))
);
this.frontCacheEngine = frontCacheEngine;
}
@Override
protected Object run() throws Exception {
frontCacheEngine.processRequestInternal();
return null;
}
} | frontcache-core/src/main/java/org/frontcache/hystrix/FC_Total.java | hystrix command refactoring | frontcache-core/src/main/java/org/frontcache/hystrix/FC_Total.java | hystrix command refactoring |
|
Java | apache-2.0 | error: pathspec 'polydata-domain/src/main/java/com/unidev/polydata/domain/Poly.java' did not match any file(s) known to git
| 8e23ec23e4acf7e19c675d4e131bb5792577ec9c | 1 | unidev-polydata/polydata-domain,unidev-polydata/polydata-domain | package com.unidev.polydata.domain;
import java.util.Map;
/**
* Poly - storage for polydata records
*/
public interface Poly extends Map<String, Object> {
}
| polydata-domain/src/main/java/com/unidev/polydata/domain/Poly.java | Domain poly interface
| polydata-domain/src/main/java/com/unidev/polydata/domain/Poly.java | Domain poly interface |
|
Java | apache-2.0 | error: pathspec 'chapter_002/src/main/java/ru/job4j/tracker/models/package-info.java' did not match any file(s) known to git
| bca539262573e54547b4231f230b798f1f99b513 | 1 | Basil135/vkucyh | /**
* This package contains models to application tracker.
*/
package ru.job4j.tracker.models; | chapter_002/src/main/java/ru/job4j/tracker/models/package-info.java | Added package-info.java to models
| chapter_002/src/main/java/ru/job4j/tracker/models/package-info.java | Added package-info.java to models |
|
Java | apache-2.0 | error: pathspec 'dart/src/test/java/com/f2prateek/dart/internal/IntentBuilderTest.java' did not match any file(s) known to git
| 7515353c2799bc2296620691b17d5036a431bb0b | 1 | pakoito/dart,f2prateek/dart,pakoito/dart,MaTriXy/dart,brunodles/dart,brunodles/dart,AbnerLv/dart,bryant1410/dart,MaTriXy/dart,bryant1410/dart,f2prateek/dart,AbnerLv/dart | /*
* Copyright 2013 Jake Wharton
* Copyright 2014 Prateek Srivastava (@f2prateek)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.f2prateek.dart.internal;
import com.google.common.base.Joiner;
import com.google.testing.compile.JavaFileObjects;
import javax.tools.JavaFileObject;
import org.junit.Test;
import static com.f2prateek.dart.internal.ProcessorTestUtilities.dartProcessors;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import static org.truth0.Truth.ASSERT;
public class IntentBuilderTest {
@Test public void injectingExtra() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test extends Activity {", //
" @InjectExtra(\"key\") String extra;", //
"}" //
));
JavaFileObject expectedSource =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;" , //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra;", //
"", //
" private boolean extraIsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withExtra(String extra) {", //
" this.extra = extra;", //
" extraIsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (extraIsSet) {", //
" intent.putExtra(\"key\", extra);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void injectingAllPrimitives() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test extends Activity {", //
" @InjectExtra(\"key_bool\") boolean aBool;", //
" @InjectExtra(\"key_byte\") byte aByte;", //
" @InjectExtra(\"key_short\") short aShort;", //
" @InjectExtra(\"key_int\") int anInt;", //
" @InjectExtra(\"key_long\") long aLong;", //
" @InjectExtra(\"key_char\") char aChar;", //
" @InjectExtra(\"key_float\") float aFloat;", //
" @InjectExtra(\"key_double\") double aDouble;", //
"}" //
));
JavaFileObject expectedSource =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private boolean aBool;", //
"", //
" private boolean aBoolIsSet;", //
"", //
" private byte aByte;", //
"", //
" private boolean aByteIsSet;", //
"", //
" private short aShort;", //
"", //
" private boolean aShortIsSet;", //
"", //
" private int anInt;", //
"", //
" private boolean anIntIsSet;", //
"", //
" private long aLong;", //
"", //
" private boolean aLongIsSet;", //
"", //
" private char aChar;", //
"", //
" private boolean aCharIsSet;", //
"", //
" private float aFloat;", //
"", //
" private boolean aFloatIsSet;", //
"", //
" private double aDouble;", //
"", //
" private boolean aDoubleIsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withABool(boolean aBool) {", //
" this.aBool = aBool;", //
" aBoolIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withAByte(byte aByte) {", //
" this.aByte = aByte;", //
" aByteIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withAShort(short aShort) {", //
" this.aShort = aShort;", //
" aShortIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withAnInt(int anInt) {", //
" this.anInt = anInt;", //
" anIntIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withALong(long aLong) {", //
" this.aLong = aLong;", //
" aLongIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withAChar(char aChar) {", //
" this.aChar = aChar;", //
" aCharIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withAFloat(float aFloat) {", //
" this.aFloat = aFloat;", //
" aFloatIsSet = true;", //
" return this;", //
" }", //
"", //
" public TestIntentBuilder withADouble(double aDouble) {", //
" this.aDouble = aDouble;", //
" aDoubleIsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (aBoolIsSet) {", //
" intent.putExtra(\"key_bool\", aBool);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aBool is mandatory\");", //
" }", //
" if (aByteIsSet) {", //
" intent.putExtra(\"key_byte\", aByte);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aByte is mandatory\");", //
" }", //
" if (aShortIsSet) {", //
" intent.putExtra(\"key_short\", aShort);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aShort is mandatory\");", //
" }", //
" if (anIntIsSet) {", //
" intent.putExtra(\"key_int\", anInt);", //
" } else {", //
" throw new IllegalStateException(\"Parameter anInt is mandatory\");", //
" }", //
" if (aLongIsSet) {", //
" intent.putExtra(\"key_long\", aLong);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aLong is mandatory\");", //
" }", //
" if (aCharIsSet) {", //
" intent.putExtra(\"key_char\", aChar);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aChar is mandatory\");", //
" }", //
" if (aFloatIsSet) {", //
" intent.putExtra(\"key_float\", aFloat);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aFloat is mandatory\");", //
" }", //
" if (aDoubleIsSet) {", //
" intent.putExtra(\"key_double\", aDouble);", //
" } else {", //
" throw new IllegalStateException(\"Parameter aDouble is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void oneFindPerKey() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test extends Activity {", //
" @InjectExtra(\"key\") String extra1;", //
" @InjectExtra(\"key\") String extra2;", //
" @InjectExtra(\"key\") String extra3;", //
"}" //
));
JavaFileObject expectedSource =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra1;", //
"", //
" private boolean extra1IsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withExtra1(String extra1) {", //
" this.extra1 = extra1;", //
" extra1IsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (extra1IsSet) {", //
" intent.putExtra(\"key\", extra1);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra1 is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void defaultKey() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test extends Activity {", //
" @InjectExtra String key;", //
"}" //
));
JavaFileObject expectedSource =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private String key;", //
"", //
" private boolean keyIsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withKey(String key) {", //
" this.key = key;", //
" keyIsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (keyIsSet) {", //
" intent.putExtra(\"key\", key);", //
" } else {", //
" throw new IllegalStateException(\"Parameter key is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void superclass() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test extends Activity {", //
" @InjectExtra(\"key\") String extra;", //
"}", //
"class TestOne extends Test {", //
" @InjectExtra(\"key\") String extra1;", //
"}", //
"class TestTwo extends Test {", //
"}" //
));
JavaFileObject expectedSource1 =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra;", //
"", //
" private boolean extraIsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withExtra(String extra) {", //
" this.extra = extra;", //
" extraIsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (extraIsSet) {", //
" intent.putExtra(\"key\", extra);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
JavaFileObject expectedSource2 =
JavaFileObjects.forSourceString("test/TestOneIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestOneIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra1;", //
"", //
" private boolean extra1IsSet;", //
"", //
" public TestOneIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestOneIntentBuilder withExtra1(String extra1) {", //
" this.extra1 = extra1;", //
" extra1IsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.TestOne.class);", //
" if (extra1IsSet) {", //
" intent.putExtra(\"key\", extra1);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra1 is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
@Test public void genericSuperclass() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( //
"package test;", //
"import android.app.Activity;", //
"import com.f2prateek.dart.InjectExtra;", //
"public class Test<T> extends Activity {", //
" @InjectExtra(\"key\") String extra;", //
"}", //
"class TestOne extends Test<String> {", //
" @InjectExtra(\"key\") String extra1;", //
"}", //
"class TestTwo extends Test<Object> {", //
"}" //
));
JavaFileObject expectedSource1 =
JavaFileObjects.forSourceString("test/TestIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra;", //
"", //
" private boolean extraIsSet;", //
"", //
" public TestIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestIntentBuilder withExtra(String extra) {", //
" this.extra = extra;", //
" extraIsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.Test.class);", //
" if (extraIsSet) {", //
" intent.putExtra(\"key\", extra);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
JavaFileObject expectedSource2 =
JavaFileObjects.forSourceString("test/TestOneIntentBuilder", Joiner.on('\n').join( //
"package test;", //
"", //
"import android.content.Context;", //
"import android.content.Intent;", //
"import java.lang.String;", //
"", //
"public class TestOneIntentBuilder {", //
" private final Context context;", //
"", //
" private String extra1;", //
"", //
" private boolean extra1IsSet;", //
"", //
" public TestOneIntentBuilder(Context context) {", //
" this.context = context;", //
" }", //
"", //
" public TestOneIntentBuilder withExtra1(String extra1) {", //
" this.extra1 = extra1;", //
" extra1IsSet = true;", //
" return this;", //
" }", //
"", //
" public Intent build() {", //
" Intent intent = new Intent(context, test.TestOne.class);", //
" if (extra1IsSet) {", //
" intent.putExtra(\"key\", extra1);", //
" } else {", //
" throw new IllegalStateException(\"Parameter extra1 is mandatory\");", //
" }", //
" return intent;", //
" }", //
"}" //
));
ASSERT.about(javaSource())
.that(source)
.processedWith(dartProcessors())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
}
| dart/src/test/java/com/f2prateek/dart/internal/IntentBuilderTest.java | Add truth test for intent builder
| dart/src/test/java/com/f2prateek/dart/internal/IntentBuilderTest.java | Add truth test for intent builder |
|
Java | apache-2.0 | error: pathspec 'projects/question/src/org/batfish/question/CompositeQuestionPlugin.java' did not match any file(s) known to git
| 10bd8df5ec36f5c59349f19183d0843f3d263164 | 1 | intentionet/batfish,batfish/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,dhalperi/batfish | package org.batfish.question;
import java.util.ArrayList;
import java.util.List;
import org.batfish.common.Answerer;
import org.batfish.common.plugin.IBatfish;
import org.batfish.datamodel.answers.AnswerElement;
import org.batfish.datamodel.questions.Question;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CompositeQuestionPlugin extends QuestionPlugin {
public static class CompositeAnswerElement implements AnswerElement {
private static final String ANSWERS_VAR = "answers";
private List<AnswerElement> _answers;
public CompositeAnswerElement() {
_answers = new ArrayList<>();
}
@JsonProperty(ANSWERS_VAR)
public List<AnswerElement> getAnswers() {
return _answers;
}
@JsonProperty(ANSWERS_VAR)
public void setAnswers(List<AnswerElement> answers) {
_answers = answers;
}
}
public static class CompositeAnswerer extends Answerer {
public CompositeAnswerer(Question question, IBatfish batfish) {
super(question, batfish);
}
@Override
public CompositeAnswerElement answer() {
CompositeQuestion question = (CompositeQuestion) _question;
CompositeAnswerElement answerElement = new CompositeAnswerElement();
for (Question innerQuestion : question._questions) {
String innerQuestionName = innerQuestion.getName();
Answerer innerAnswerer = _batfish.getAnswererCreators()
.get(innerQuestionName).apply(innerQuestion, _batfish);
AnswerElement innerAnswer = innerAnswerer.answer();
answerElement._answers.add(innerAnswer);
}
return answerElement;
}
}
public static class CompositeQuestion extends Question {
private static final String QUESTIONS_VAR = "questions";
private List<Question> _questions;
public CompositeQuestion() {
_questions = new ArrayList<>();
}
@Override
public boolean getDataPlane() {
return false;
}
@Override
public String getName() {
return "composite";
}
@JsonProperty(QUESTIONS_VAR)
public List<Question> getQuestions() {
return _questions;
}
@Override
public boolean getTraffic() {
return false;
}
@JsonProperty(QUESTIONS_VAR)
public void setQuestions(List<Question> questions) {
_questions = questions;
}
}
@Override
protected CompositeAnswerer createAnswerer(Question question,
IBatfish batfish) {
return new CompositeAnswerer(question, batfish);
}
@Override
protected CompositeQuestion createQuestion() {
return new CompositeQuestion();
}
}
| projects/question/src/org/batfish/question/CompositeQuestionPlugin.java | add Composite base question
| projects/question/src/org/batfish/question/CompositeQuestionPlugin.java | add Composite base question |
|
Java | apache-2.0 | error: pathspec 'rapidoid-integrate/src/main/java/org/rapidoid/integrate/JMustacheViewRenderer.java' did not match any file(s) known to git
| 0ce7708ecdb3c3303de96efa65bd213ffc8288b7 | 1 | rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid | package org.rapidoid.integrate;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.http.customize.ViewRenderer;
import org.rapidoid.io.Res;
import org.rapidoid.render.Templates;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
/*
* #%L
* rapidoid-integrate
* %%
* Copyright (C) 2014 - 2016 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* <p>ViewRenderer for samskivert's JMustache. <br>
* To use this call {@code My.viewRenderer(new JMustacheViewRenderer());} </p>
*
* <p>
* By default template partials should be stored in /templates/partials folder and
* should have the .mustache file extension. You can change this by setting a new
* compiler with your own template loader. Example on partials:
* </p>
* {{>name}} somewhere will by default look for a /templates/partials/name.mustache
* in your resources folder and load the contents into the mustache template.
*
*
* <p>If you want to change any compiler configurations or add partial support do e.g.:</p>
* <pre>{@code
* JMustacheViewRenderer renderer = (JMustacheViewRenderer) My.getViewRenderer();
* renderer.setCompiler(Mustache.compiler().defaultValue("Template not found!"));
* }</pre>
*/
@Authors("kormakur")
@Since("5.1.8")
public class JMustacheViewRenderer extends RapidoidThing implements ViewRenderer {
private Mustache.TemplateLoader defaultPartialLoader = new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) throws Exception {
return Templates.resource("templates/partials/" + name + ".mustache").getReader();
}
};
private Mustache.Compiler compiler = Mustache.compiler().withLoader(defaultPartialLoader);
@Override
public boolean render(String viewName, Object[] model, OutputStream out) throws Exception {
Res template = Templates.resource(viewName + ".html");
if (!template.exists()) {
return false;
}
Template mustache = compiler.compile(template.getContent());
PrintWriter writer = new PrintWriter(out);
mustache.execute(model[model.length-1], writer);
writer.flush();
return true;
}
/**
* Change the compiler settings e.g.
* <pre>
* {@code
* renderer.setCompiler(Mustache.compiler().defaultValue("Template not found"));
* }
* </pre>
* @param compiler Usually Mustache.compiler() with supplied settings.
*/
public void setCompiler(Mustache.Compiler compiler) {
if(Mustache.compiler().loader.equals(compiler.loader)) {
this.compiler = compiler.withLoader(defaultPartialLoader);
}
else {
this.compiler = compiler;
}
}
}
| rapidoid-integrate/src/main/java/org/rapidoid/integrate/JMustacheViewRenderer.java | Added support for JMustache view renderer
| rapidoid-integrate/src/main/java/org/rapidoid/integrate/JMustacheViewRenderer.java | Added support for JMustache view renderer |
|
Java | artistic-2.0 | error: pathspec 'src/main/java/org/pfaa/chemica/processing/CanonicalForms.java' did not match any file(s) known to git
| 2c4d00c05d892068594e967b796c9015c75387ed | 1 | lawremi/PerFabricaAdAstra,lawremi/PerFabricaAdAstra | package org.pfaa.chemica.processing;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.pfaa.chemica.model.IndustrialMaterial;
import org.pfaa.chemica.processing.Form;
import com.google.common.collect.Sets;
public class CanonicalForms {
private static Map<IndustrialMaterial, Set<Form>> formsForMaterial;
public static void register(IndustrialMaterial material, Form... forms) {
Set<Form> materialForms = formsForMaterial.get(material);
if (materialForms == null) {
materialForms = Sets.newHashSet();
formsForMaterial.put(material, materialForms);
}
materialForms.addAll(Arrays.asList(forms));
}
public static Set<Form> of(IndustrialMaterial material) {
return Collections.unmodifiableSet(formsForMaterial.get(material));
}
}
| src/main/java/org/pfaa/chemica/processing/CanonicalForms.java | introduce notion of CanonicalForms, inferred from item registration
| src/main/java/org/pfaa/chemica/processing/CanonicalForms.java | introduce notion of CanonicalForms, inferred from item registration |
|
Java | bsd-3-clause | 9cc6e8864f983e7400cc266b83e74179c112e64f | 0 | karouani/javasimon,ferstl/javasimon,mukteshkrmishra/javasimon,mukteshkrmishra/javasimon,ilmaliek/javasimon,mukteshkrmishra/javasimon,tfordeveaux/javasimon,tfordeveaux/javasimon,tfordeveaux/javasimon,google-code-export/javasimon,ilmaliek/javasimon,ilmaliek/javasimon,tectronics/javasimon,karouani/javasimon,tectronics/javasimon,Muktesh01/javasimon,syzer/javasimon,tectronics/javasimon,Muktesh01/javasimon,virgo47/javasimon,ilmaliek/javasimon,Acidburn0zzz/javasimon,syzer/javasimon,dqVM/javasimon-DQ,virgo47/javasimon,Acidburn0zzz/javasimon,google-code-export/javasimon,virgo47/javasimon,karouani/javasimon,syzer/javasimon,Muktesh01/javasimon,ferstl/javasimon,Muktesh01/javasimon,google-code-export/javasimon,dqVM/javasimon-DQ,ferstl/javasimon,mukteshkrmishra/javasimon,dqVM/javasimon-DQ,syzer/javasimon,google-code-export/javasimon,ferstl/javasimon,tfordeveaux/javasimon,Acidburn0zzz/javasimon,dqVM/javasimon-DQ,karouani/javasimon,Acidburn0zzz/javasimon,tectronics/javasimon | package org.javasimon.javaee;
import org.javasimon.Manager;
import org.javasimon.SimonManager;
import org.javasimon.Split;
import org.javasimon.utils.SimonUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Simon Servlet filter measuring HTTP request execution times. Non-HTTP usages are not supported.
*
* @author Richard Richter
* @version $Revision$ $Date$
* @since 2.3
*/
public class SimonServletFilter implements Filter {
/**
* Default prefix for web filter Simons if no "prefix" init parameter is used.
*/
public static final String DEFAULT_SIMON_PREFIX = "org.javasimon.web";
/**
* Name of filter init parameter for Simon name prefix.
*/
public static final String INIT_PARAM_PREFIX = "prefix";
/**
* Name of filter init parameter determining the attribute name under which
* Simon Manager is to be published in servlet context attributes. If this
* parameter is not used the manager is not published.
*/
public static final String INIT_PARAM_PUBLISH_MANAGER = "manager-attribute-name";
/**
* Name of filter init parameter that sets the value of threshold in milliseconds
* for maximal request duration beyond which all splits will be dumped to log.
*/
public static final String INIT_PARAM_REPORT_THRESHOLD = "report-threshold";
/**
* Name of filter init parameter that sets relative ULR path that will provide
* Simon console page.
*/
public static final String INIT_PARAM_SIMON_CONSOLE = "console-path";
/**
* Public thread local list of splits used to cummulate all splits for the request.
*/
public static final ThreadLocal<List<Split>> SPLITS = new ThreadLocal<List<Split>>();
private String simonPrefix = DEFAULT_SIMON_PREFIX;
private Long reportThreshold;
/**
* URL path that displays Simon web console (or null if no console is required).
*/
private String consolePath;
/**
* Initialization method that processes {@link #INIT_PARAM_PREFIX} and {@link #INIT_PARAM_PUBLISH_MANAGER}
* parameters from {@literal web.xml}.
*
* @param filterConfig filter config object
*/
public void init(FilterConfig filterConfig) {
if (filterConfig.getInitParameter(INIT_PARAM_PREFIX) != null) {
simonPrefix = filterConfig.getInitParameter(INIT_PARAM_PREFIX);
}
String publishManager = filterConfig.getInitParameter(INIT_PARAM_PUBLISH_MANAGER);
if (publishManager != null) {
filterConfig.getServletContext().setAttribute(publishManager, SimonManager.manager());
}
String reportTreshold = filterConfig.getInitParameter(INIT_PARAM_REPORT_THRESHOLD);
if (reportTreshold != null) {
try {
this.reportThreshold = Long.parseLong(reportTreshold);
} catch (NumberFormatException e) {
// ignore
}
}
String consolePath = filterConfig.getInitParameter(INIT_PARAM_SIMON_CONSOLE);
if (consolePath != null) {
this.consolePath = consolePath;
}
}
/**
* Wraps the HTTP request with Simon measuring. Separate Simons are created for different URIs (parameters
* ignored).
*
* @param servletRequest HTTP servlet request
* @param response HTTP servlet response
* @param filterChain filter chain
* @throws IOException possibly thrown by other filter/serlvet in the chain
* @throws ServletException possibly thrown by other filter/serlvet in the chain
*/
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
if (consolePath != null && request.getRequestURI().startsWith(consolePath)) {
consolePage(request, (HttpServletResponse) response);
return;
}
String simonName = getSimonName(request);
SPLITS.set(new ArrayList<Split>());
Split split = SimonManager.getStopwatch(simonPrefix + Manager.HIERARCHY_DELIMITER + simonName).start();
try {
filterChain.doFilter(request, response);
} finally {
split.stop();
if (reportThreshold != null && split.runningFor() > reportThreshold) {
// logSomehow(SPLITS.get()); TODO + callback
}
SPLITS.remove();
}
}
private void consolePage(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.setHeader("Pragma", "no-cache");
String subcommand = request.getRequestURI().substring(consolePath.length());
if (subcommand.isEmpty()) {
printSimonTree(response);
} else if (subcommand.equalsIgnoreCase("/clear")) {
SimonManager.clear();
response.getOutputStream().println("Simon Manager was cleared");
} else {
response.getOutputStream().println("Invalid command\n");
simonHelp(response);
}
}
private void simonHelp(ServletResponse response) throws IOException {
response.getOutputStream().println("Simon Console help:");
}
private void printSimonTree(ServletResponse response) throws IOException {
response.getOutputStream().println(SimonUtils.simonTreeString(SimonManager.getRootSimon()));
}
/**
* Returns Simon name for the specified HTTP request. By default it contains URI without parameters with
* all slashes replaced for dots (slashes then determines position in Simon hierarchy). Method can be
* overriden.
*
* @param request HTTP request
* @return fully qualified name of the Simon
*/
protected String getSimonName(HttpServletRequest request) {
StringBuilder name = new StringBuilder(request.getRequestURI().replaceAll("\\.+", "").replace('/', '.'));
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == '?') {
name.delete(i, name.length());
break;
}
if (SimonUtils.ALLOWED_CHARS.indexOf(name.charAt(i)) == -1) {
name.deleteCharAt(i);
i--;
}
}
return name.toString().replaceAll("^\\.+", "").replaceAll("\\.+", ".");
}
/**
* Does nothing - just implements the contract.
*/
public void destroy() {
}
}
| javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java | package org.javasimon.javaee;
import org.javasimon.Manager;
import org.javasimon.SimonManager;
import org.javasimon.Split;
import org.javasimon.utils.SimonUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Simon Servlet filter measuring HTTP request execution times. Non-HTTP usages are not supported.
*
* @author Richard Richter
* @version $Revision$ $Date$
* @since 2.3
*/
public class SimonServletFilter implements Filter {
/**
* Default prefix for web filter Simons if no "prefix" init parameter is used.
*/
public static final String DEFAULT_SIMON_PREFIX = "org.javasimon.web";
/**
* Name of filter init parameter for Simon name prefix.
*/
public static final String INIT_PARAM_PREFIX = "prefix";
/**
* Name of filter init parameter determining the attribute name under which
* Simon Manager is to be published in servlet context attributes. If this
* parameter is not used the manager is not published.
*/
public static final String INIT_PARAM_PUBLISH_MANAGER = "manager-attribute-name";
/**
* Name of filter init parameter that sets the value of threshold in milliseconds
* for maximal request duration beyond which all splits will be dumped to log.
*/
public static final String INIT_PARAM_REPORT_THRESHOLD = "report-threshold";
/**
* Name of filter init parameter that sets relative ULR path that will provide
* Simon report page.
*/
public static final String INIT_PARAM_REPORT_PATH = "report-path";
/**
* Public thread local list of splits used to cummulate all splits for the request.
*/
public static final ThreadLocal<List<Split>> SPLITS = new ThreadLocal<List<Split>>();
private String simonPrefix = DEFAULT_SIMON_PREFIX;
private Long reportThreshold;
/**
* URL path that displays report (or null if no report is required).
*/
private String reportPath;
/**
* Initialization method that processes {@link #INIT_PARAM_PREFIX} and {@link #INIT_PARAM_PUBLISH_MANAGER}
* parameters from {@literal web.xml}.
*
* @param filterConfig filter config object
*/
public void init(FilterConfig filterConfig) {
if (filterConfig.getInitParameter(INIT_PARAM_PREFIX) != null) {
simonPrefix = filterConfig.getInitParameter(INIT_PARAM_PREFIX);
}
String publishManager = filterConfig.getInitParameter(INIT_PARAM_PUBLISH_MANAGER);
if (publishManager != null) {
filterConfig.getServletContext().setAttribute(publishManager, SimonManager.manager());
}
String reportTreshold = filterConfig.getInitParameter(INIT_PARAM_REPORT_THRESHOLD);
if (reportTreshold != null) {
try {
this.reportThreshold = Long.parseLong(reportTreshold);
} catch (NumberFormatException e) {
// ignore
}
}
String reportPath = filterConfig.getInitParameter(INIT_PARAM_REPORT_PATH);
if (reportPath != null) {
this.reportPath = reportPath;
}
}
/**
* Wraps the HTTP request with Simon measuring. Separate Simons are created for different URIs (parameters
* ignored).
*
* @param servletRequest HTTP servlet request
* @param response HTTP servlet response
* @param filterChain filter chain
* @throws IOException possibly thrown by other filter/serlvet in the chain
* @throws ServletException possibly thrown by other filter/serlvet in the chain
*/
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
if (reportPath != null && request.getRequestURI().startsWith(reportPath)) {
response.getOutputStream().println(SimonUtils.simonTreeString(SimonManager.getRootSimon()));
return;
}
String simonName = getSimonName(request);
SPLITS.set(new ArrayList<Split>());
Split split = SimonManager.getStopwatch(simonPrefix + Manager.HIERARCHY_DELIMITER + simonName).start();
try {
filterChain.doFilter(request, response);
} finally {
split.stop();
if (reportThreshold != null && split.runningFor() > reportThreshold) {
// logSomehow(SPLITS.get()); TODO + callback
}
SPLITS.remove();
}
}
/**
* Returns Simon name for the specified HTTP request. By default it contains URI without parameters with
* all slashes replaced for dots (slashes then determines position in Simon hierarchy). Method can be
* overriden.
*
* @param request HTTP request
* @return fully qualified name of the Simon
*/
protected String getSimonName(HttpServletRequest request) {
StringBuilder name = new StringBuilder(request.getRequestURI().replaceAll("\\.+", "").replace('/', '.'));
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == '?') {
name.delete(i, name.length());
break;
}
if (SimonUtils.ALLOWED_CHARS.indexOf(name.charAt(i)) == -1) {
name.deleteCharAt(i);
i--;
}
}
return name.toString().replaceAll("^\\.+", "").replaceAll("\\.+", ".");
}
/**
* Does nothing - just implements the contract.
*/
public void destroy() {
}
}
| added "simon console" to servlet filter, plain text, but working :-)
git-svn-id: 63b603a2a0cd69e5d3fd458c77bfcc9aeec23abf@322 b27f8733-aa53-0410-bf41-0b3b0dae0d5f
| javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java | added "simon console" to servlet filter, plain text, but working :-) |
|
Java | bsd-3-clause | error: pathspec 'src/test/java/com/notnoop/apns/APNSTest.java' did not match any file(s) known to git
| 383884f79d5c0214ed9992fac2eed8dbf9a6d722 | 1 | treejames/java-apns,talk-to/java-apns,noahxinhao/java-apns,treejames/java-apns,talk-to/java-apns,borellaster/java-apns,flozano/java-apns,l0s/java-apns,SinnerSchraderMobileMirrors/java-apns,notnoop/java-apns,l0s/java-apns,Catapush/java-apns,mukhanov/java-apns,t-watana/java-apns,bilalsas/java-apns,notnoop/java-apns,leancloud/java-apns,mukhanov/java-apns,t-watana/java-apns,Catapush/java-apns,borellaster/java-apns,noahxinhao/java-apns | package com.notnoop.apns;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
/**
* Silly Tests
*/
public class APNSTest {
@Test
public void testInstances() {
assertThat(APNS.newPayload(), is(PayloadBuilder.class));
assertThat(APNS.newService(), is(ApnsServiceBuilder.class));
}
@Test
public void payloadShouldGetNewInstances() {
assertNotSame(APNS.newPayload(), APNS.newPayload());
}
@Test
public void newServiceGetNewInstances() {
assertNotSame(APNS.newService(), APNS.newService());
}
}
| src/test/java/com/notnoop/apns/APNSTest.java | add more silly tests
| src/test/java/com/notnoop/apns/APNSTest.java | add more silly tests |
|
Java | bsd-3-clause | error: pathspec 'xstream/src/test/com/thoughtworks/acceptance/ImplicitTest.java' did not match any file(s) known to git
| a9daad74b3be868b7e5af8586e869ef4f05de4b9 | 1 | svn2github/xstream,svn2github/xstream | /*
* Copyright (C) 2013 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 22. April 2013 by Joerg Schaible
*/
package com.thoughtworks.acceptance;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.thoughtworks.xstream.core.util.OrderRetainingMap;
public class ImplicitTest extends AbstractAcceptanceTest {
public static class AllImplicitTypes {
public static class A {
public int val;
}
public static class B {
public int val;
}
public static class C {
public Integer val;
}
public A[] aArray = new A[2];
public List bList = new ArrayList();
public Map cMap = new OrderRetainingMap();
}
public void testAllImplicitTypesAtOnce()
{
xstream.alias("implicits", AllImplicitTypes.class);
xstream.alias("a", AllImplicitTypes.A.class);
xstream.alias("b", AllImplicitTypes.B.class);
xstream.alias("c", AllImplicitTypes.C.class);
xstream.addDefaultImplementation(OrderRetainingMap.class, Map.class);
xstream.addImplicitArray(AllImplicitTypes.class, "aArray");
xstream.addImplicitCollection(AllImplicitTypes.class, "bList");
xstream.addImplicitMap(AllImplicitTypes.class, "cMap", AllImplicitTypes.C.class, "val");
String expected = "" +
"<implicits>\n" +
" <a>\n" +
" <val>1</val>\n" +
" </a>\n" +
" <a>\n" +
" <val>2</val>\n" +
" </a>\n" +
" <b>\n" +
" <val>3</val>\n" +
" </b>\n" +
" <b>\n" +
" <val>4</val>\n" +
" </b>\n" +
" <c>\n" +
" <val>5</val>\n" +
" </c>\n" +
" <c>\n" +
" <val>6</val>\n" +
" </c>\n" +
"</implicits>";
AllImplicitTypes implicits = new AllImplicitTypes();
implicits.aArray[0] = new AllImplicitTypes.A();
implicits.aArray[0].val = 1;
implicits.aArray[1] = new AllImplicitTypes.A();
implicits.aArray[1].val = 2;
implicits.bList.add(new AllImplicitTypes.B());
((AllImplicitTypes.B)implicits.bList.get(0)).val = 3;
implicits.bList.add(new AllImplicitTypes.B());
((AllImplicitTypes.B)implicits.bList.get(1)).val = 4;
AllImplicitTypes.C c = new AllImplicitTypes.C();
c.val = new Integer(5);
implicits.cMap.put(c.val, c);
c = new AllImplicitTypes.C();
c.val = new Integer(6);
implicits.cMap.put(c.val, c);
assertBothWays(implicits, expected);
}
}
| xstream/src/test/com/thoughtworks/acceptance/ImplicitTest.java | Add acceptance tests that uses all 3 implicit types at once.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@2060 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
| xstream/src/test/com/thoughtworks/acceptance/ImplicitTest.java | Add acceptance tests that uses all 3 implicit types at once. |
|
Java | bsd-3-clause | error: pathspec 'SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/prediction/DBLanguage.java' did not match any file(s) known to git
| 025421065d197600d7d06faa41e6b1a179700ddb | 1 | BuildmLearn/Indic-Language-Input-Tool-ILIT | package org.buildmlearn.indickeyboard.prediction;
/**
* Created by bhavita on 18/8/16.
*/
public class DBLanguage {
private static String[] predictionLanguages ={ "hindi"}; //Add others here
public static boolean hasPrediction(String lang)
{
boolean result=false;
for(String i:predictionLanguages)
{
if(i==lang)
{
result=true;
break;
}
}
return result;
}
}
| SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/prediction/DBLanguage.java | Added DB utlity
| SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/prediction/DBLanguage.java | Added DB utlity |
|
Java | mit | 79235f15ba5ffd37f8d62532859445ab2e9df9bc | 0 | Dimmerworld/TechReborn,TechReborn/TechReborn,drcrazy/TechReborn | package techreborn.client.hud;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import org.lwjgl.opengl.GL11;
import techreborn.client.keybindings.KeyBindings;
import techreborn.config.ConfigTechReborn;
import techreborn.util.Color;
public class ChargeHud
{
public static final ChargeHud instance = new ChargeHud();
private static Minecraft mc = Minecraft.getMinecraft();
public static KeyBindings key;
public static boolean showHud = true;
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.LOW)
public void onRenderExperienceBar(RenderGameOverlayEvent event)
{
if (key.config.isPressed())
{
showHud = !showHud;
}
if (event.isCancelable() || event.type != ElementType.ALL)
return;
if (mc.inGameHasFocus || (mc.currentScreen != null && mc.gameSettings.showDebugInfo))
drawChargeHud(event.resolution);
}
public void drawChargeHud(ScaledResolution res)
{
EntityPlayer player = mc.thePlayer;
ItemStack stack = player.getCurrentArmor(2);
ItemStack stack2 = mc.thePlayer.inventory.getCurrentItem();
if (showHud)
{
if(stack2 != null)
{
if ((stack2.getItem() instanceof IElectricItem))
{
double MaxCharge = ((IElectricItem) stack2.getItem()).getMaxCharge(stack2);
double CurrentCharge = ElectricItem.manager.getCharge(stack2);
Color color = Color.GREEN;
double quarter = MaxCharge / 4;
double half = MaxCharge / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
RenderItem.getInstance().renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, stack2, 0, 20);
RenderItem.getInstance().renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, stack2, 0, 20);
if(CurrentCharge <= half)
{
color = Color.YELLOW;
}
if(CurrentCharge <= quarter)
{
color = Color.DARK_RED;
}
mc.fontRenderer.drawString(color + GetEUString(CurrentCharge) + "/" + GetEUString(MaxCharge), 20, 25, 0);
}
}
if(stack != null)
{
if((stack.getItem() instanceof IElectricItem) && ConfigTechReborn.ShowChargeHud)
{
double MaxCharge = ((IElectricItem) stack.getItem()).getMaxCharge(stack);
double CurrentCharge = ElectricItem.manager.getCharge(stack);
Color color = Color.GREEN;
double quarter = MaxCharge / 4;
double half = MaxCharge / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
//Render the stack
RenderItem.getInstance().renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, stack, 0, 0);
//Render Overlay
RenderItem.getInstance().renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, stack, 0, 0);
//Get the color depending on current charge
if(CurrentCharge <= half)
{
color = Color.YELLOW;
}
if(CurrentCharge <= quarter)
{
color = Color.DARK_RED;
}
mc.fontRenderer.drawString(color + GetEUString(CurrentCharge) + "/" + GetEUString(MaxCharge), 20, 5, 0);
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private String GetEUString(double euValue)
{
if (euValue > 1000000) {
double tenX = Math.round(euValue / 100000);
return Double.toString(tenX / 10.0).concat("M ");
}
else if (euValue > 1000) {
double tenX = Math.round(euValue / 100);
return Double.toString(tenX / 10.0).concat("k ");
}
else {
return Double.toString(Math.floor(euValue)).concat(" EU");
}
}
}
| src/main/java/techreborn/client/hud/ChargeHud.java | package techreborn.client.hud;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import org.lwjgl.opengl.GL11;
import techreborn.client.keybindings.KeyBindings;
import techreborn.config.ConfigTechReborn;
import techreborn.util.Color;
public class ChargeHud
{
public static final ChargeHud instance = new ChargeHud();
private static Minecraft mc = Minecraft.getMinecraft();
public static KeyBindings key;
public static boolean showHud = true;
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.LOW)
public void onRenderExperienceBar(RenderGameOverlayEvent event)
{
if (key.config.isPressed())
{
showHud = !showHud;
}
if (event.isCancelable() || event.type != ElementType.ALL)
return;
if (mc.inGameHasFocus || (mc.currentScreen != null && mc.gameSettings.showDebugInfo))
drawChargeHud(event.resolution);
}
public void drawChargeHud(ScaledResolution res)
{
EntityPlayer player = mc.thePlayer;
ItemStack stack = player.getCurrentArmor(2);
ItemStack stack2 = mc.thePlayer.inventory.getCurrentItem();
if (showHud)
{
if(stack2 != null)
{
if ((stack2.getItem() instanceof IElectricItem))
{
double MaxCharge = ((IElectricItem) stack2.getItem()).getMaxCharge(stack2);
double CurrentCharge = ElectricItem.manager.getCharge(stack2);
Color color = Color.GREEN;
double quarter = MaxCharge / 4;
double half = MaxCharge / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
RenderItem.getInstance().renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, stack2, 0, 20);
RenderItem.getInstance().renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, stack2, 0, 20);
if(CurrentCharge <= half)
{
color = Color.YELLOW;
}
if(CurrentCharge <= quarter)
{
color = Color.DARK_RED;
}
mc.fontRenderer.drawString(color + GetEUString(CurrentCharge) + "/" + GetEUString(MaxCharge), 20, 25, 0);
}
}
if(stack != null)
{
if((stack.getItem() instanceof IElectricItem) && ConfigTechReborn.ShowChargeHud)
{
double MaxCharge = ((IElectricItem) stack.getItem()).getMaxCharge(stack);
double CurrentCharge = ElectricItem.manager.getCharge(stack);
Color color = Color.GREEN;
double quarter = MaxCharge / 4;
double half = MaxCharge / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
//Render the stack
RenderItem.getInstance().renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, stack, 0, 0);
//Render Overlay
RenderItem.getInstance().renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, stack, 0, 0);
//Get the color depending on current charge
if(CurrentCharge <= half)
{
color = Color.YELLOW;
}
if(CurrentCharge <= quarter)
{
color = Color.DARK_RED;
}
mc.fontRenderer.drawString(color + GetEUString(CurrentCharge) + "/" + GetEUString(MaxCharge), 20, 5, 0);
}
}
}
}
private String GetEUString(double euValue)
{
if (euValue > 1000000) {
double tenX = Math.round(euValue / 100000);
return Double.toString(tenX / 10.0).concat("M ");
}
else if (euValue > 1000) {
double tenX = Math.round(euValue / 100);
return Double.toString(tenX / 10.0).concat("k ");
}
else {
return Double.toString(Math.floor(euValue)).concat(" EU");
}
}
}
| Fixed gui's changing colour while in f3
| src/main/java/techreborn/client/hud/ChargeHud.java | Fixed gui's changing colour while in f3 |
|
Java | mit | 9006178a05df3586cc4bfac61634f3bed735cbc1 | 0 | universsky/jedis,perrystreetsoftware/jedis,thinkbread/jedis,zts1993/jedis,hrqiang/jedis,smagellan/jedis,carlvine500/jedis,yapei123/jedis,fengshao0907/jedis,softliumin/jedis,aiyan2001/jedis,cocosli/jedis,zhaojinqiang/jedis,kevinsawicki/jedis,HeartSaVioR/jedis,StevenTsai/jedis,RedisLabs/jedis,JungMinu/jedis,rabbitcount/jedis,zhouyinyan/jedis,dingmanyao/jedis,shanzejun9811/jedis,AnselQiao/jedis,xetorthio/jedis,2bitoperations/jedis,yangyunfei/jedis,kevinsawicki/jedis,zhoffice/jedis,WangErXiao/jedis,argvk/jedis,sazzad16/jedis,fooljohnny/jedis,Raul-/jedis,BUCTdarkness/jedis,Xephi/jedis,smagellan/jedis,jiangtong1982/testProject,nykolaslima/jedis,wh007/jedis,xuanyue202/jedis-byte-cluster,iousin/jedis,jvorhauer/jedis,Rembau/jedis,mosoft521/jedis,adamweixuan/jedis,xmbsn/jedis,KengoTODA/jedis,perrystreetsoftware/jedis,tsc-nemeses/jedis,prosche/jedis,HeartSaVioR/jedis,sumit784/jedis,ystory/jedis,mosoft521/jedis,corydolphin/jedis,junho85/jedis,amikey/jedis,lousama/jedis,springning/jedis,MCGamerNetwork/jedis,mbrukman/jedis,kschroeder/jedis,sazzad16/jedis,elijah513/jedis,garyrussell/jedis,yapei123/jedis,xetorthio/jedis,grzegorz-dubicki/jedis,RoyZeng/jedis,adnear/jedis,zts1993/jedis,kag0/jedis,mashuai/jedis,xinster819/jedis,xiexingguang/jedis,lancevalour/jedis,RedisLabs/jedis,selfimprov/jedis,zhangyancoder/jedis,Foxlik/jedis | package redis.clients.jedis;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> {
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null);
}
public JedisPool(String host, int port) {
super(new Config(), new JedisFactory(host, port,
Protocol.DEFAULT_TIMEOUT, null));
}
public JedisPool(final Config poolConfig, final String host, int port,
int timeout, final String password) {
super(poolConfig, new JedisFactory(host, port, timeout, password));
}
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null);
}
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null);
}
/**
* PoolableObjectFactory custom impl.
*/
private static class JedisFactory extends BasePoolableObjectFactory {
private final String host;
private final int port;
private final int timeout;
private final String password;
public JedisFactory(final String host, final int port,
final int timeout, final String password) {
super();
this.host = host;
this.port = port;
this.timeout = timeout;
this.password = password;
}
public Object makeObject() throws Exception {
final Jedis jedis = new Jedis(this.host, this.port, this.timeout);
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
return jedis;
}
public void destroyObject(final Object obj) throws Exception {
if (obj instanceof Jedis) {
final Jedis jedis = (Jedis) obj;
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
public boolean validateObject(final Object obj) {
if (obj instanceof Jedis) {
final Jedis jedis = (Jedis) obj;
try {
return jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
} else {
return false;
}
}
}
}
| src/main/java/redis/clients/jedis/JedisPool.java | package redis.clients.jedis;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> {
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null);
}
public JedisPool(String host, int port) {
super(new Config(), new JedisFactory(host, port,
Protocol.DEFAULT_TIMEOUT, null));
}
public JedisPool(final Config poolConfig, final String host, int port,
int timeout, final String password) {
super(poolConfig, new JedisFactory(host, port, timeout, password));
}
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null);
}
public JedisPool(final GenericObjectPool.Config poolConfig,
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null);
}
/**
* PoolableObjectFactory custom impl.
*/
private static class JedisFactory extends BasePoolableObjectFactory {
private final String host;
private final int port;
private final int timeout;
private final String password;
public JedisFactory(final String host, final int port,
final int timeout, final String password) {
super();
this.host = host;
this.port = port;
this.timeout = (timeout > 0) ? timeout : -1;
this.password = password;
}
public Object makeObject() throws Exception {
final Jedis jedis;
if (timeout > 0) {
jedis = new Jedis(this.host, this.port, this.timeout);
} else {
jedis = new Jedis(this.host, this.port);
}
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
return jedis;
}
public void destroyObject(final Object obj) throws Exception {
if (obj instanceof Jedis) {
final Jedis jedis = (Jedis) obj;
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
public boolean validateObject(final Object obj) {
if (obj instanceof Jedis) {
final Jedis jedis = (Jedis) obj;
try {
return jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
} else {
return false;
}
}
}
}
| JedisPool timeout was broken. Values <= 0 where treated as -1, where 0 is infinite
| src/main/java/redis/clients/jedis/JedisPool.java | JedisPool timeout was broken. Values <= 0 where treated as -1, where 0 is infinite |
|
Java | mit | error: pathspec 'CircuitClass.java' did not match any file(s) known to git
| 308b2d326eebb328c42e7167cd8e24e93662fff8 | 1 | appsmehta/CMPE202-CSUnplugged-PeruvianFlipCoin | package circuitPackage;
import java.util.Scanner;
public class CircuitClass
{
public static void main(String[] args)
{
int[] input = new int[6];
boolean[] boolinput = new boolean[6];
int output1 = 0, output2 = 0, output3 = 0, output4 = 0, output5 = 0, output6 = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Put your six digit binary input here -");
for(int i=0;i<6;i++)
{
input[i] = sc.nextInt();
}
System.out.print("Input to the circuit : ");
for(int i=0;i<6;i++)
{
if(input[i]==1)
boolinput[i] = true;
else
boolinput[i] = false;
System.out.print(input[i]);
}
System.out.println("\n");
//First Round
boolean firstnumber1 = !(boolinput[0] & boolinput[5]);
boolean firstnumber2 = boolinput[1] & boolinput[2];
boolean firstnumber3 = boolinput[1] | boolinput[3];
boolean firstnumber4 = boolinput[2] ^ boolinput[4];
boolean firstnumber5 = !(boolinput[3] | boolinput[5]);
boolean firstnumber6 = !(boolinput[4]);
System.out.println(firstnumber1+" "+firstnumber2+" "+firstnumber3+" "+firstnumber4+" "+firstnumber5+" "+firstnumber6);
//Second Round
boolean secondnumber1 = firstnumber1 ^ firstnumber2;
boolean secondnumber2 = !(firstnumber1 | firstnumber3);
boolean secondnumber3 = firstnumber2 | firstnumber4;
boolean secondnumber4 = !(firstnumber3 & firstnumber5);
boolean secondnumber5 = firstnumber4 & firstnumber6;
boolean secondnumber6 = !(firstnumber6);
System.out.println(secondnumber1+" "+secondnumber2+" "+secondnumber3+" "+secondnumber4+" "+secondnumber5+" "+secondnumber6);
//Third Round
boolean thirdnumber1 = !(secondnumber1);
boolean thirdnumber2 = secondnumber1 ^ secondnumber2;
boolean thirdnumber3 = !(secondnumber2 | secondnumber3);
boolean thirdnumber4 = secondnumber3 | secondnumber4;
boolean thirdnumber5 = !(secondnumber4 & secondnumber5);
boolean thirdnumber6 = secondnumber5 & secondnumber6;
System.out.println(thirdnumber1+" "+thirdnumber2+" "+thirdnumber3+" "+thirdnumber4+" "+thirdnumber5+" "+thirdnumber6+"\n");
if(thirdnumber1 == true)
output1 = 1;
if(thirdnumber2 == true)
output2 = 1;
if(thirdnumber3 == true)
output3 = 1;
if(thirdnumber4 == true)
output4 = 1;
if(thirdnumber5 == true)
output5 = 1;
if(thirdnumber6 == true)
output6 = 1;
System.out.println("Output of the circuit : "+output1+" "+output2+" "+output3+" "+output4+" "+output5+" "+output6);
}
}
| CircuitClass.java | CircuitClass for peruvian flip coin project
This is the code for peruvian flip coin circuit.
This circuit is of 3 levels. I believe that this much complexity is enough.
I am still testing it to ensure that no 2 inputs will produce same output. | CircuitClass.java | CircuitClass for peruvian flip coin project |
|
Java | mit | error: pathspec 'WU10/WriteUp.java' did not match any file(s) known to git
| 2a38889de3573587493389b43fcf9f1eb512d60c | 1 | anandimous/UB-CSE_116 | package code;
import stack.EmptyStackException;
import stack.Stack;
public class Queue<E> implements IQueue<E> {
/**
* Implement a Queue which uses two Stacks as storage.
*
* Declare instance variables (and a constructor) as
* appropriate. Define the methods below. Run the provided
* JUnit tests and ensure they all pass.
*
* You must use the Stack implementation provided in the "stack" package.
* Ensure the peek and dequeue methods throw an
* EmptyQueueExceptions when appropriate.
*
* HINTS:
* 1) enqueue must push data onto the first stack
* 2) dequeue must pop data from the second stack
* 3) shift data from first to second stack when second stack is empty
*/
private Stack<E> s1;
private Stack<E> s2;
public Queue(){
s1 = new Stack<E>();
s2 = new Stack<E>();
}
@Override
public void enqueue(E item) {
s1.push(item);
}
@Override
public E dequeue() {
if(s1.isEmpty()){
throw new EmptyStackException("Cannot pop an empty stack.");
}
else{
if(s2.isEmpty()){
E item = s1.pop();
s2.push(item);
}
return s2.pop();
}
}
@Override
public E peek() {
if(s1.isEmpty()) {
throw new EmptyStackException("Cannot pop an empty stack.");
}
else {
return s1.peek();
}
}
@Override
public boolean isEmpty() {
return false;
}
}
| WU10/WriteUp.java | Created WU10 dir in current repo. Added relevant files
This assignment involved working with data shifting using stacks & queues. See comments for more info | WU10/WriteUp.java | Created WU10 dir in current repo. Added relevant files |
|
Java | mit | error: pathspec 'problem026/java.java' did not match any file(s) known to git
| d8ac3d3649eb76fc226f472ab78da93e12f5d3f4 | 1 | costasdroid/project_euler | public class Solution026 {
public static void main(String[] args) {
int maxOrder = 0;
int temp;
int number = 1;
for (int i = 2; i <= 1000; i++) {
temp = orderOf10In(i);
if (temp > maxOrder) {
maxOrder = temp;
number = i;
}
}
System.out.println(number);
}
static int orderOf10In(int n) {
int order = 0;
int temp = 10;
while (temp > 1 && order <= n) {
order++;
temp = (10 * temp) % n;
}
if (order > n)
return 0;
else
return order;
}
}
| problem026/java.java | solution026_2 | problem026/java.java | solution026_2 |
|
Java | mit | error: pathspec 'src/sound/Sound.java' did not match any file(s) known to git
| 6da3ffc7954d1ff4384cdf899605e6628acc0f41 | 1 | Crumster/Simplex2D | /**
*
*/
package sound;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* @author Aaron
* @author Ryan
*
*/
public class Sound {
private Clip clip;
private String fileName;
/**
*
*/
public Sound(String fileName) {
this.fileName = fileName;
loadSound();
}
/**
* This method plays the sound
*/
public void play(){
if(clip.isRunning()){
clip.stop();
}
clip.setFramePosition(0);
clip.start();
}
/**
* This method loops the sound
*/
public void loop(){
if(clip.isRunning()){
clip.stop();
}
clip.setFramePosition(0);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
/**
* This method stops the sound
*/
public void stop(){
clip.stop();
}
/**
* This method loads the sound into memory
*/
private void loadSound(){
try {
AudioInputStream audio = AudioSystem.getAudioInputStream(this.getClass().getResource(fileName));
clip = AudioSystem.getClip();
clip.open(audio);
} catch(UnsupportedAudioFileException e){
e.printStackTrace();
} catch(LineUnavailableException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
}
| src/sound/Sound.java | Add Sound.java
| src/sound/Sound.java | Add Sound.java |
|
Java | mit | error: pathspec 'src/easygame/SpriteAnimation.java' did not match any file(s) known to git
| a982fa4e1518df65cdf342a7de42063de972b425 | 1 | WilliansCPPP/jeasygame | /*The MIT License (MIT)
Copyright (c) 2015 Willians Magalhães Primo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
package easygame;
/**
* Essa classe é usada para criar animações para sprites.
* @author Willians Magalhães Primo
*/
public class SpriteAnimation {
/**
* Sem animação
*/
public static final SpriteAnimation NONE = null;
private float firstFrame = 0.0f;
private float lastFrame = 0.0f;
private float transitionVelocity = 0.0f;
public SpriteAnimation(float firstFrame, float lastFrame, float transitionVelocity){
this.firstFrame = firstFrame;
this.lastFrame = lastFrame;
this.transitionVelocity = transitionVelocity;
}
/**
* Retorna o proximo frame da animação baseando-se no frame atual.
*/
public float getNextFrame(float frame){
frame += transitionVelocity;
if(frame > lastFrame || frame < firstFrame){
frame = firstFrame;
}
return frame;
}
/**
* Retorna o primeiro frame da animação.
*/
public float getFirstFrame() {
return firstFrame;
}
/**
* Seta o primeiro frame da animação.
*/
public void setFirstFrame(float firstFrame) {
this.firstFrame = firstFrame;
}
/**
* Retorna o primeiro o ultimo frama da animação.
*/
public float getLastFrame() {
return lastFrame;
}
/**
* Seta o último frame da animação.
*/
public void setLastFrame(float lastFrame) {
this.lastFrame = lastFrame;
}
/**
* Retorna a velocidade de transição da animação.
*/
public float getTransitionVelocity() {
return transitionVelocity;
}
/**
* Seta a velocidade de transição da animação.
*/
public void setTransitionVelocity(float transitionVelocity) {
this.transitionVelocity = transitionVelocity;
}
}
| src/easygame/SpriteAnimation.java | Create SpriteAnimation.java
/**
* Essa classe é usada para criar animações para sprites.
* @author Willians Magalhães Primo
*/ | src/easygame/SpriteAnimation.java | Create SpriteAnimation.java |
|
Java | mit | error: pathspec 'src/main/java/com/spoj/PT07Z.java' did not match any file(s) known to git
| 516c4be18d2bc14dc87108c61ea50be1574c5b28 | 1 | sureshsajja/CodingProblems,sureshsajja/CodeRevisited | package com.spoj;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
import static java.lang.Integer.parseInt;
import static java.lang.System.in;
import static java.lang.System.out;
/**
* http://www.spoj.com/problems/PT07Z/
*
* @author sursajja
*/
public class PT07Z
{
private static BufferedReader reader;
private static StringTokenizer tokenizer;
private static PrintWriter pw;
private static String next() throws IOException
{
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private static int nextInt() throws IOException
{
return parseInt(next());
}
public static void main(String[] args) throws IOException
{
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
solve();
reader.close();
pw.close();
}
private static void solve() throws IOException
{
int V = nextInt();
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int v = 0; v <= V; v++) {
adjacencyList.add(new ArrayList<Integer>());
}
for (int i = 0; i < V - 1; i++) {
int v = nextInt();
int u = nextInt();
adjacencyList.get(v).add(u);
adjacencyList.get(u).add(v);
}
Pair pair = bfs(adjacencyList, V, 1);
pair = bfs(adjacencyList, V, pair.deepVertex);
pw.println(pair.maxDistance);
}
private static Pair bfs(List<List<Integer>> adjacencyList, int V, int start)
{
boolean[] visited = new boolean[V + 1];
int[] distance = new int[V + 1];
for (int i = 0; i < V + 1; i++) {
distance[i] = -1;
}
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
distance[start] = 0;
while (!queue.isEmpty()) {
int top = queue.poll();
List<Integer> list = adjacencyList.get(top);
for (Integer i : list) {
if (!visited[i]) {
queue.add(i);
visited[i] = true;
distance[i] = distance[top] + 1;
}
}
}
int maxDis = 0;
int deepVertex = 0;
for (int i = 0; i < V + 1; i++) {
if (maxDis < distance[i]) {
maxDis = distance[i];
deepVertex = i;
}
}
return new Pair(maxDis, deepVertex);
}
private static class Pair
{
int maxDistance;
int deepVertex;
Pair(int maxDistance, int deepVertex)
{
this.deepVertex = deepVertex;
this.maxDistance = maxDistance;
}
}
}
| src/main/java/com/spoj/PT07Z.java | longest path in a tree
| src/main/java/com/spoj/PT07Z.java | longest path in a tree |
|
Java | mit | error: pathspec 'ch04/4.07_-_Build_Order/BuildOrder.java' did not match any file(s) known to git
| 25e2b4844d93635a27561551c5cc481e333f5ea0 | 1 | nawns/ctci_v6,zillonxu/ctci-6E,zillonxu/ctci-6E,nawns/ctci_v6,nawns/ctci_v6,nawns/ctci_v6,zillonxu/ctci-6E,zillonxu/ctci-6E | import java.util.*;
import java.io.*;
public class BuildOrder {
public static int[] visited;
public static int[][] matrix;
public static LinkedList<Integer> out;
public static void dfs(int u, int V) {
if (visited[u] == 0) {
visited[u] = 1;
for (int i = 0; i < V; i++) {
if (matrix[u][i] == 1 && visited[i] == 0)
dfs(i, V);
}
out.addFirst(u);
}
}
public static List<Integer> build(int[] projects, int[][] dependencies, int V, int E) {
out = new LinkedList<Integer>();
visited = new int[V];
Arrays.fill(visited, 0);
matrix = new int[V][V];
for (int i = 0; i < V; i++)
Arrays.fill(matrix[i], 0);
for (int i = 0; i < E; i++) {
int edge1 = dependencies[i][0];
int edge2 = dependencies[i][1];
matrix[edge2][edge1] = 1;
}
for (int i = 0; i < V; i++) {
if (visited[i] == 0)
dfs(i, V);
}
return out;
}
public static void main(String[] args) {
int[] projects1 = new int[]{1, 2, 3, 4, 5, 6};
int[][] dependencies1 = new int[][]{{3, 0}, {1, 5}, {3, 1}, {0, 5}, {2, 3}};
int V = 6;
int E = 5;
List<Integer> list = build(projects1, dependencies1, V, E);
for (int i = 0; i < V; i++) {
System.out.print(projects1[list.get(i)]);
if (i < V - 1)
System.out.print(" ");
}
}
}
| ch04/4.07_-_Build_Order/BuildOrder.java | 4.07 - example from book
| ch04/4.07_-_Build_Order/BuildOrder.java | 4.07 - example from book |
|
Java | mit | error: pathspec 'src/xyz/jadonfowler/o/test/TestSuite.java' did not match any file(s) known to git
| 28031b584a3be3ec665545094c6af31d5f64cf82 | 1 | thyrgle/o,thyrgle/o,thyrgle/o,thyrgle/o,phase/o,phase/o,phase/o,phase/o | package xyz.jadonfowler.o.test;
import xyz.jadonfowler.o.O;
public class TestSuite {
private static O o;
public static void main(String[] args) throws Exception {
o = new O();
O.instance = o;
//checkParse("", "");
checkParse("\"Hello World\"o", "Hello World");
checkParse("12+o", "3");
checkParse("[123]+o", "6");
checkParse("[12] (4]*o", "8");
checkParse("[3,]2^+o", "14");
}
public static void checkParse(String code, String expected) throws Exception {
String result = "";
for (char c : code.toCharArray())
result += o.parse(c);
if (!(result.equals(expected)))
throw new Exception("'" + result + "' should be '" + expected + "' for '" + code + "'");
}
}
| src/xyz/jadonfowler/o/test/TestSuite.java | TestSuite with simple tests | src/xyz/jadonfowler/o/test/TestSuite.java | TestSuite with simple tests |
|
Java | mit | error: pathspec 'src/ca/vire/ChatMunger/MungedLanguage.java' did not match any file(s) known to git
| cdf7bbce10e60920f514ad3eeeb60ccb6369acef | 1 | F1shb0ne/ChatMunger | package ca.vire.ChatMunger;
/*
* This object represents the attributes of a specific language that belongs to a player
*/
public class MungedLanguage {
public int CurrentSkillPoints; // Number of skill points the player has gained so far
public int RequiredSkillPoints; // Number of skill points required to have learned the language
public MungedLanguage(int currentSkillPoints, int requiredSkillPoints) {
CurrentSkillPoints = currentSkillPoints;
RequiredSkillPoints = currentSkillPoints;
}
// Add or remove a skill point
public void AddPoint(int point) {
CurrentSkillPoints += point;
if (CurrentSkillPoints > RequiredSkillPoints)
CurrentSkillPoints = RequiredSkillPoints;
if (CurrentSkillPoints < 0)
CurrentSkillPoints = 0;
}
// Return language skill as number between 0 - 100
public int GetSkillPercentage() {
return (int)(((double)CurrentSkillPoints / (double)RequiredSkillPoints) * 100.0);
}
}
| src/ca/vire/ChatMunger/MungedLanguage.java | initial work on MungedLanguage module
| src/ca/vire/ChatMunger/MungedLanguage.java | initial work on MungedLanguage module |
|
Java | mit | error: pathspec 'garakuta/src/test/java/example/ReferenceTest.java' did not match any file(s) known to git
| 718444f17bcc2fb5360502c0b2f6924a82f84cb9 | 1 | backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox,backpaper0/sandbox | package example;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class ReferenceTest {
@Test
public void test_WeakReference() throws Exception {
//finalizeが呼ばれることを確認するために使用するラッチ
final CountDownLatch finalized = new CountDownLatch(1);
//assertのために一旦変数に突っ込む
Date date = new Date() {
@Override
protected void finalize() throws Throwable {
super.finalize();
finalized.countDown();
}
};
/*
* 弱い参照にする
* ソフト参照だとこの規模だとGCされなかった
*/
WeakReference<Date> ref = new WeakReference<Date>(date);
assertThat(ref.get(), sameInstance(date));
//強い参照があるとGCされないのでnullを
//突っ込んで強い参照を断ち切る
date = null;
gc();
assertThat(ref.get(), nullValue());
//finalizeが呼ばれてカウントダウンされるのを待つ
//いつまで経っても終わらないと困るので
//3秒待ってダメなら失敗と見なす
finalized.await(3, TimeUnit.SECONDS);
}
//free memoryが増えなくなるまでGCする
static void gc() {
long beforeFreeMemory = Runtime.getRuntime().freeMemory();
while (true) {
System.gc();
long freeMemory = Runtime.getRuntime().freeMemory();
if (beforeFreeMemory == freeMemory) {
break;
}
beforeFreeMemory = freeMemory;
}
}
} | garakuta/src/test/java/example/ReferenceTest.java | 弱い参照はGCされる
| garakuta/src/test/java/example/ReferenceTest.java | 弱い参照はGCされる |
|
Java | mit | error: pathspec 'src/main/java/cz/jcu/uai/javapract/Controler.java' did not match any file(s) known to git
| 1564c903ca7b16bc707a57e56abbf2c1ceb61ddb | 1 | drml/jcu-UAI734-stag | package cz.jcu.uai.javapract;
import cz.jcu.uai.javapract.Comparator;
import cz.jcu.uai.javapract.GUI;
import cz.jcu.uai.javapract.Parser;
import cz.jcu.uai.javapract.Stag;
/**
* Created by Drml on 4.7.2017.
*/
public class Controler {
private Stag stag;
private Parser $parser;
private Comparator $comparator;
private GUI $gui;
private String fileLocation;
public Controler(Stag stag, Parser $parser, Comparator $comparator, GUI $gui, String fileLocation)
{
this.stag = stag;
this.$parser = $parser;
this.$comparator = $comparator;
this.$gui = $gui;
this.fileLocation = fileLocation;
}
public void run(){
// TODO: implement
}
}
| src/main/java/cz/jcu/uai/javapract/Controler.java | Controler
| src/main/java/cz/jcu/uai/javapract/Controler.java | Controler |
|
Java | mit | error: pathspec 'src/test/java/atg/tools/ant/mock/MockManifest.java' did not match any file(s) known to git
| f4632091088c4f9c8d3ae4a6e119b0b7b53d0859 | 1 | jvz/atg-ant-plugin | package atg.tools.ant.mock;
import atg.tools.ant.util.IdentityFeatureExtractor;
import atg.tools.ant.util.ManifestUtils;
import atg.tools.ant.util.StringUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import static atg.tools.ant.util.AtgAttribute.ATG_REQUIRED;
import static org.junit.Assert.assertTrue;
/**
* Helper class to generate a manifest file for unit tests.
*
* @author msicker
* @version 2.0
*/
public class MockManifest {
private static final IdentityFeatureExtractor<String> STRING_IDENTITY_EXTRACTOR =
new IdentityFeatureExtractor<String>();
private final Manifest manifest = new Manifest();
private final Attributes attributes = manifest.getMainAttributes();
private final File rootDirectory;
public MockManifest(final File rootDirectory) {
this.rootDirectory = rootDirectory;
}
public MockManifest withRequiredModules(final Iterable<String> moduleNames) {
final String modules = StringUtils.join(' ', moduleNames.iterator(), STRING_IDENTITY_EXTRACTOR);
this.attributes.put(ATG_REQUIRED.getName(), modules);
return this;
}
public void save()
throws IOException {
if (!this.rootDirectory.exists()) {
assertTrue(this.rootDirectory.mkdirs());
}
final File manifest = ManifestUtils.touchManifestIn(this.rootDirectory);
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(manifest));
try {
this.manifest.write(stream);
} finally {
stream.close();
}
}
}
| src/test/java/atg/tools/ant/mock/MockManifest.java | Add mock manifest helper class.
| src/test/java/atg/tools/ant/mock/MockManifest.java | Add mock manifest helper class. |
|
Java | mit | error: pathspec 'src/main/java/org/ngseq/metagenomics/HMMSearch.java' did not match any file(s) known to git
| cde13c0202418c10ce888bf7710c7ee899e0f122 | 1 | NGSeq/ViraPipe,NGSeq/ViraPipe,NGSeq/ViraPipe | package org.ngseq.metagenomics;
import org.apache.commons.cli.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSInputStream;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.broadcast.Broadcast;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
public class HMMSearch {
public static void main(String[] args) throws IOException {
SparkConf conf = new SparkConf().setAppName("Assemble");
JavaSparkContext sc = new JavaSparkContext(conf);
Options options = new Options();
Option inOpt = new Option( "in", true, "" );
Option cOpt = new Option( "t", true, "Threads" );
Option ouOpt = new Option( "out", true, "" );
options.addOption(new Option( "localdir", true, "Absolute path to local temp dir"));
options.addOption( new Option( "debug", "saves error log" ) );
options.addOption( new Option( "bin", true,"Path to megahit binary, defaults calls 'megahit'" ) );
options.addOption(new Option( "db", true, "Path to local BlastNT database (database must be available on every node under the same path)" ));
options.addOption( inOpt );
options.addOption( cOpt );
options.addOption( ouOpt );
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "spark-submit <spark specific args>", options, true );
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse( options, args );
}
catch( ParseException exp ) {
System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
System.exit(1);
}
String inputPath = (cmd.hasOption("in")==true)? cmd.getOptionValue("in"):null;
String outDir = (cmd.hasOption("out")==true)? cmd.getOptionValue("out"):null;
String localdir = cmd.getOptionValue("localdir");
boolean debug = cmd.hasOption("debug");
String db = (cmd.hasOption("db")==true)? cmd.getOptionValue("db"):"Path to local hmmer database (database must be available on every node under the same path)"; //We want to filter out human matches, so use human db as default
String bin = (cmd.hasOption("bin")==true)? cmd.getOptionValue("bin"):"hmmsearch";
int t = (cmd.hasOption("t")==true)? Integer.valueOf(cmd.getOptionValue("t")):1;
FileSystem fs = FileSystem.get(new Configuration());
fs.mkdirs(fs,new Path(outDir),new FsPermission(FsAction.ALL,FsAction.ALL,FsAction.ALL));
ArrayList<String> splitFileList = new ArrayList<>();
FileStatus[] st = fs.listStatus(new Path(inputPath));
for (int i=0;i<st.length;i++){
String fn = st[i].getPath().getName().toString();
if(!fn.equalsIgnoreCase("_SUCCESS"))
splitFileList.add(st[i].getPath().toUri().getRawPath().toString());
}
JavaRDD<String> splitFilesRDD = sc.parallelize(splitFileList, splitFileList.size());
Broadcast<String> bs = sc.broadcast(fs.getUri().toString());
JavaRDD<String> outRDD = splitFilesRDD.mapPartitions(f -> {
String path = f.next();
System.out.println(path);
String fname;
if(path.lastIndexOf(".")<path.lastIndexOf("/"))
fname = path.substring(path.lastIndexOf("/")+1);
else fname = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));
// String tempName = String.valueOf((new Date()).getTime());
DFSClient client = new DFSClient(URI.create(bs.getValue()), new Configuration());
DFSInputStream hdfsstream = client.open(path);
String ass_cmd = bin+" --noali --cpu "+t+" -o "+localdir+"/lsu."+fname+".txt --tblout "+localdir+"/lsu."+fname+".table.txt " +db+ " /dev/stdin";
System.out.println(ass_cmd);
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", ass_cmd);
Process process = pb.start();
BufferedReader hdfsinput = new BufferedReader(new InputStreamReader(hdfsstream));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String line;
while ((line = hdfsinput.readLine()) != null) {
writer.write(line);
writer.newLine();
}
writer.close();
ArrayList<String> out = new ArrayList<String>();
BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String e;
while ((e = err.readLine()) != null) {
System.out.println(e);
out.add(e);
}
/* String mkdir = System.getenv("HADOOP_HOME")+"/bin/hdfs dfs -mkdir "+outDir;
String chown = System.getenv("HADOOP_HOME")+"/bin/hdfs dfs -chown yarn "+outDir;
Process mkpb = new ProcessBuilder("/bin/sh", "-c", mkdir).start();
Process chpb = new ProcessBuilder("/bin/sh", "-c", chown).start();
BufferedReader err1 = new BufferedReader(new InputStreamReader(dprocess.getErrorStream()));
String e1;
while ((e1 = err1.readLine()) != null) {
System.out.println(e1);
out.add(e1);
}
dprocess.waitFor(); */
String copy_cmd = System.getenv("HADOOP_HOME")+"/bin/hdfs dfs -put "+localdir+"/lsu."+fname+"* " +outDir;
ProcessBuilder pb2 = new ProcessBuilder("/bin/sh", "-c", copy_cmd);
Process process2 = pb2.start();
BufferedReader err2 = new BufferedReader(new InputStreamReader(process2.getErrorStream()));
String e2;
while ((e2 = err2.readLine()) != null) {
System.out.println(e2);
out.add(e2);
}
process2.waitFor();
String delete_cmd = "rm -rf "+localdir+"/lsu."+fname+"*";
ProcessBuilder pb3 = new ProcessBuilder("/bin/sh", "-c", delete_cmd);
Process process3 = pb3.start();
BufferedReader err3 = new BufferedReader(new InputStreamReader(process3.getErrorStream()));
String e3;
while ((e3 = err3.readLine()) != null) {
System.out.println(e3);
out.add(e3);
}
process3.waitFor();
out.add(ass_cmd);
out.add(copy_cmd);
out.add(delete_cmd);
return out.iterator();
});
if(debug) outRDD.saveAsTextFile("hmm_errorlog/"+String.valueOf(new Date().getTime()));
else outRDD.foreach(err -> System.out.println(err));
sc.stop();
}
}
| src/main/java/org/ngseq/metagenomics/HMMSearch.java | HMMsearch class added
| src/main/java/org/ngseq/metagenomics/HMMSearch.java | HMMsearch class added |
|
Java | mit | error: pathspec 'src/com/haxademic/core/hardware/midi/AbletonNotes.java' did not match any file(s) known to git
| 8efb946debc8f16e03fbfeebeea901366b4eb1c4 | 1 | cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic | package com.haxademic.core.hardware.midi;
public class AbletonNotes {
public static int NOTE_01 = 48;
public static int NOTE_02 = 49;
public static int NOTE_03 = 50;
public static int NOTE_04 = 51;
public static int NOTE_05 = 52;
public static int NOTE_06 = 53;
public static int NOTE_07 = 54;
public static int NOTE_08 = 55;
public static int NOTE_09 = 56;
public static int NOTE_10 = 57;
public static int NOTE_11 = 58;
public static int NOTE_12 = 59;
public static int NOTE_13 = 60;
public static int NOTE_14 = 61;
public static int NOTE_15 = 62;
public static int NOTE_16 = 63;
}
| src/com/haxademic/core/hardware/midi/AbletonNotes.java | Add ableton notes definition | src/com/haxademic/core/hardware/midi/AbletonNotes.java | Add ableton notes definition |
|
Java | mit | error: pathspec 'src/main/java/com/github/cschen1205/jp/chap04/Q03.java' did not match any file(s) known to git
| 9ca43449e677289ec1d728aa36bf0770cb1b7c9a | 1 | cschen1205/java-programming,cschen1205/java-programming | package com.github.cschen1205.jp.chap04;
/**
* Created by memeanalytics on 28/6/17.
* Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height
*/
public class Q03 {
public static class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
value = val;
}
}
public static TreeNode addToTree(int[] a, int lo, int hi){
if(lo > hi) return null;
int mid = lo + (hi - lo) / 2;
TreeNode x = new TreeNode(a[mid]);
x.left = addToTree(a, lo, mid-1);
x.right = addToTree(a, mid+1, hi);
return x;
}
public static TreeNode createMinBST(int[] a) {
return addToTree(a, 0, a.length-1);
}
}
| src/main/java/com/github/cschen1205/jp/chap04/Q03.java | minimum depth balance tree
| src/main/java/com/github/cschen1205/jp/chap04/Q03.java | minimum depth balance tree |
|
Java | mit | error: pathspec 'app/src/main/java/ru/unatco/rss/model/Subscription.java' did not match any file(s) known to git
| faf648bd75d8441a404a81e6b07bebb0d174cb72 | 1 | fsherstobitov/rss-reader | package ru.unatco.rss.model;
public class Subscription {
private String mTitle;
private String mUrl;
}
| app/src/main/java/ru/unatco/rss/model/Subscription.java | added Subscription model
| app/src/main/java/ru/unatco/rss/model/Subscription.java | added Subscription model |
|
Java | mit | error: pathspec 'algorithms_warmup/src/com/codeprep/valleycount/Solution.java' did not match any file(s) known to git
| 860565126ffad4652c7f5fb1800fbab9b8c0b716 | 1 | thejavamonk/hackerrankAlgorithms | package com.codeprep.valleycount;
import java.io.IOException;
import java.util.Scanner;
public class Solution {
// Complete the countingValleys function below.
static int countingValleys(int n, String s) {
char [] steps = s.toCharArray();
int currStep = 0;
int noOfValleys = 0;
for(char ch: steps){
if(ch == 'U'){
currStep++;
}
else if(ch == 'D'){
currStep--;
}
if(currStep == 0 && ch == 'U'){
noOfValleys++;
}
}
return noOfValleys;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int n = scanner.nextInt();
String s = scanner.nextLine();
int result = countingValleys(n, s);
System.out.println(result);
scanner.close();
}
}
| algorithms_warmup/src/com/codeprep/valleycount/Solution.java | solved counting valleys problem
| algorithms_warmup/src/com/codeprep/valleycount/Solution.java | solved counting valleys problem |
|
Java | mit | error: pathspec 'app/src/main/java/nl/drewez/gyrosnek/SnekFood/SnekFoodFactory.java' did not match any file(s) known to git
| 16e8e477df63ea6160c6084ad446a0835d48696f | 1 | Want100Cookies/GyroSnek | package nl.drewez.gyrosnek.SnekFood;
import java.util.Random;
public class SnekFoodFactory implements ISnekFoodFactory {
private static final Random random = new Random();
private static final int MinNoOfFoods = 0;
private static final int MaxNoOfFoods = 5;
@Override
public ISnekFood[] createSnekBar() {
int noOfFoods = random.nextInt(MaxNoOfFoods - MinNoOfFoods) + MinNoOfFoods;
ISnekFood[] snekBar = new ISnekFood[noOfFoods];
for (int i = 0; i < noOfFoods; i++) {
int snekType = random.nextInt(3);
switch (snekType) {
case 0:
snekBar[i] = new CheeseBurger(0, 0);
break;
case 1:
snekBar[i] = new HotDog(0, 0);
break;
case 2:
snekBar[i] = new Pizza(0, 0);
break;
}
}
return snekBar;
}
}
| app/src/main/java/nl/drewez/gyrosnek/SnekFood/SnekFoodFactory.java | Start on SnekFoodFactory
| app/src/main/java/nl/drewez/gyrosnek/SnekFood/SnekFoodFactory.java | Start on SnekFoodFactory |
|
Java | mit | error: pathspec 'gto-support-core/src/main/java/org/ccci/gto/android/common/preference/ListPreferenceCompat.java' did not match any file(s) known to git
| ae7ce1522f30ad46e1e6ff6e6e62ffa318ef5922 | 1 | CruGlobal/android-gto-support,GlobalTechnology/android-gto-support,CruGlobal/android-gto-support | package org.ccci.gto.android.common.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.preference.ListPreference;
import android.util.AttributeSet;
public class ListPreferenceCompat extends ListPreference {
public ListPreferenceCompat(final Context context) {
super(context);
}
public ListPreferenceCompat(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ListPreferenceCompat(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ListPreferenceCompat(final Context context, final AttributeSet attrs, final int defStyleAttr,
final int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
/**
* Returns the summary of this ListPreference. If the summary
* has a {@linkplain java.lang.String#format String formatting}
* marker in it (i.e. "%s" or "%1$s"), then the current entry
* value will be substituted in its place.
*
* @return the summary with appropriate string substitution
*/
@Override
public CharSequence getSummary() {
// Android pre-Honeycomb didn't support String formatting for the Summary, so we replicate that behavior here
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
final CharSequence summary = super.getSummary();
final CharSequence entry = getEntry();
if (summary == null || entry == null) {
return summary;
} else {
return String.format(summary.toString(), entry);
}
} else {
return super.getSummary();
}
}
}
| gto-support-core/src/main/java/org/ccci/gto/android/common/preference/ListPreferenceCompat.java | [#MMAND-23] create ListPreferenceCompat to support String formatting for android pre-honeycomb
| gto-support-core/src/main/java/org/ccci/gto/android/common/preference/ListPreferenceCompat.java | [#MMAND-23] create ListPreferenceCompat to support String formatting for android pre-honeycomb |
|
Java | mit | error: pathspec 'lod-qualitymetrics/lod-qualitymetrics-representation/src/main/java/eu/diachron/qualitymetrics/representational/versatility/DifferentSerialisationFormats.java' did not match any file(s) known to git
| 34bf361c719da6a8770994efa6cdee689e93916a | 1 | diachron/quality | /**
*
*/
package eu.diachron.qualitymetrics.representational.versatility;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.core.Quad;
import de.unibonn.iai.eis.diachron.semantics.DQM;
import de.unibonn.iai.eis.diachron.technques.probabilistic.ResourceBaseURIOracle;
import de.unibonn.iai.eis.luzzu.assessment.QualityMetric;
import de.unibonn.iai.eis.luzzu.datatypes.ProblemList;
import de.unibonn.iai.eis.luzzu.exceptions.ProblemListInitialisationException;
import de.unibonn.iai.eis.luzzu.semantics.vocabularies.QPRO;
import de.unibonn.iai.eis.luzzu.semantics.vocabularies.VOID;
/**
* @author Jeremy Debattista
*
* Datasets can be represented in different formats, such as RDF/XML, N3,
* N-Triples etc... The voID vocabulary allows data publishers to define
* the possible formats in the dataset's metadata using the void:feature
* predicate.
*
* In this metric we check if in a dataset has 1 or more triples descibing
* the different serialisation formats that a dataset is available in,
* using the void:feature. A list of possible serialisation formats
* can be found: http://www.w3.org/ns/formats/
*
* The metric returns 1 if the data published is represented in 2 or more
* formats.
*/
public class DifferentSerialisationFormats implements QualityMetric{
private int features = 0;
private List<Quad> _problemList = new ArrayList<Quad>();
private static Logger logger = LoggerFactory.getLogger(DifferentSerialisationFormats.class);
private String datasetURI = null;
ResourceBaseURIOracle oracle = new ResourceBaseURIOracle();
private static List<String> formats = new ArrayList<String>();
static{
formats.add("http://www.w3.org/ns/formats/JSON-LD");
formats.add("http://www.w3.org/ns/formats/N3");
formats.add("http://www.w3.org/ns/formats/N-Triples");
formats.add("http://www.w3.org/ns/formats/N-Quads");
formats.add("http://www.w3.org/ns/formats/LD_Patch");
formats.add("http://www.w3.org/ns/formats/microdata");
formats.add("http://www.w3.org/ns/formats/OWL_XML");
formats.add("http://www.w3.org/ns/formats/OWL_Functional");
formats.add("http://www.w3.org/ns/formats/OWL_Manchester");
formats.add("http://www.w3.org/ns/formats/POWDER");
formats.add("http://www.w3.org/ns/formats/POWDER-S");
formats.add("http://www.w3.org/ns/formats/PROV-N");
formats.add("http://www.w3.org/ns/formats/PROV-XML");
formats.add("http://www.w3.org/ns/formats/RDFa");
formats.add("http://www.w3.org/ns/formats/RDF_JSON");
formats.add("http://www.w3.org/ns/formats/RDF_XML");
formats.add("http://www.w3.org/ns/formats/RIF_XML");
formats.add("http://www.w3.org/ns/formats/SPARQL_Results_XML");
formats.add("http://www.w3.org/ns/formats/SPARQL_Results_JSON");
formats.add("http://www.w3.org/ns/formats/SPARQL_Results_CSV");
formats.add("http://www.w3.org/ns/formats/SPARQL_Results_TSV");
formats.add("http://www.w3.org/ns/formats/Turtle");
formats.add("http://www.w3.org/ns/formats/TriG");
}
@Override
public void compute(Quad quad) {
oracle.addHint(quad);
Node predicate = quad.getPredicate();
Node object = quad.getObject();
if (predicate.hasURI(VOID.feature.getURI())){
datasetURI = quad.getSubject().getURI();
if (formats.contains(object.getURI())) features++;
else {
Quad q = new Quad(null, object, QPRO.exceptionDescription.asNode(), DQM.IncorrectFormatDefined.asNode());
this._problemList.add(q);
}
}
}
@Override
public double metricValue() {
return (features > 1) ? 1 : 0;
}
@Override
public Resource getMetricURI() {
return DQM.DifferentSerialisationsMetric;
}
public ProblemList<?> getQualityProblems() {
if (features > 1){
if (datasetURI == null) datasetURI = oracle.getEstimatedResourceBaseURI();
Quad q = new Quad(null, ModelFactory.createDefaultModel().createResource(datasetURI).asNode(), QPRO.exceptionDescription.asNode(), DQM.NoMultipleFormatDefined.asNode());
this._problemList.add(q);
}
ProblemList<Quad> pl = null;
try {
pl = new ProblemList<Quad>(this._problemList);
} catch (ProblemListInitialisationException e) {
logger.error(e.getMessage());
}
return pl;
}
@Override
public boolean isEstimate() {
return false;
}
@Override
public Resource getAgentURI() {
return DQM.LuzzuProvenanceAgent;
}
}
| lod-qualitymetrics/lod-qualitymetrics-representation/src/main/java/eu/diachron/qualitymetrics/representational/versatility/DifferentSerialisationFormats.java | added different serialisation formats metric | lod-qualitymetrics/lod-qualitymetrics-representation/src/main/java/eu/diachron/qualitymetrics/representational/versatility/DifferentSerialisationFormats.java | added different serialisation formats metric |
|
Java | epl-1.0 | 2b52b65a4140be9ec071ddf83050cd9fe91ba7ec | 0 | cemalkilic/che,sleshchenko/che,davidfestal/che,sudaraka94/che,sunix/che,akervern/che,Mirage20/che,TypeFox/che,sudaraka94/che,jonahkichwacoders/che,akervern/che,davidfestal/che,TypeFox/che,sunix/che,codenvy/che,jonahkichwacoders/che,ollie314/che,jonahkichwacoders/che,sleshchenko/che,sunix/che,TypeFox/che,bartlomiej-laczkowski/che,gazarenkov/che-sketch,cdietrich/che,sudaraka94/che,lehmanju/che,lehmanju/che,lehmanju/che,davidfestal/che,bartlomiej-laczkowski/che,sunix/che,sleshchenko/che,davidfestal/che,TypeFox/che,gazarenkov/che-sketch,sleshchenko/che,bartlomiej-laczkowski/che,slemeur/che,Patricol/che,akervern/che,Mirage20/che,snjeza/che,cdietrich/che,cdietrich/che,bartlomiej-laczkowski/che,ollie314/che,Patricol/che,slemeur/che,sleshchenko/che,Patricol/che,ollie314/che,jonahkichwacoders/che,snjeza/che,sudaraka94/che,cemalkilic/che,ollie314/che,jonahkichwacoders/che,lehmanju/che,akervern/che,jonahkichwacoders/che,snjeza/che,Patricol/che,cdietrich/che,sudaraka94/che,Patricol/che,sunix/che,sunix/che,cemalkilic/che,Mirage20/che,slemeur/che,akervern/che,ollie314/che,akervern/che,cdietrich/che,akervern/che,jonahkichwacoders/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,cemalkilic/che,Patricol/che,davidfestal/che,sleshchenko/che,sleshchenko/che,sleshchenko/che,lehmanju/che,cemalkilic/che,TypeFox/che,TypeFox/che,sleshchenko/che,snjeza/che,cemalkilic/che,jonahkichwacoders/che,codenvy/che,snjeza/che,codenvy/che,gazarenkov/che-sketch,bartlomiej-laczkowski/che,jonahkichwacoders/che,davidfestal/che,sudaraka94/che,snjeza/che,Patricol/che,akervern/che,snjeza/che,codenvy/che,lehmanju/che,lehmanju/che,lehmanju/che,davidfestal/che,akervern/che,sunix/che,Patricol/che,cdietrich/che,davidfestal/che,sleshchenko/che,TypeFox/che,snjeza/che,slemeur/che,sudaraka94/che,davidfestal/che,cemalkilic/che,cdietrich/che,TypeFox/che,gazarenkov/che-sketch,davidfestal/che,bartlomiej-laczkowski/che,sudaraka94/che,cemalkilic/che,gazarenkov/che-sketch,gazarenkov/che-sketch,sunix/che,snjeza/che,TypeFox/che,cdietrich/che,TypeFox/che,Patricol/che,Mirage20/che,Mirage20/che,jonahkichwacoders/che,slemeur/che,gazarenkov/che-sketch,Patricol/che,Mirage20/che,sudaraka94/che,sudaraka94/che,gazarenkov/che-sketch,gazarenkov/che-sketch,cdietrich/che,sunix/che,bartlomiej-laczkowski/che,lehmanju/che,cemalkilic/che,ollie314/che | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ui.multisplitpanel.panel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckLayoutPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.ide.api.action.Action;
import org.eclipse.che.ide.ui.multisplitpanel.SubPanel;
import org.eclipse.che.ide.ui.multisplitpanel.WidgetToShow;
import org.eclipse.che.ide.ui.multisplitpanel.actions.ClosePaneAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.RemoveAllWidgetsInPaneAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.SplitHorizontallyAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.SplitVerticallyAction;
import org.eclipse.che.ide.ui.multisplitpanel.menu.Menu;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItem;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItemActionWidget;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItemWidget;
import org.eclipse.che.ide.ui.multisplitpanel.tab.Tab;
import org.eclipse.che.ide.ui.multisplitpanel.tab.TabItemFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of {@link SubPanelView}.
*
* @author Artem Zatsarynnyi
*/
public class SubPanelViewImpl extends Composite implements SubPanelView,
Menu.ActionDelegate,
Tab.ActionDelegate {
private final TabItemFactory tabItemFactory;
private final Menu menu;
private final Map<Tab, WidgetToShow> tabs2Widgets;
private final Map<WidgetToShow, Tab> widgets2Tabs;
private final Map<WidgetToShow, MenuItemWidget> widgets2ListItems;
@UiField(provided = true)
SplitLayoutPanel splitLayoutPanel;
@UiField
DockLayoutPanel mainPanel;
@UiField
FlowPanel tabsPanel;
@UiField
DeckLayoutPanel widgetsPanel;
private ActionDelegate delegate;
private SubPanelView parentPanel;
@Inject
public SubPanelViewImpl(SubPanelViewImplUiBinder uiBinder,
TabItemFactory tabItemFactory,
Menu menu,
@Assisted ClosePaneAction closePaneAction,
@Assisted RemoveAllWidgetsInPaneAction removeAllWidgetsInPaneAction,
@Assisted SplitHorizontallyAction splitHorizontallyAction,
@Assisted SplitVerticallyAction splitVerticallyAction) {
this.tabItemFactory = tabItemFactory;
this.menu = menu;
menu.addListItem(new MenuItemActionWidget(closePaneAction));
menu.addListItem(new MenuItemActionWidget(removeAllWidgetsInPaneAction));
menu.addListItem(new MenuItemActionWidget(splitHorizontallyAction));
menu.addListItem(new MenuItemActionWidget(splitVerticallyAction));
menu.setDelegate(this);
tabs2Widgets = new HashMap<>();
widgets2Tabs = new HashMap<>();
widgets2ListItems = new HashMap<>();
splitLayoutPanel = new SplitLayoutPanel(3);
initWidget(uiBinder.createAndBindUi(this));
tabsPanel.add(menu);
widgetsPanel.addDomHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
delegate.onWidgetFocused(widgetsPanel.getVisibleWidget());
}
}, ClickEvent.getType());
}
@Override
public void setDelegate(ActionDelegate delegate) {
this.delegate = delegate;
}
@Override
public void splitHorizontally(IsWidget subPanelView) {
int height = splitLayoutPanel.getOffsetHeight() / 2;
splitLayoutPanel.remove(mainPanel);
splitLayoutPanel.addSouth(subPanelView, height);
splitLayoutPanel.add(mainPanel);
}
@Override
public void splitVertically(IsWidget subPanelView) {
int width = splitLayoutPanel.getOffsetWidth() / 2;
splitLayoutPanel.remove(mainPanel);
splitLayoutPanel.addEast(subPanelView, width);
splitLayoutPanel.add(mainPanel);
}
@Override
public void addWidget(WidgetToShow widget, boolean removable) {
final Tab tab = tabItemFactory.createTabItem(widget.getTitle(), widget.getIcon(), removable);
tab.setDelegate(this);
tabs2Widgets.put(tab, widget);
widgets2Tabs.put(widget, tab);
tabsPanel.add(tab);
widgetsPanel.setWidget(widget.getWidget());
// add item to drop-down menu
final MenuItemWidget listItemWidget = new MenuItemWidget(tab, removable);
menu.addListItem(listItemWidget);
widgets2ListItems.put(widget, listItemWidget);
}
@Override
public void activateWidget(WidgetToShow widget) {
final Tab tab = widgets2Tabs.get(widget);
if (tab != null) {
selectTab(tab);
}
widgetsPanel.showWidget(widget.getWidget().asWidget());
// add 'active' attribute for active widget for testing purpose
for (WidgetToShow widgetToShow : widgets2Tabs.keySet()) {
widgetToShow.getWidget().asWidget().getElement().removeAttribute("active");
}
widget.getWidget().asWidget().getElement().setAttribute("active", "");
}
@Override
public void removeWidget(WidgetToShow widget) {
final Tab tab = widgets2Tabs.get(widget);
if (tab != null) {
closeTab(tab);
}
}
private void removeWidgetFromUI(WidgetToShow widget) {
final Tab tab = widgets2Tabs.remove(widget);
if (tab != null) {
tabsPanel.remove(tab);
widgetsPanel.remove(widget.getWidget());
tabs2Widgets.remove(tab);
// remove item from drop-down menu
final MenuItemWidget listItemWidget = widgets2ListItems.remove(widget);
if (listItemWidget != null) {
menu.removeListItem(listItemWidget);
}
}
}
@Override
public void closePanel() {
if (splitLayoutPanel.getWidgetCount() == 1) {
parentPanel.removeChildSubPanel(this);
return;
}
splitLayoutPanel.remove(mainPanel);
// move widget from east/south part to the center
final Widget lastWidget = splitLayoutPanel.getWidget(0);
splitLayoutPanel.setWidgetSize(lastWidget, 0);
splitLayoutPanel.remove(lastWidget);
splitLayoutPanel.add(lastWidget);
}
@Override
public void removeChildSubPanel(Widget widget) {
if (splitLayoutPanel.getWidgetDirection(widget) == DockLayoutPanel.Direction.CENTER) {
// this is the only widget on the panel
// don't allow to remove it
return;
}
splitLayoutPanel.setWidgetSize(widget, 0);
splitLayoutPanel.remove(widget);
}
@Override
public void setParentPanel(SubPanelView parentPanel) {
this.parentPanel = parentPanel;
}
@Override
public void onMenuItemSelected(MenuItem menuItem) {
final Object data = menuItem.getData();
if (data instanceof Tab) {
selectTab((Tab)data);
WidgetToShow widget = tabs2Widgets.get(data);
if (widget != null) {
activateWidget(widget);
delegate.onWidgetFocused(widget.getWidget());
}
} else if (data instanceof Action) {
((Action)data).actionPerformed(null);
}
}
@Override
public void onMenuItemClosing(MenuItem menuItem) {
Object data = menuItem.getData();
if (data instanceof Tab) {
closeTab((Tab)data);
}
}
@Override
public void onTabClicked(Tab tab) {
selectTab(tab);
// TODO: extract code to the separate method
WidgetToShow widget = tabs2Widgets.get(tab);
if (widget != null) {
activateWidget(widget);
delegate.onWidgetFocused(widget.getWidget());
}
}
private void selectTab(Tab tab) {
for (Tab tabItem : tabs2Widgets.keySet()) {
tabItem.unSelect();
}
tab.select();
}
@Override
public void onTabClosing(Tab tab) {
closeTab(tab);
}
private void closeTab(Tab tab) {
final WidgetToShow widget = tabs2Widgets.get(tab);
if (widget != null) {
delegate.onWidgetRemoving(widget.getWidget(), new SubPanel.RemoveCallback() {
@Override
public void remove() {
removeWidgetFromUI(widget);
}
});
}
}
interface SubPanelViewImplUiBinder extends UiBinder<Widget, SubPanelViewImpl> {
}
}
| ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/multisplitpanel/panel/SubPanelViewImpl.java | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ui.multisplitpanel.panel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckLayoutPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.ide.api.action.Action;
import org.eclipse.che.ide.ui.multisplitpanel.SubPanel;
import org.eclipse.che.ide.ui.multisplitpanel.WidgetToShow;
import org.eclipse.che.ide.ui.multisplitpanel.actions.ClosePaneAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.RemoveAllWidgetsInPaneAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.SplitHorizontallyAction;
import org.eclipse.che.ide.ui.multisplitpanel.actions.SplitVerticallyAction;
import org.eclipse.che.ide.ui.multisplitpanel.menu.Menu;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItem;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItemActionWidget;
import org.eclipse.che.ide.ui.multisplitpanel.menu.MenuItemWidget;
import org.eclipse.che.ide.ui.multisplitpanel.tab.Tab;
import org.eclipse.che.ide.ui.multisplitpanel.tab.TabItemFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of {@link SubPanelView}.
*
* @author Artem Zatsarynnyi
*/
public class SubPanelViewImpl extends Composite implements SubPanelView,
Menu.ActionDelegate,
Tab.ActionDelegate {
private final TabItemFactory tabItemFactory;
private final Menu menu;
private final Map<Tab, WidgetToShow> tabs2Widgets;
private final Map<WidgetToShow, Tab> widgets2Tabs;
private final Map<WidgetToShow, MenuItemWidget> widgets2ListItems;
@UiField(provided = true)
SplitLayoutPanel splitLayoutPanel;
@UiField
DockLayoutPanel mainPanel;
@UiField
FlowPanel tabsPanel;
@UiField
DeckLayoutPanel widgetsPanel;
private ActionDelegate delegate;
private SubPanelView parentPanel;
@Inject
public SubPanelViewImpl(SubPanelViewImplUiBinder uiBinder,
TabItemFactory tabItemFactory,
Menu menu,
@Assisted ClosePaneAction closePaneAction,
@Assisted RemoveAllWidgetsInPaneAction removeAllWidgetsInPaneAction,
@Assisted SplitHorizontallyAction splitHorizontallyAction,
@Assisted SplitVerticallyAction splitVerticallyAction) {
this.tabItemFactory = tabItemFactory;
this.menu = menu;
menu.addListItem(new MenuItemActionWidget(closePaneAction));
menu.addListItem(new MenuItemActionWidget(removeAllWidgetsInPaneAction));
menu.addListItem(new MenuItemActionWidget(splitHorizontallyAction));
menu.addListItem(new MenuItemActionWidget(splitVerticallyAction));
menu.setDelegate(this);
tabs2Widgets = new HashMap<>();
widgets2Tabs = new HashMap<>();
widgets2ListItems = new HashMap<>();
splitLayoutPanel = new SplitLayoutPanel(3);
initWidget(uiBinder.createAndBindUi(this));
tabsPanel.add(menu);
widgetsPanel.addDomHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
delegate.onWidgetFocused(widgetsPanel.getVisibleWidget());
}
}, ClickEvent.getType());
}
@Override
public void setDelegate(ActionDelegate delegate) {
this.delegate = delegate;
}
@Override
public void splitHorizontally(IsWidget subPanelView) {
int height = splitLayoutPanel.getOffsetHeight() / 2;
splitLayoutPanel.remove(mainPanel);
splitLayoutPanel.addSouth(subPanelView, height);
splitLayoutPanel.add(mainPanel);
}
@Override
public void splitVertically(IsWidget subPanelView) {
int width = splitLayoutPanel.getOffsetWidth() / 2;
splitLayoutPanel.remove(mainPanel);
splitLayoutPanel.addEast(subPanelView, width);
splitLayoutPanel.add(mainPanel);
}
@Override
public void addWidget(WidgetToShow widget, boolean removable) {
final Tab tab = tabItemFactory.createTabItem(widget.getTitle(), widget.getIcon(), removable);
tab.setDelegate(this);
tabs2Widgets.put(tab, widget);
widgets2Tabs.put(widget, tab);
tabsPanel.add(tab);
widgetsPanel.setWidget(widget.getWidget());
// add item to drop-down menu
final MenuItemWidget listItemWidget = new MenuItemWidget(tab, removable);
menu.addListItem(listItemWidget);
widgets2ListItems.put(widget, listItemWidget);
}
@Override
public void activateWidget(WidgetToShow widget) {
final Tab tab = widgets2Tabs.get(widget);
if (tab != null) {
selectTab(tab);
}
widgetsPanel.showWidget(widget.getWidget().asWidget());
}
@Override
public void removeWidget(WidgetToShow widget) {
final Tab tab = widgets2Tabs.get(widget);
if (tab != null) {
closeTab(tab);
}
}
private void removeWidgetFromUI(WidgetToShow widget) {
final Tab tab = widgets2Tabs.remove(widget);
if (tab != null) {
tabsPanel.remove(tab);
widgetsPanel.remove(widget.getWidget());
tabs2Widgets.remove(tab);
// remove item from drop-down menu
final MenuItemWidget listItemWidget = widgets2ListItems.remove(widget);
if (listItemWidget != null) {
menu.removeListItem(listItemWidget);
}
}
}
@Override
public void closePanel() {
if (splitLayoutPanel.getWidgetCount() == 1) {
parentPanel.removeChildSubPanel(this);
return;
}
splitLayoutPanel.remove(mainPanel);
// move widget from east/south part to the center
final Widget lastWidget = splitLayoutPanel.getWidget(0);
splitLayoutPanel.setWidgetSize(lastWidget, 0);
splitLayoutPanel.remove(lastWidget);
splitLayoutPanel.add(lastWidget);
}
@Override
public void removeChildSubPanel(Widget widget) {
if (splitLayoutPanel.getWidgetDirection(widget) == DockLayoutPanel.Direction.CENTER) {
// this is the only widget on the panel
// don't allow to remove it
return;
}
splitLayoutPanel.setWidgetSize(widget, 0);
splitLayoutPanel.remove(widget);
}
@Override
public void setParentPanel(SubPanelView parentPanel) {
this.parentPanel = parentPanel;
}
@Override
public void onMenuItemSelected(MenuItem menuItem) {
final Object data = menuItem.getData();
if (data instanceof Tab) {
selectTab((Tab)data);
WidgetToShow widget = tabs2Widgets.get(data);
if (widget != null) {
activateWidget(widget);
delegate.onWidgetFocused(widget.getWidget());
}
} else if (data instanceof Action) {
((Action)data).actionPerformed(null);
}
}
@Override
public void onMenuItemClosing(MenuItem menuItem) {
Object data = menuItem.getData();
if (data instanceof Tab) {
closeTab((Tab)data);
}
}
@Override
public void onTabClicked(Tab tab) {
selectTab(tab);
// TODO: extract code to the separate method
WidgetToShow widget = tabs2Widgets.get(tab);
if (widget != null) {
activateWidget(widget);
delegate.onWidgetFocused(widget.getWidget());
}
}
private void selectTab(Tab tab) {
for (Tab tabItem : tabs2Widgets.keySet()) {
tabItem.unSelect();
}
tab.select();
}
@Override
public void onTabClosing(Tab tab) {
closeTab(tab);
}
private void closeTab(Tab tab) {
final WidgetToShow widget = tabs2Widgets.get(tab);
if (widget != null) {
delegate.onWidgetRemoving(widget.getWidget(), new SubPanel.RemoveCallback() {
@Override
public void remove() {
removeWidgetFromUI(widget);
}
});
}
}
interface SubPanelViewImplUiBinder extends UiBinder<Widget, SubPanelViewImpl> {
}
}
| Set 'active' attribute for the currently active widget in the Processes panel
| ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/multisplitpanel/panel/SubPanelViewImpl.java | Set 'active' attribute for the currently active widget in the Processes panel |
|
Java | epl-1.0 | error: pathspec 'ClientProxy.java' did not match any file(s) known to git
| d9dd1ee983bae94645ff6337c11ef44faf3aae55 | 1 | gamingnut1/MineArtOnline | package com.kidokenji.mineartonline.proxy;
import com.kidokenji.mineartonline.init.MAOBlocks;
import com.kidokenji.mineartonline.init.MAOItems;
public class ClientProxy extends CommonProxy{
@Override
public void registerRenders(){
MAOBlocks.registerRenders();
MAOItems.registerRenders();
}
}
| ClientProxy.java | Create ClientProxy.java
Client Proxy | ClientProxy.java | Create ClientProxy.java |
|
Java | mpl-2.0 | error: pathspec 'gui/src/main/java/org/verapdf/pdfa/validators/SummarisingValidator.java' did not match any file(s) known to git
| 6496127d31a96a970d4240103baf3057def26c32 | 1 | carlwilson/veraPDF-library | /**
*
*/
package org.verapdf.pdfa.validators;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.verapdf.core.ValidationException;
import org.verapdf.pdfa.PDFAValidator;
import org.verapdf.pdfa.ValidationModelParser;
import org.verapdf.pdfa.results.TestAssertion;
import org.verapdf.pdfa.results.TestAssertion.Status;
import org.verapdf.pdfa.results.ValidationResult;
import org.verapdf.pdfa.results.ValidationResults;
import org.verapdf.pdfa.validation.ValidationProfile;
/**
* @author <a href="mailto:[email protected]">Carl Wilson</a>
*
*/
public class SummarisingValidator implements PDFAValidator {
private final PDFAValidator validator;
private final boolean logPassedTests;
protected SummarisingValidator(final ValidationProfile profile) {
this(profile, false);
}
protected SummarisingValidator(final ValidationProfile profile,
final boolean logPassedTests) {
super();
this.validator = new BaseValidator(profile);
this.logPassedTests = logPassedTests;
}
/**
* { @inheritDoc }
*/
@Override
public ValidationProfile getProfile() {
return this.validator.getProfile();
}
/**
* { @inheritDoc }
*/
@Override
public ValidationResult validate(final ValidationModelParser toValidate)
throws ValidationException, IOException {
if (this.logPassedTests)
return this.validator.validate(toValidate);
ValidationResult result = this.validator.validate(toValidate);
return ValidationResults.resultFromValues(result.getPDFAFlavour(),
stripPassedTests(result.getTestAssertions()),
result.isCompliant(), result.getTotalAssertions());
}
private static final Set<TestAssertion> stripPassedTests(
final Set<TestAssertion> toStrip) {
Set<TestAssertion> strippedSet = new HashSet<>();
for (TestAssertion test : toStrip) {
if (test.getStatus() != Status.PASSED)
strippedSet.add(test);
}
return strippedSet;
}
}
| gui/src/main/java/org/verapdf/pdfa/validators/SummarisingValidator.java | New reporting Validator wrapper.
| gui/src/main/java/org/verapdf/pdfa/validators/SummarisingValidator.java | New reporting Validator wrapper. |
|
Java | agpl-3.0 | 3b189078cf893ea48a9794a22f9fd8d5b1ce0d77 | 0 | jaytaylor/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,relateiq/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1 | package com.akiban.cserver.loader;
import com.akiban.ais.model.UserTable;
import com.akiban.ais.util.Command;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.IdentityHashMap;
public class DataGrouper
{
public DataGrouper(DB db, String artifactsSchema)
throws SQLException
{
this.db = db;
this.artifactsSchema = artifactsSchema;
}
public void run(IdentityHashMap<UserTable, TableTasks> tableTasksMap) throws Exception
{
DB.Connection connection = db.new Connection();
try {
prepareWorkArea(connection);
saveTasks(connection, tableTasksMap);
runTasks(connection);
} finally {
connection.close();
}
}
public void resume() throws Exception
{
DB.Connection connection = db.new Connection();
try {
cleanupFailedTasks(connection);
runTasks(connection);
} finally {
connection.close();
}
}
public void deleteWorkArea() throws SQLException
{
DB.Connection connection = db.new Connection();
try {
connection.new DDL(TEMPLATE_DROP_BULK_LOAD_SCHEMA, artifactsSchema).execute();
} finally {
connection.close();
}
}
private void cleanupFailedTasks(DB.Connection connection) throws Exception
{
logger.info(String.format("Cleanup from failed tasks"));
connection.new Query(TEMPLATE_ABANDONED_TASKS, artifactsSchema)
{
@Override
protected void handleRow(ResultSet resultSet) throws Exception
{
int taskId = resultSet.getInt(1);
String artifactTable = resultSet.getString(2);
final DB.Connection cleanupConnection = db.new Connection();
try {
cleanupConnection.new DDL(TEMPLATE_DROP_TABLE, artifactsSchema, artifactTable).execute();
cleanupConnection.new Update(TEMPLATE_RESET_TASK_STATE, artifactsSchema, taskId).execute();
} finally {
cleanupConnection.close();
}
}
}.execute();
}
private void runTasks(DB.Connection connection)
throws Exception
{
/*
* Task execution order:
* 1. $child
* 2. $parent in order of increasing depth
* 3. $final
* This guarantees that artifacts are created before they are needed, without the need to track
* individual task dependencies.
*/
runTasks("child", TEMPLATE_CHILD_TASKS, connection);
runTasks("parent", TEMPLATE_PARENT_TASKS_BY_DEPTH, connection);
runTasks("final", TEMPLATE_FINAL_TASKS, connection);
}
private void prepareWorkArea(DB.Connection connection)
throws SQLException
{
logger.info(String.format("Preparing work area %s", artifactsSchema));
connection.new DDL(TEMPLATE_DROP_BULK_LOAD_SCHEMA, artifactsSchema).execute();
connection.new DDL(TEMPLATE_CREATE_BULK_LOAD_SCHEMA, artifactsSchema).execute();
connection.new DDL(TEMPLATE_CREATE_TASKS_TABLE, artifactsSchema).execute();
}
private void saveTasks(DB.Connection connection, IdentityHashMap<UserTable, TableTasks> tableTasksMap)
throws SQLException
{
logger.info("Saving tasks");
for (TableTasks tableTasks : tableTasksMap.values()) {
tableTasks.saveTasks(connection);
}
}
private void runTasks(String label, String taskQueryTemplate, DB.Connection connection) throws Exception
{
logger.info(String.format("Running %s tasks", label));
connection.new Query(taskQueryTemplate, artifactsSchema)
{
@Override
protected void handleRow(ResultSet resultSet) throws SQLException, Command.Exception, IOException
{
// Need a separate connection for updates because the first connection (running the tasks query),
// is streaming results and can't support another statement at the same time.
DB.Connection updateConnection = db.new Connection();
try {
int taskId = resultSet.getInt(1);
String command = resultSet.getString(2);
updateConnection.new Update(TEMPLATE_MARK_STARTED, artifactsSchema, taskId).execute();
long start = System.nanoTime();
db.spawn(command);
long stop = System.nanoTime();
double timeSec = ((double)(stop - start)) / ONE_BILLION;
updateConnection.new Update(TEMPLATE_MARK_COMPLETED, artifactsSchema, timeSec, taskId).execute();
} finally {
updateConnection.close();
}
}
}.execute();
}
private static final Log logger = LogFactory.getLog(DataGrouper.class.getName());
private static final String TEMPLATE_DROP_BULK_LOAD_SCHEMA =
"drop schema if exists %s";
private static final String TEMPLATE_CREATE_BULK_LOAD_SCHEMA =
"create schema %s";
private static final String TEMPLATE_CREATE_TASKS_TABLE =
"create table %s.task(" +
" task_id int auto_increment, " +
" task_type enum('GenerateFinalBySort', " +
" 'GenerateFinalByMerge', " +
" 'GenerateChild', " +
" 'GenerateParentBySort'," +
" 'GenerateParentByMerge') not null, " +
" state enum('waiting', 'started', 'completed') not null, " +
" time_sec double, " +
" user_table_schema varchar(64) not null, " +
" user_table_table varchar(64) not null, " +
" user_table_depth int not null, " +
" artifact_schema varchar(64) not null, " +
" artifact_table varchar(64) not null, " +
" command varchar(10000) not null, " +
" primary key(task_id)" +
")";
private static final String TEMPLATE_MARK_STARTED =
"update %s.task " +
"set state = 'started' " +
"where task_id = %s";
private static final String TEMPLATE_MARK_COMPLETED =
"update %s.task " +
"set state = 'completed', " +
" time_sec = %s " +
"where task_id = %s";
private static final String TEMPLATE_FINAL_TASKS =
"select task_id, command " +
"from %s.task " +
"where task_type like 'GenerateFinal%%' " +
"and state = 'waiting'";
private static final String TEMPLATE_PARENT_TASKS_BY_DEPTH =
"select task_id, command " +
"from %s.task " +
"where task_type like 'GenerateParent%%' " +
"and state = 'waiting' " +
"order by user_table_depth";
private static final String TEMPLATE_CHILD_TASKS =
"select task_id, command " +
"from %s.task " +
"where task_type = 'GenerateChild' " +
"and state = 'waiting'";
private static final String TEMPLATE_ABANDONED_TASKS =
"select task_id, artifact_table " +
"from %s.task " +
"where state = 'started'";
private static final String TEMPLATE_DROP_TABLE =
"drop table if exists %s.%s";
private static final String TEMPLATE_RESET_TASK_STATE =
"update %s.task " +
"set state = 'waiting' " +
"where task_id = %s";
private static final int ONE_BILLION = 1000 * 1000 * 1000;
private final DB db;
private final String artifactsSchema;
}
| src/main/java/com/akiban/cserver/loader/DataGrouper.java | package com.akiban.cserver.loader;
import com.akiban.ais.model.UserTable;
import com.akiban.ais.util.Command;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.IdentityHashMap;
public class DataGrouper
{
public DataGrouper(DB db, String artifactsSchema)
throws SQLException
{
this.db = db;
this.artifactsSchema = artifactsSchema;
}
public void run(IdentityHashMap<UserTable, TableTasks> tableTasksMap) throws Exception
{
DB.Connection connection = db.new Connection();
try {
prepareWorkArea(connection);
saveTasks(connection, tableTasksMap);
runTasks(connection);
} finally {
connection.close();
}
}
public void resume() throws Exception
{
DB.Connection connection = db.new Connection();
try {
cleanupFailedTasks(connection);
runTasks(connection);
} finally {
connection.close();
}
}
public void deleteWorkArea() throws SQLException
{
DB.Connection connection = db.new Connection();
try {
connection.new DDL(TEMPLATE_DROP_BULK_LOAD_SCHEMA, artifactsSchema).execute();
} finally {
connection.close();
}
}
private void cleanupFailedTasks(DB.Connection connection) throws Exception
{
logger.info(String.format("Cleanup from failed tasks"));
connection.new Query(TEMPLATE_ABANDONED_TASKS, artifactsSchema)
{
@Override
protected void handleRow(ResultSet resultSet) throws Exception
{
int taskId = resultSet.getInt(1);
String artifactTable = resultSet.getString(2);
final DB.Connection cleanupConnection = db.new Connection();
try {
cleanupConnection.new DDL(TEMPLATE_DROP_TABLE, artifactsSchema, artifactTable).execute();
cleanupConnection.new Update(TEMPLATE_RESET_TASK_STATE, artifactsSchema, taskId).execute();
} finally {
cleanupConnection.close();
}
}
}.execute();
}
private void runTasks(DB.Connection connection)
throws Exception
{
/*
* Task execution order:
* 1. $child
* 2. $parent in order of increasing depth
* 3. $final
* This guarantees that artifacts are created before they are needed, without the need to track
* individual task dependencies.
*/
runTasks("child", TEMPLATE_CHILD_TASKS, connection);
runTasks("parent", TEMPLATE_PARENT_TASKS_BY_DEPTH, connection);
runTasks("final", TEMPLATE_FINAL_TASKS, connection);
}
private void prepareWorkArea(DB.Connection connection)
throws SQLException
{
logger.info(String.format("Preparing work area %s", artifactsSchema));
connection.new DDL(TEMPLATE_DROP_BULK_LOAD_SCHEMA, artifactsSchema).execute();
connection.new DDL(TEMPLATE_CREATE_BULK_LOAD_SCHEMA, artifactsSchema).execute();
connection.new DDL(TEMPLATE_CREATE_TASKS_TABLE, artifactsSchema).execute();
}
private void saveTasks(DB.Connection connection, IdentityHashMap<UserTable, TableTasks> tableTasksMap)
throws SQLException
{
logger.info("Saving tasks");
for (TableTasks tableTasks : tableTasksMap.values()) {
tableTasks.saveTasks(connection);
}
}
private void runTasks(String label, String taskQueryTemplate, DB.Connection connection) throws Exception
{
logger.info(String.format("Running %s tasks", label));
connection.new Query(taskQueryTemplate, artifactsSchema)
{
@Override
protected void handleRow(ResultSet resultSet) throws SQLException, Command.Exception, IOException
{
// Need a separate connection for updates because the first connection (running the tasks query),
// is streaming results and can't support another statement at the same time.
DB.Connection updateConnection = db.new Connection();
try {
int taskId = resultSet.getInt(1);
String command = resultSet.getString(2);
updateConnection.new Update(TEMPLATE_MARK_STARTED, artifactsSchema, taskId).execute();
db.spawn(command);
updateConnection.new Update(TEMPLATE_MARK_COMPLETED, artifactsSchema, taskId).execute();
} finally {
updateConnection.close();
}
}
}.execute();
}
private static final Log logger = LogFactory.getLog(DataGrouper.class.getName());
private static final String TEMPLATE_DROP_BULK_LOAD_SCHEMA =
"drop schema if exists %s";
private static final String TEMPLATE_CREATE_BULK_LOAD_SCHEMA =
"create schema %s";
private static final String TEMPLATE_CREATE_TASKS_TABLE =
"create table %s.task(" +
" task_id int auto_increment, " +
" task_type enum('GenerateFinalBySort', " +
" 'GenerateFinalByMerge', " +
" 'GenerateChild', " +
" 'GenerateParentBySort'," +
" 'GenerateParentByMerge') not null, " +
" state enum('waiting', 'started', 'completed') not null, " +
" user_table_schema varchar(64) not null, " +
" user_table_table varchar(64) not null, " +
" user_table_depth int not null, " +
" artifact_schema varchar(64) not null, " +
" artifact_table varchar(64) not null, " +
" command varchar(10000) not null, " +
" primary key(task_id)" +
")";
private static final String TEMPLATE_MARK_STARTED =
"update %s.task " +
"set state = 'started' " +
"where task_id = %s";
private static final String TEMPLATE_MARK_COMPLETED =
"update %s.task " +
"set state = 'completed' " +
"where task_id = %s";
private static final String TEMPLATE_FINAL_TASKS =
"select task_id, command " +
"from %s.task " +
"where task_type like 'GenerateFinal%%' " +
"and state = 'waiting'";
private static final String TEMPLATE_PARENT_TASKS_BY_DEPTH =
"select task_id, command " +
"from %s.task " +
"where task_type like 'GenerateParent%%' " +
"and state = 'waiting' " +
"order by user_table_depth";
private static final String TEMPLATE_CHILD_TASKS =
"select task_id, command " +
"from %s.task " +
"where task_type = 'GenerateChild' " +
"and state = 'waiting'";
private static final String TEMPLATE_ABANDONED_TASKS =
"select task_id, artifact_table " +
"from %s.task " +
"where state = 'started'";
private static final String TEMPLATE_DROP_TABLE =
"drop table if exists %s.%s";
private static final String TEMPLATE_RESET_TASK_STATE =
"update %s.task " +
"set state = 'waiting' " +
"where task_id = %s";
private final DB db;
private final String artifactsSchema;
}
| Loader's task table now records time of each mysql task. | src/main/java/com/akiban/cserver/loader/DataGrouper.java | Loader's task table now records time of each mysql task. |
|
Java | agpl-3.0 | b06e1a54fe8babb303292aee0d4664e769235875 | 0 | fqqb/yamcs,bitblit11/yamcs,m-sc/yamcs,yamcs/yamcs,fqqb/yamcs,fqqb/yamcs,m-sc/yamcs,m-sc/yamcs,bitblit11/yamcs,fqqb/yamcs,dhosa/yamcs,m-sc/yamcs,m-sc/yamcs,yamcs/yamcs,dhosa/yamcs,bitblit11/yamcs,dhosa/yamcs,m-sc/yamcs,yamcs/yamcs,bitblit11/yamcs,yamcs/yamcs,yamcs/yamcs,bitblit11/yamcs,fqqb/yamcs,yamcs/yamcs,dhosa/yamcs,fqqb/yamcs,dhosa/yamcs | package org.yamcs.xtceproc;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.ItemIdPacketConsumerStruct;
import org.yamcs.ParameterValue;
import org.yamcs.utils.TimeEncoding;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtce.SequenceContainer;
import org.yamcs.xtce.XtceDb;
/**
*
* Extracts parameters out of packets based on the XTCE description
*
*
* @author mache
*
*/
public class XtceTmExtractor {
private static final Logger log=LoggerFactory.getLogger(XtceTmExtractor.class);
protected final Subscription subscription;
private ProcessingStatistics stats=new ProcessingStatistics();
public final XtceDb xtcedb;
final SequenceContainer rootContainer;
ArrayList<ParameterValue> paramResult=new ArrayList<ParameterValue>();
ArrayList<SequenceContainer> containerResult=new ArrayList<SequenceContainer>();
/**
* Creates a TmExtractor extracting data according to the XtceDb
* @param xtcedb
*/
public XtceTmExtractor(XtceDb xtcedb) {
this.xtcedb=xtcedb;
this.subscription=new Subscription(xtcedb);
rootContainer=xtcedb.getRootSequenceContainer();
}
/**
* Adds a parameter to the current subscription list:
* finds all the SequenceContainers in which this parameter may appear and adds them to the list.
* also for each sequence container adds the parameter needed to instantiate the sequence container.
* @param param parameter to be added to the current subscription list
*/
public void startProviding(Parameter param) {
synchronized(subscription) {
subscription.addParameter(param);
}
}
/**
* adds all parameters to the subscription
*/
public void startProvidingAll() {
subscription.addAll(rootContainer);
}
public void stopProviding(Parameter param) {
//TODO 2.0 do something here
}
/**
* Extract one packet
*
*/
public void processPacket(ByteBuffer bb, long generationTime) {
try {
paramResult=new ArrayList<ParameterValue>();
containerResult=new ArrayList<SequenceContainer>();
synchronized(subscription) {
long aquisitionTime=TimeEncoding.currentInstant(); //we do this in order that all the parameters inside this packet have the same acquisition time
ProcessingContext pcontext=new ProcessingContext(bb, 0, 0, subscription, paramResult, containerResult, aquisitionTime, generationTime, stats);
pcontext.sequenceContainerProcessor.extract(rootContainer);
for(ParameterValue pv:paramResult) {
pcontext.parameterTypeProcessor.performLimitChecking(pv.getParameter().getParameterType(), pv);
}
}
} catch (Exception e) {
log.error("got exception in tmextractor ", e);
}
}
public void resetStatistics() {
stats.reset();
}
public ProcessingStatistics getStatistics(){
return stats;
}
public void startProviding(SequenceContainer sequenceContainer) {
synchronized(subscription) {
subscription.addSequenceContainer(sequenceContainer);
}
}
public void subscribePackets(List<ItemIdPacketConsumerStruct> iipcs) {
synchronized(subscription) {
for(ItemIdPacketConsumerStruct i:iipcs) {
subscription.addSequenceContainer(i.def);
}
}
}
public ArrayList<ParameterValue> getParameterResult() {
return paramResult;
}
public ArrayList<SequenceContainer> getContainerResult() {
return containerResult;
}
public Subscription getSubscription() {
return subscription;
}
@Override
public String toString() {
return subscription.toString();
}
}
| yamcs-core/src/main/java/org/yamcs/xtceproc/XtceTmExtractor.java | package org.yamcs.xtceproc;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.ItemIdPacketConsumerStruct;
import org.yamcs.ParameterValue;
import org.yamcs.utils.StringConvertors;
import org.yamcs.utils.TimeEncoding;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtce.SequenceContainer;
import org.yamcs.xtce.XtceDb;
/**
*
* Extracts parameters out of packets based on the XTCE description
*
*
* @author mache
*
*/
public class XtceTmExtractor {
Logger log=LoggerFactory.getLogger(this.getClass().getName());
protected final Subscription subscription;
private ProcessingStatistics stats=new ProcessingStatistics();
public final XtceDb xtcedb;
final SequenceContainer rootContainer;
ArrayList<ParameterValue> paramResult=new ArrayList<ParameterValue>();
ArrayList<SequenceContainer> containerResult=new ArrayList<SequenceContainer>();
/**
* Creates a TmExtractor extracting data according to the XtceDb
* @param xtcedb
*/
public XtceTmExtractor(XtceDb xtcedb) {
log=LoggerFactory.getLogger(this.getClass().getName());
this.xtcedb=xtcedb;
this.subscription=new Subscription(xtcedb);
rootContainer=xtcedb.getRootSequenceContainer();
}
/**
* Adds a parameter to the current subscription list:
* finds all the SequenceContainers in which this parameter may appear and adds them to the list.
* also for each sequence container adds the parameter needed to instantiate the sequence container.
* @param param parameter to be added to the current subscription list
*/
public void startProviding(Parameter param) {
synchronized(subscription) {
subscription.addParameter(param);
}
}
/**
* adds all parameters to the subscription
*/
public void startProvidingAll() {
subscription.addAll(rootContainer);
}
public void stopProviding(Parameter param) {
//TODO 2.0 do something here
}
/**
* Extract one packets
*
*/
public void processPacket(ByteBuffer bb, long generationTime){
try {
//we only support packets that have ccsds secondary header
if(bb.capacity()<16) {
log.warn("packet smaller than 16 bytes has been received size="+(bb.capacity())+" content:"+StringConvertors.byteBufferToHexString(bb));
return;
}
paramResult=new ArrayList<ParameterValue>();
containerResult=new ArrayList<SequenceContainer>();
synchronized(subscription) {
long aquisitionTime=TimeEncoding.currentInstant(); //we do this in order that all the parameters inside this packet have the same acquisition time
ProcessingContext pcontext=new ProcessingContext(bb, 0, 0, subscription, paramResult, containerResult, aquisitionTime, generationTime, stats);
pcontext.sequenceContainerProcessor.extract(rootContainer);
for(ParameterValue pv:paramResult) {
pcontext.parameterTypeProcessor.performLimitChecking(pv.getParameter().getParameterType(), pv);
}
}
} catch (Exception e) {
log.error("got exception in tmextractor ", e);
e.printStackTrace();
}
}
public void resetStatistics() {
stats.reset();
}
public ProcessingStatistics getStatistics(){
return stats;
}
public void startProviding(SequenceContainer sequenceContainer) {
synchronized(subscription) {
subscription.addSequenceContainer(sequenceContainer);
}
}
public void subscribePackets(List<ItemIdPacketConsumerStruct> iipcs) {
synchronized(subscription) {
for(ItemIdPacketConsumerStruct i:iipcs) {
subscription.addSequenceContainer(i.def);
}
}
}
public ArrayList<ParameterValue> getParameterResult() {
return paramResult;
}
public ArrayList<SequenceContainer> getContainerResult() {
return containerResult;
}
public Subscription getSubscription() {
return subscription;
}
@Override
public String toString() {
return subscription.toString();
}
}
| Remove check on minimal packet size
The XtceTmExtractor has a wider applicability than CCSDS packets.
Remove the check on presence of CCSDS secundary header.
| yamcs-core/src/main/java/org/yamcs/xtceproc/XtceTmExtractor.java | Remove check on minimal packet size |
|
Java | lgpl-2.1 | error: pathspec 'src/test/java/org/lightmare/utils/NamingUtilsTest.java' did not match any file(s) known to git
| 34cdb0208a6355d0e2cf068359e4046399bb4c26 | 1 | levants/lightmare | package org.lightmare.utils;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.junit.Test;
public class NamingUtilsTest {
@Test
public void contextCloseTest() {
String name = "test_name";
String value = "test_value";
try {
InitialContext contextBind = new InitialContext();
contextBind.bind(name, value);
contextBind.close();
InitialContext contextGet = new InitialContext();
Object gotten = contextGet.lookup(name);
System.out.println(gotten);
} catch (NamingException ex) {
ex.printStackTrace();
}
}
}
| src/test/java/org/lightmare/utils/NamingUtilsTest.java | added test cases for naming utilities | src/test/java/org/lightmare/utils/NamingUtilsTest.java | added test cases for naming utilities |
|
Java | lgpl-2.1 | error: pathspec 'intermine/src/test/org/intermine/codegen/CastorModelOutputTest.java' did not match any file(s) known to git
| a0c82ac70cdc942b06b67f5dc409b611ea4e97e8 | 1 | kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,drhee/toxoMine,JoeCarlson/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,julie-sullivan/phytomine,justincc/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,JoeCarlson/intermine,elsiklab/intermine,JoeCarlson/intermine,julie-sullivan/phytomine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,tomck/intermine,elsiklab/intermine,julie-sullivan/phytomine,tomck/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,zebrafishmine/intermine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,tomck/intermine,elsiklab/intermine,JoeCarlson/intermine,justincc/intermine,elsiklab/intermine,drhee/toxoMine,elsiklab/intermine,tomck/intermine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,elsiklab/intermine,kimrutherford/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,julie-sullivan/phytomine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,joshkh/intermine,joshkh/intermine,julie-sullivan/phytomine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,JoeCarlson/intermine,julie-sullivan/phytomine,tomck/intermine,julie-sullivan/phytomine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,justincc/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine | package org.flymine.codegen;
import junit.framework.TestCase;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.URL;
import org.exolab.castor.mapping.*;
import org.exolab.castor.xml.*;
import org.flymine.model.testmodel.*;
import org.flymine.util.*;
public class CastorModelOutputTest extends TestCase
{
protected static final org.apache.log4j.Logger LOG
= org.apache.log4j.Logger.getLogger(CastorModelOutputTest.class);
private Mapping map;
private Company p1, p2;
private Contractor c1, c2;
private int fakeId = 0;
private File file;
public CastorModelOutputTest(String name) {
super(name);
}
public void setUp() throws Exception {
URL mapFile = getClass().getClassLoader().getResource("castor_xml_testmodel.xml");
map = new Mapping();
map.loadMapping(mapFile);
p1 = p1(); p2 = p2();
c1 = c1(); c2 = c2();
p1.setContractors(Arrays.asList(new Object[] { c1, c2 }));
p2.setContractors(Arrays.asList(new Object[] { c1, c2 }));
p1.setOldContracts(Arrays.asList(new Object[] {c1, c1, c2, c2}));
p2.setOldContracts(Arrays.asList(new Object[] {c1, c1, c2, c2}));
c1.setCompanys(Arrays.asList(new Object[] {p1, p2}));
c2.setCompanys(Arrays.asList(new Object[] {p1, p2}));
c1.setOldComs(Arrays.asList(new Object[] {p1, p1, p2, p2}));
c2.setOldComs(Arrays.asList(new Object[] {p1, p1, p2, p2}));
}
public void tearDown() {
file.delete();
}
public void testTestData() throws Exception {
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(p1);
List flatList = (List)flatten(list);
setIds(flatList);
ListBean bean = new ListBean();
bean.setItems(flatList);
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flatList);
Company com = (Company)result.get(0);
assertEquals(com, p1);
}
public void testSimpleObject() throws Exception {
Employee e1 = new Employee();
e1.setName("e1");
e1.setFullTime(true);
e1.setAge(25);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(e1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testSimpleObject..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Employee e2 = (Employee) result.get(0);
assertEquals(e1, e2);
}
public void testSimpleRelation() throws Exception {
Employee e1 = new Employee();
e1.setName("e1");
e1.setFullTime(true);
e1.setAge(25);
Address a1 = new Address();
a1.setAddress("a1");
e1.setAddress(a1);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(e1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testSimpleRelation..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Employee e2 = (Employee) result.get(0);
assertEquals(e1, e2);
Address a2 = (Address) result.get(1);
assertEquals(a1, a2);
assertEquals(a1, e2.getAddress());
}
public void testOneToOne() throws Exception {
Company c1 = new Company();
c1.setName("c1");
c1.setVatNumber(101);
CEO ceo1 = new CEO();
ceo1.setName("ceo1");
ceo1.setAge(40);
ceo1.setFullTime(false);
ceo1.setTitle("Dr.");
ceo1.setSalary(10000);
c1.setCEO(ceo1);
ceo1.setCompany(c1);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(c1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testOneToOne..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Company c2 = (Company) result.get(0);
assertEquals(c1, c2);
CEO ceo2 = (CEO) result.get(1);
assertEquals(ceo1, ceo2);
CEO ceo3 = c2.getCEO();
assertEquals(ceo1, ceo3);
Company c3 = ceo2.getCompany();
assertEquals(c1, c3);
}
public void testUnidirectional() throws Exception {
Department d1 = new Department();
d1.setName("d1");
Manager m1 = new Manager();
m1.setName("m1");
m1.setAge(40);
m1.setFullTime(false);
m1.setTitle("Dr.");
d1.setManager(m1);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(d1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testUnidirectional..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Department d2 = (Department) result.get(0);
assertEquals(d1, d2);
Manager m2 = (Manager) result.get(1);
assertEquals(m1, m2);
Manager m3 = d2.getManager();
assertEquals(m1, m3);
}
public void testCollection() throws Exception {
Company c1 = new Company();
c1.setName("c1");
c1.setVatNumber(101);
Department d1 = new Department();
d1.setName("d1");
Department d2 = new Department();
d2.setName("d2");
Department d3 = new Department();
d3.setName("d3");
List depts = new ArrayList();
depts.addAll(Arrays.asList(new Object[] {d1, d2, d3}));
c1.setDepartments(depts);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(c1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testCollection..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Company c2 = (Company) result.get(0);
assertEquals(c1, c2);
Department dd1 = (Department) result.get(1);
assertEquals(d1, dd1);
Department dd2 = (Department) result.get(2);
assertEquals(d2, dd2);
Department dd3 = (Department) result.get(3);
assertEquals(d3, dd3);
assertEquals(depts, c2.getDepartments());
}
public void testManyToMany() throws Exception {
Company c1 = new Company();
c1.setName("c1");
c1.setVatNumber(101);
Company c2 = new Company();
c2.setName("c2");
c2.setVatNumber(202);
Contractor t1 = new Contractor();
t1.setName("t1");
Contractor t2 = new Contractor();
t2.setName("t2");
List ts1 = new ArrayList();
ts1.add(t1);
List ts2 = new ArrayList();
ts2.addAll(Arrays.asList(new Object[] {t1, t2}));
List cs1 = new ArrayList();
cs1.add(c1);
List cs2 = new ArrayList();
cs2.addAll(Arrays.asList(new Object[] {c1, c2}));
c1.setContractors(ts1);
c2.setContractors(ts2);
t1.setCompanys(cs1);
t2.setCompanys(cs2);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(c1);
list.add(c2);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testManyToMany..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Company cc1 = (Company) result.get(0);
assertEquals(c1, cc1);
List tts1 = cc1.getContractors();
assertEquals(ts1, tts1);
Company cc2 = (Company) result.get(2);
assertEquals(c2, cc2);
List tts2 = cc2.getContractors();
assertEquals(ts2, tts2);
Contractor tt1 = (Contractor) tts1.get(0);
assertEquals(cs1, tt1.getCompanys());
Contractor tt2 = (Contractor) tts2.get(1);
assertEquals(cs2, tt2.getCompanys());
}
public void testInheritatnce() throws Exception {
Department d1 = new Department();
d1.setName("d1");
Employee e1 = new Employee();
e1.setName("e1");
e1.setFullTime(true);
e1.setAge(25);
Manager e2 = new Manager();
e2.setName("e2_m");
e2.setFullTime(true);
e2.setAge(35);
e2.setTitle("Dr.");
CEO e3 = new CEO();
e3.setName("e3_c");
e3.setFullTime(true);
e3.setAge(45);
e3.setSalary(10000);
List emps = new ArrayList();
emps.addAll(Arrays.asList(new Object[] {e1, e2, e3}));
d1.setEmployees(emps);
d1.setManager((Manager)e2);
e1.setDepartment(d1);
e2.setDepartment(d1);
e3.setDepartment(d1);
file = new File("temp.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
List list = new ArrayList();
list.add(d1);
List flat = (List)flatten(list);
setIds(flat);
ListBean bean = new ListBean();
bean.setItems(flat);
//LOG.warn("testInheritance..." + bean.getItems().toString());
marshaller.marshal(bean);
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
List result = (List)unmarshaller.unmarshal(reader);
stripIds(flat);
Department dd1 = (Department) result.get(0);
assertEquals(d1, dd1);
Employee ee1 = (Employee) result.get(1);
assertEquals(e1, ee1);
Employee ee2 = (Employee) result.get(2);
assertEquals(e2, ee2);
Employee ee3 = (Employee) result.get(3);
assertEquals(e3, ee3);
assertEquals(d1, ee1.getDepartment());
assertEquals(e2, dd1.getManager());
}
// set fake ids for a collection of business objects
void setIds(Collection c) throws Exception {
Iterator iter = c.iterator();
while (iter.hasNext()) {
fakeId++;
Object obj = iter.next();
Class cls = obj.getClass();
Field f = getIdField(cls);
if (f != null) {
f.setAccessible(true);
f.set(obj, new Integer(fakeId));
}
}
}
// remove fake ids for a collection of business objects
void stripIds(Collection c) throws Exception {
Iterator iter = c.iterator();
while (iter.hasNext()) {
fakeId++;
Object obj = iter.next();
Class cls = obj.getClass();
Field f = getIdField(cls);
if (f != null) {
f.setAccessible(true);
f.set(obj, null);
}
}
}
// find the id field of an object, search superclasses if not found
Field getIdField(Class cls) throws Exception {
Field[] fields = cls.getDeclaredFields();
for(int i=0; i<fields.length; i++) {
if (fields[i].getName() == "id") {
return fields[i];
}
}
Class sup = cls.getSuperclass();
if (sup != null && !sup.isInterface()) {
return getIdField(sup);
}
return null;
}
// make all nested objects top-level in returned collection
Collection flatten(Collection c) throws Exception {
List toStore = new ArrayList();
Iterator i = c.iterator();
while(i.hasNext()) {
flatten(i.next(), toStore);
}
return toStore;
}
void flatten(Object o, Collection c) throws Exception {
if(o == null || c.contains(o)) {
return;
}
c.add(o);
Method[] getters = TypeUtil.getGetters(o.getClass());
for(int i=0;i<getters.length;i++) {
Method getter = getters[i];
Class returnType = getter.getReturnType();
if(ModelUtil.isCollection(returnType)) {
Iterator iter = ((Collection)getter.invoke(o, new Object[] {})).iterator();
while(iter.hasNext()) {
flatten(iter.next(), c);
}
} else if(ModelUtil.isReference(returnType)) {
flatten(getter.invoke(o, new Object[] {}), c);
}
}
}
Contractor c1() {
Address a1 = new Address();
a1.setAddress("Contractor Personal Street, AVille");
Address a2 = new Address();
a2.setAddress("Contractor Business Street, AVille");
Contractor c = new Contractor();
c.setName("ContractorA");
c.setPersonalAddress(a1);
c.setBusinessAddress(a2);
return c;
}
Contractor c2() {
Address a1 = new Address();
a1.setAddress("Contractor Personal Street, BVille");
Address a2 = new Address();
a2.setAddress("Contractor Business Street, BVille");
Contractor c = new Contractor();
c.setName("ContractorB");
c.setPersonalAddress(a1);
c.setBusinessAddress(a2);
return c;
}
Company p1() {
Address a1 = new Address();
a1.setAddress("Company Street, AVille");
Address a2 = new Address();
a2.setAddress("Employee Street, AVille");
Company p = new Company();
p.setName("CompanyA");
p.setVatNumber(1234);
p.setAddress(a1);
Employee e1 = new Manager();
e1.setName("EmployeeA1");
e1.setFullTime(true);
e1.setAddress(a2);
e1.setAge(10);
Employee e2 = new Employee();
e2.setName("EmployeeA2");
e2.setFullTime(true);
e2.setAddress(a2);
e2.setAge(20);
Employee e3 = new Employee();
e3.setName("EmployeeA3");
e3.setFullTime(false);
e3.setAddress(a2);
e3.setAge(30);
Department d1 = new Department();
d1.setName("DepartmentA1");
d1.setManager((Manager) e1);
d1.setEmployees(Arrays.asList(new Object[] { e1, e2, e3 }));
d1.setCompany(p);
p.setDepartments(Arrays.asList(new Object[] { d1 }));
return p;
}
Company p2() {
Address a1 = new Address();
a1.setAddress("Company Street, BVille");
Address a2 = new Address();
a2.setAddress("Employee Street, BVille");
Company p = new Company();
p.setName("CompanyB");
p.setVatNumber(5678);
p.setAddress(a1);
CEO e1 = new CEO();
e1.setName("EmployeeB1");
e1.setFullTime(true);
e1.setAddress(a2);
e1.setAge(40);
e1.setTitle("Mr.");
e1.setSalary(45000);
Employee e2 = new Employee();
e2.setName("EmployeeB2");
e2.setFullTime(true);
e2.setAddress(a2);
e2.setAge(50);
Employee e3 = new Manager();
e3.setName("EmployeeB3");
e3.setFullTime(true);
e3.setAddress(a2);
e3.setAge(60);
Department d1 = new Department();
d1.setName("DepartmentB1");
d1.setManager(e1);
d1.setEmployees(Arrays.asList(new Object[] { e1, e2 }));
d1.setCompany(p);
Department d2 = new Department();
d2.setName("DepartmentB2");
d2.setManager((Manager) e3);
d2.setEmployees(Arrays.asList(new Object[] { e3 }));
d2.setCompany(p);
p.setDepartments(Arrays.asList(new Object[] { d1, d2 }));
return p;
}
}
| intermine/src/test/org/intermine/codegen/CastorModelOutputTest.java | test relationship types map correctly to xml
| intermine/src/test/org/intermine/codegen/CastorModelOutputTest.java | test relationship types map correctly to xml |
|
Java | lgpl-2.1 | error: pathspec 'LGPL/CommonSoftware/ACSLaser/alarm-clients/test/alma/alarmsystem/clients/test/CategoryClientTest.java' did not match any file(s) known to git
| 580bfaa22af6ed11fa89318508e6597d5290c123 | 1 | ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO | /*
* ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2007
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package alma.alarmsystem.clients.test;
import java.sql.Timestamp;
import java.util.Vector;
import cern.laser.client.data.Alarm;
import cern.laser.client.services.selection.AlarmSelectionListener;
import cern.laser.client.services.selection.LaserSelectionException;
import cern.laser.source.alarmsysteminterface.FaultState;
import alma.acs.component.client.ComponentClientTestCase;
import alma.alarmsystem.clients.CategoryClient;
import alma.alarmsystem.source.ACSAlarmSystemInterface;
import alma.alarmsystem.source.ACSAlarmSystemInterfaceFactory;
import alma.alarmsystem.source.ACSFaultState;
public class CategoryClientTest extends ComponentClientTestCase implements AlarmSelectionListener {
/**
* The definition of the alarms as we expect they arrive from
* the alarm system
*
* @author acaproni
*
*/
private enum AlarmsFromCDB {
M1_1A("TEST", "TEST_MEMBER1", 1, true,2,"The cause","Run and fix quickly","Test alarm 1","A disaster"),
M1_2A("TEST", "TEST_MEMBER1", 2, true,3,null,null,"Test alarm 2",null),
M2_1A("TEST", "TEST_MEMBER2", 1, true,2,"The cause","Run and fix quickly","Test alarm 1","A disaster"),
M2_2A("TEST", "TEST_MEMBER2", 2, true,3,null,null,"Test alarm 2",null),
M1_1I("TEST", "TEST_MEMBER1", 1, false,2,"The cause","Run and fix quickly","Test alarm 1","A disaster"),
M1_2I("TEST", "TEST_MEMBER1", 2, false,3,null,null,"Test alarm 2",null),
M2_1I("TEST", "TEST_MEMBER2", 1, false,2,"The cause","Run and fix quickly","Test alarm 1","A disaster"),
M2_2I("TEST", "TEST_MEMBER2", 2, false,3,null,null,"Test alarm 2",null);
public final String FF;
public final String FM;
public final Integer FC;
public boolean state;
public final String cause;
public final String action;
public final String consequence;
public final String description;
public final Integer priority;
private AlarmsFromCDB(
String FF,
String FM,
int code,
boolean status,
int pri,
String cause,
String action,
String desc,
String consequence) {
this.FF=FF;
this.FM=FM;
this.FC=code;
this.state=status;
this.priority=pri;
this.consequence=consequence;
this.description=desc;
this.cause=cause;
this.action=action;
}
/**
* Return the alarm with the given triplet
*
* @param FF Fault Family
* @param FM Fault Member
* @param code Fault Code
* @return The alarm with the given triplet
* null if the triplet does not exist
*/
public static AlarmsFromCDB getCDBAlarm(String FF, String FM, int code) {
for (AlarmsFromCDB alarm: AlarmsFromCDB.values()) {
if (alarm.FF.equals(FF) && alarm.FM.equals(FM) && alarm.FC==code) {
return alarm;
}
}
return null;
}
}
// The categoryClient to test
private CategoryClient categoryClient;
// The vector with the alarms received
private Vector<Alarm> alarmsReceived;
// Max number of seconds to wait for the messages
private static final int MAX_TIMEOUT = 120;
/**
* Constructor
*
* @throws Exception
*/
public CategoryClientTest() throws Exception{
super("CategoryClientTest");
}
/**
* @see extends ComponentClientTestCase
*/
public void setUp() throws Exception {
super.setUp();
categoryClient = new CategoryClient(getContainerServices());
assertNotNull(categoryClient);
alarmsReceived=new Vector<Alarm>();
}
/**
* @see extends ComponentClientTestCase
*/
public void teraDown() throws Exception {
categoryClient.close();
alarmsReceived.clear();
super.tearDown();
}
/**
* @see AlarmSelectionListener
*/
public void onAlarm(Alarm alarm) {
synchronized (alarmsReceived) {
alarmsReceived.add(alarm);
}
}
/**
* @see AlarmSelectionListener
*/
public void onException(LaserSelectionException e) {
System.err.println("onException: "+e.getMessage());
e.printStackTrace(System.err);
}
/**
* Sends a couple of alarms and check if they arrive from the client
* @throws Exception
*/
public void testAlarmReception() throws Exception {
categoryClient.connect(this);
// Send the alarms
send_alarm("TEST", "TEST_MEMBER1", 1, true);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER1", 2, true);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER2", 1, true);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER2", 2, true);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER1", 1, false);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER1", 2, false);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER2", 1, false);
try {
Thread.sleep(5000);
} catch (Exception e) {}
send_alarm("TEST", "TEST_MEMBER2", 2, false);
// Wait for all the messages
assertEquals(8,waitForMessages(8));
// Check the correctness of the messages
for (Alarm alarm: alarmsReceived) {
assertEquals("Alex", alarm.getResponsiblePerson().getFirstName());
assertEquals("123456", alarm.getResponsiblePerson().getGsmNumber());
assertEquals("[email protected]", alarm.getResponsiblePerson().getEMail());
assertEquals("http://tempuri.org", alarm.getHelpURL().toString());
AlarmsFromCDB cdbAlarm = AlarmsFromCDB.getCDBAlarm(
alarm.getTriplet().getFaultFamily(),
alarm.getTriplet().getFaultMember(),
alarm.getTriplet().getFaultCode());
String alarmDesc = "<"+alarm.getTriplet().getFaultFamily()+", "+alarm.getTriplet().getFaultMember()+", "+alarm.getTriplet().getFaultCode()+ "> ";
assertEquals(alarmDesc+"Priority",cdbAlarm.priority,alarm.getPriority());
assertEquals(alarmDesc+"Cause",cdbAlarm.cause,alarm.getCause());
assertEquals(alarmDesc+"Description",cdbAlarm.description,alarm.getProblemDescription());
assertEquals(alarmDesc+"Consequence",cdbAlarm.consequence,alarm.getConsequence());
assertEquals(alarmDesc+"Action",cdbAlarm.action,alarm.getAction());
}
}
/**
* Push an alarm
*
* @param active If true the alarm is active
*/
private void send_alarm(String family, String member, int code, boolean active) throws Exception {
ACSAlarmSystemInterface alarmSource;
alarmSource = ACSAlarmSystemInterfaceFactory.createSource(member);
ACSFaultState fs = ACSAlarmSystemInterfaceFactory.createFaultState(family, member, code);
if (active) {
fs.setDescriptor(FaultState.ACTIVE);
} else {
fs.setDescriptor(FaultState.TERMINATE);
}
fs.setUserTimestamp(new Timestamp(System.currentTimeMillis()));
alarmSource.push(fs);
}
/**
* Wait for the messages from the alarm system.
*
* @param numOfMessages The number of messages to wait for
* @return true if all the messages are received
* false in case of timeout (i.e. not all the messages received
* in MAX_TIMEOUT seconds)
*/
private int waitForMessages(int numOfMessages) {
long startTime = System.currentTimeMillis();
long endTime = startTime+MAX_TIMEOUT*1000;
while (alarmsReceived.size()<numOfMessages && System.currentTimeMillis()<=endTime) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
return alarmsReceived.size();
}
}
| LGPL/CommonSoftware/ACSLaser/alarm-clients/test/alma/alarmsystem/clients/test/CategoryClientTest.java | A test for the CategoryClient
git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@84381 523d945c-050c-4681-91ec-863ad3bb968a
| LGPL/CommonSoftware/ACSLaser/alarm-clients/test/alma/alarmsystem/clients/test/CategoryClientTest.java | A test for the CategoryClient |
|
Java | unlicense | error: pathspec 'Son.java' did not match any file(s) known to git
| 0a1da51eb1ea290ec03a5675406660cb25725b7c | 1 | Ackincolor/GLAS | package Main.Model;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
import java.util.Vector;
import java.awt.geom.Line2D;
public class Son implements Runnable
{
private final int BUFL = 128000;
private File soundfile;
private AudioInputStream stream;
private AudioFormat format;
private SourceDataLine source;
private boolean play;
private boolean stop;
public Son(File f)
{
soundfile = f;
try
{
this.stream = AudioSystem.getAudioInputStream(soundfile);
this.format = stream.getFormat();
}
catch(Exception e)
{
System.out.println("Ce type de fichier n'est pas supporté.");
}
}
public Vector createWaveForm(Dimension d) {
byte[] audioBytes = null;
Vector lines = new Vector();
lines.removeAllElements(); // clear the old vector
//AudioFormat format = this.stream.getFormat();
if (audioBytes == null) {
try {
audioBytes = new byte[
(int) (this.stream.getFrameLength()
* this.format.getFrameSize())];
this.stream.read(audioBytes);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
//Dimension d = getSize();
int w = d.width;
int h = d.height-15;
int[] audioData = null;
int nb16=0,nb8=0;
if (format.getSampleSizeInBits() == 16) {
int longueurSample = audioBytes.length / 2;
System.out.println("longueur="+longueurSample);
audioData = new int[longueurSample];
if (format.isBigEndian()) {
for (int i = 0; i < longueurSample; i++) {
int MSB = (int) audioBytes[2*i];
int LSB = (int) audioBytes[2*i+1];
audioData[i] = MSB << 8 | (255 & LSB);
nb16++;
}
} else {
for (int i = 0; i < longueurSample; i++) {
int LSB = (int) audioBytes[2*i];
int MSB = (int) audioBytes[2*i+1];
audioData[i] = MSB << 8 | (255 & LSB);
nb16++;
}
}
} else if (format.getSampleSizeInBits() == 8) {
int longueurSample = audioBytes.length;
audioData = new int[longueurSample];
System.out.println("longueur"+longueurSample);
if (format.getEncoding().toString().startsWith("PCM_SIGN")) {
for (int i = 0; i < audioBytes.length; i++) {
audioData[i] = audioBytes[i];
nb8++;
}
} else {
for (int i = 0; i < audioBytes.length; i++) {
audioData[i] = audioBytes[i] - 128;
nb8++;
}
}
}else if (format.getSampleSizeInBits() == 24) {
int longueurSample = audioBytes.length / 3;
System.out.println("longueur"+longueurSample);
audioData = new int[longueurSample];
if (format.isBigEndian()) {
for (int i = 0; i < longueurSample; i++) {
int o1,o2,o3;
o3= audioBytes[3*i];
o2= audioBytes[3*i+1];
o1= audioBytes[3*i+2];
audioData[i] = o3<<16 | o2 << 8 |o1;
}
} else {
for (int i = 0; i < longueurSample; i++) {
int o1,o2,o3;
o3= audioBytes[3*i+2];
o2= audioBytes[3*i+1];
o1= audioBytes[3*i];
audioData[i] = o3<<16 | o2 << 8 |o1;
}
}
}
int frames_per_pixel = audioBytes.length / format.getFrameSize()/w;
byte my_byte = 0;
double y_last = 0,y_new=0;
int nbLine=0;
int numChannels = format.getChannels();
for (double x = 0; x < w && audioData != null; x++) {
int idx = (int) (frames_per_pixel * numChannels * x);
if (format.getSampleSizeInBits() == 8) {
my_byte = (byte) audioData[idx];
y_new = (double) (h * (128 - my_byte) / 256);
} else if(format.getSampleSizeInBits() == 16){
my_byte = (byte) (audioData[idx]>>8);
y_new = (double) (h * (128 - my_byte) / 256);
}
else
{
my_byte=(byte)(audioData[idx]>>16);
y_new = (double) (h * (128 - my_byte) / 256);
}
nbLine++;
lines.add(new Line2D.Double(x, y_last, x, y_new));
y_last = y_new;
}
System.out.println("nombre ligne = "+nbLine+" nb16="+nb16+" nb8="+nb8+" sampleSizeinBits="+format.getSampleSizeInBits());
return lines;
}
/*teste de lecture avec Clip*/
/*
public void run()
{
this.play = true;
this.stop = false;
try
{
Line.Info linfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(linfo);
Clip clip = (Clip) line;
//clip.addLineListener(this);
clip.open(this.stream);
clip.start();
}catch(LineUnavailableException e)
{
System.out.println("Line unavailable");
}catch(IOException e)
{
e.printStackTrace();
}
}*/
public void run()
{
this.play = true;
this.stop = false;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, this.format);
try
{
if(this.source != null)
{
this.source.close();
}
this.source = (SourceDataLine) AudioSystem.getLine(info);
this.source.open(format);
}
catch(LineUnavailableException e)
{
System.out.println("Line unavailable");
}
this.source.start();
int bytes = 0;
byte[] buf = new byte[BUFL];
while(bytes != -1 && this.play)
{
try
{
bytes = stream.read(buf, 0, buf.length);
}
catch(IOException e)
{
System.out.println("Problème de lecture!");
}
if(bytes >= 0)
{
int byteswritten = this.source.write(buf, 0, bytes);
System.out.println("envoie du flux");
}
}
if(stop)
{
this.source.drain();
}
}
public void arreterSon()
{
this.play = false;
this.stop = true;
}
public void pauseSon()
{
this.play = false;
this.stop = false;
}
}
| Son.java | Add files via upload
dessin de la courbe 8,16 et 24 bits | Son.java | Add files via upload |
|
Java | unlicense | error: pathspec 'src/main/java/gvlfm78/plugin/Hotels/tasks/HotelTask.java' did not match any file(s) known to git
| 3c7d3cb5683277c379463ecd26883dbed31f897b | 1 | gvlfm78/BukkitHotels | package kernitus.plugin.Hotels.tasks;
import java.io.File;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import kernitus.plugin.Hotels.Hotel;
import kernitus.plugin.Hotels.handlers.HotelsConfigHandler;
import kernitus.plugin.Hotels.managers.HotelsFileFinder;
import kernitus.plugin.Hotels.managers.Mes;
public class HotelTask extends BukkitRunnable{
@Override
public void run(){
//Hotel files
ArrayList<String> fileList = HotelsFileFinder.listFiles("plugins" + File.separator + "Hotels" + File.separator + "Hotels");
for(String fileName : fileList){
File file = HotelsConfigHandler.getFile("Hotels" + File.separator + fileName);
YamlConfiguration hconf = YamlConfiguration.loadConfiguration(file);
String buyeruuid = hconf.getString("Hotel.sell.buyer");
if(buyeruuid != null){
String hotelName = file.getName().replaceFirst(".yml", "");
Hotel hotel = new Hotel(hotelName);
//Messaging the buyer
OfflinePlayer buyer = Bukkit.getOfflinePlayer(UUID.fromString(buyeruuid));
if(buyer.isOnline()){
Player onlineBuyer = (Player) buyer;
onlineBuyer.sendMessage(Mes.mes("hotels.commands.buyhotel.expired").replaceAll("%hotel%", hotelName));
}
//Messaging the seller
for(UUID ownerUUID : hotel.getOwners().getUniqueIds()){
OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerUUID);
if(owner.isOnline()){
Player player = (Player) owner;
player.sendMessage(Mes.mes("hotels.commands.sellhotel.expired").replaceAll("%hotel%", hotelName));
}
}
hotel.setBuyer(null);
hotel.removePrice();
hotel.saveHotelConfig();
}
}
}
}
| src/main/java/gvlfm78/plugin/Hotels/tasks/HotelTask.java | Added HotelTask | src/main/java/gvlfm78/plugin/Hotels/tasks/HotelTask.java | Added HotelTask |
|
Java | apache-2.0 | 083f28a704c8e7d4438461bf0a26136a18ce8f5e | 0 | strapdata/elassandra5-rc,wangtuo/elasticsearch,IanvsPoplicola/elasticsearch,kaneshin/elasticsearch,myelin/elasticsearch,wuranbo/elasticsearch,avikurapati/elasticsearch,mjason3/elasticsearch,robin13/elasticsearch,kalimatas/elasticsearch,s1monw/elasticsearch,socialrank/elasticsearch,socialrank/elasticsearch,snikch/elasticsearch,C-Bish/elasticsearch,iacdingping/elasticsearch,Shepard1212/elasticsearch,qwerty4030/elasticsearch,MaineC/elasticsearch,mmaracic/elasticsearch,spiegela/elasticsearch,winstonewert/elasticsearch,JSCooke/elasticsearch,brandonkearby/elasticsearch,markwalkom/elasticsearch,rmuir/elasticsearch,LeoYao/elasticsearch,mapr/elasticsearch,Helen-Zhao/elasticsearch,awislowski/elasticsearch,jbertouch/elasticsearch,nezirus/elasticsearch,artnowo/elasticsearch,winstonewert/elasticsearch,obourgain/elasticsearch,andrestc/elasticsearch,ThiagoGarciaAlves/elasticsearch,rlugojr/elasticsearch,ZTE-PaaS/elasticsearch,rmuir/elasticsearch,liweinan0423/elasticsearch,davidvgalbraith/elasticsearch,naveenhooda2000/elasticsearch,sneivandt/elasticsearch,jprante/elasticsearch,dongjoon-hyun/elasticsearch,martinstuga/elasticsearch,vroyer/elasticassandra,pozhidaevak/elasticsearch,strapdata/elassandra5-rc,trangvh/elasticsearch,MaineC/elasticsearch,alexshadow007/elasticsearch,GlenRSmith/elasticsearch,maddin2016/elasticsearch,geidies/elasticsearch,nknize/elasticsearch,drewr/elasticsearch,schonfeld/elasticsearch,ricardocerq/elasticsearch,wenpos/elasticsearch,jprante/elasticsearch,nezirus/elasticsearch,iacdingping/elasticsearch,ThiagoGarciaAlves/elasticsearch,gfyoung/elasticsearch,qwerty4030/elasticsearch,dpursehouse/elasticsearch,AndreKR/elasticsearch,markwalkom/elasticsearch,Stacey-Gammon/elasticsearch,fforbeck/elasticsearch,wangtuo/elasticsearch,LeoYao/elasticsearch,dpursehouse/elasticsearch,fred84/elasticsearch,polyfractal/elasticsearch,mikemccand/elasticsearch,mjason3/elasticsearch,socialrank/elasticsearch,jimczi/elasticsearch,jimczi/elasticsearch,bawse/elasticsearch,nezirus/elasticsearch,martinstuga/elasticsearch,markharwood/elasticsearch,myelin/elasticsearch,andrestc/elasticsearch,robin13/elasticsearch,nomoa/elasticsearch,spiegela/elasticsearch,gfyoung/elasticsearch,obourgain/elasticsearch,JackyMai/elasticsearch,ZTE-PaaS/elasticsearch,trangvh/elasticsearch,palecur/elasticsearch,socialrank/elasticsearch,njlawton/elasticsearch,naveenhooda2000/elasticsearch,pozhidaevak/elasticsearch,a2lin/elasticsearch,mortonsykes/elasticsearch,Shepard1212/elasticsearch,yanjunh/elasticsearch,IanvsPoplicola/elasticsearch,bawse/elasticsearch,naveenhooda2000/elasticsearch,Stacey-Gammon/elasticsearch,JackyMai/elasticsearch,ricardocerq/elasticsearch,naveenhooda2000/elasticsearch,GlenRSmith/elasticsearch,StefanGor/elasticsearch,dongjoon-hyun/elasticsearch,Stacey-Gammon/elasticsearch,dpursehouse/elasticsearch,StefanGor/elasticsearch,LeoYao/elasticsearch,xuzha/elasticsearch,wbowling/elasticsearch,brandonkearby/elasticsearch,martinstuga/elasticsearch,avikurapati/elasticsearch,jpountz/elasticsearch,masaruh/elasticsearch,qwerty4030/elasticsearch,nomoa/elasticsearch,scorpionvicky/elasticsearch,camilojd/elasticsearch,andrejserafim/elasticsearch,mikemccand/elasticsearch,martinstuga/elasticsearch,robin13/elasticsearch,mohit/elasticsearch,vroyer/elasticassandra,rhoml/elasticsearch,kaneshin/elasticsearch,nomoa/elasticsearch,jpountz/elasticsearch,henakamaMSFT/elasticsearch,jchampion/elasticsearch,drewr/elasticsearch,maddin2016/elasticsearch,jchampion/elasticsearch,kaneshin/elasticsearch,jbertouch/elasticsearch,C-Bish/elasticsearch,vroyer/elassandra,PhaedrusTheGreek/elasticsearch,drewr/elasticsearch,F0lha/elasticsearch,davidvgalbraith/elasticsearch,palecur/elasticsearch,mmaracic/elasticsearch,ESamir/elasticsearch,bawse/elasticsearch,drewr/elasticsearch,MaineC/elasticsearch,polyfractal/elasticsearch,MaineC/elasticsearch,nilabhsagar/elasticsearch,tebriel/elasticsearch,trangvh/elasticsearch,ricardocerq/elasticsearch,LewayneNaidoo/elasticsearch,fforbeck/elasticsearch,mortonsykes/elasticsearch,ThiagoGarciaAlves/elasticsearch,umeshdangat/elasticsearch,Helen-Zhao/elasticsearch,JSCooke/elasticsearch,wbowling/elasticsearch,mmaracic/elasticsearch,andrejserafim/elasticsearch,cwurm/elasticsearch,polyfractal/elasticsearch,s1monw/elasticsearch,JervyShi/elasticsearch,wuranbo/elasticsearch,markwalkom/elasticsearch,AndreKR/elasticsearch,strapdata/elassandra5-rc,PhaedrusTheGreek/elasticsearch,IanvsPoplicola/elasticsearch,gmarz/elasticsearch,zkidkid/elasticsearch,nilabhsagar/elasticsearch,rajanm/elasticsearch,elasticdog/elasticsearch,episerver/elasticsearch,girirajsharma/elasticsearch,Stacey-Gammon/elasticsearch,rlugojr/elasticsearch,umeshdangat/elasticsearch,LeoYao/elasticsearch,schonfeld/elasticsearch,mjason3/elasticsearch,lks21c/elasticsearch,coding0011/elasticsearch,yynil/elasticsearch,pozhidaevak/elasticsearch,fforbeck/elasticsearch,LeoYao/elasticsearch,kaneshin/elasticsearch,henakamaMSFT/elasticsearch,cwurm/elasticsearch,glefloch/elasticsearch,schonfeld/elasticsearch,zkidkid/elasticsearch,diendt/elasticsearch,fernandozhu/elasticsearch,jpountz/elasticsearch,pozhidaevak/elasticsearch,sneivandt/elasticsearch,rmuir/elasticsearch,nazarewk/elasticsearch,C-Bish/elasticsearch,episerver/elasticsearch,strapdata/elassandra5-rc,JackyMai/elasticsearch,iacdingping/elasticsearch,rlugojr/elasticsearch,snikch/elasticsearch,kalimatas/elasticsearch,fernandozhu/elasticsearch,xuzha/elasticsearch,wuranbo/elasticsearch,jimczi/elasticsearch,geidies/elasticsearch,scottsom/elasticsearch,spiegela/elasticsearch,ricardocerq/elasticsearch,fforbeck/elasticsearch,rhoml/elasticsearch,maddin2016/elasticsearch,avikurapati/elasticsearch,andrejserafim/elasticsearch,jprante/elasticsearch,snikch/elasticsearch,F0lha/elasticsearch,winstonewert/elasticsearch,s1monw/elasticsearch,scorpionvicky/elasticsearch,s1monw/elasticsearch,iacdingping/elasticsearch,davidvgalbraith/elasticsearch,ivansun1010/elasticsearch,elasticdog/elasticsearch,MisterAndersen/elasticsearch,yanjunh/elasticsearch,winstonewert/elasticsearch,xuzha/elasticsearch,StefanGor/elasticsearch,jbertouch/elasticsearch,girirajsharma/elasticsearch,mohit/elasticsearch,markharwood/elasticsearch,schonfeld/elasticsearch,uschindler/elasticsearch,lks21c/elasticsearch,andrestc/elasticsearch,GlenRSmith/elasticsearch,i-am-Nathan/elasticsearch,cwurm/elasticsearch,vroyer/elasticassandra,vroyer/elassandra,LeoYao/elasticsearch,andrestc/elasticsearch,drewr/elasticsearch,brandonkearby/elasticsearch,markwalkom/elasticsearch,alexshadow007/elasticsearch,rajanm/elasticsearch,sneivandt/elasticsearch,episerver/elasticsearch,nknize/elasticsearch,qwerty4030/elasticsearch,liweinan0423/elasticsearch,markharwood/elasticsearch,nknize/elasticsearch,mapr/elasticsearch,gmarz/elasticsearch,gingerwizard/elasticsearch,fernandozhu/elasticsearch,rhoml/elasticsearch,i-am-Nathan/elasticsearch,JervyShi/elasticsearch,davidvgalbraith/elasticsearch,C-Bish/elasticsearch,JervyShi/elasticsearch,PhaedrusTheGreek/elasticsearch,ESamir/elasticsearch,dongjoon-hyun/elasticsearch,awislowski/elasticsearch,strapdata/elassandra,MisterAndersen/elasticsearch,camilojd/elasticsearch,bawse/elasticsearch,geidies/elasticsearch,gingerwizard/elasticsearch,dpursehouse/elasticsearch,jbertouch/elasticsearch,gmarz/elasticsearch,rajanm/elasticsearch,ivansun1010/elasticsearch,rmuir/elasticsearch,socialrank/elasticsearch,andrejserafim/elasticsearch,LeoYao/elasticsearch,shreejay/elasticsearch,njlawton/elasticsearch,fernandozhu/elasticsearch,coding0011/elasticsearch,shreejay/elasticsearch,rlugojr/elasticsearch,tebriel/elasticsearch,glefloch/elasticsearch,trangvh/elasticsearch,geidies/elasticsearch,F0lha/elasticsearch,mmaracic/elasticsearch,myelin/elasticsearch,socialrank/elasticsearch,socialrank/elasticsearch,HonzaKral/elasticsearch,scottsom/elasticsearch,yynil/elasticsearch,StefanGor/elasticsearch,palecur/elasticsearch,mapr/elasticsearch,lks21c/elasticsearch,ESamir/elasticsearch,JSCooke/elasticsearch,JervyShi/elasticsearch,wangtuo/elasticsearch,markwalkom/elasticsearch,scottsom/elasticsearch,uschindler/elasticsearch,coding0011/elasticsearch,liweinan0423/elasticsearch,mortonsykes/elasticsearch,F0lha/elasticsearch,xuzha/elasticsearch,alexshadow007/elasticsearch,myelin/elasticsearch,rmuir/elasticsearch,rlugojr/elasticsearch,cwurm/elasticsearch,elasticdog/elasticsearch,obourgain/elasticsearch,shreejay/elasticsearch,yynil/elasticsearch,rajanm/elasticsearch,clintongormley/elasticsearch,Helen-Zhao/elasticsearch,nomoa/elasticsearch,henakamaMSFT/elasticsearch,artnowo/elasticsearch,sreeramjayan/elasticsearch,mikemccand/elasticsearch,obourgain/elasticsearch,schonfeld/elasticsearch,ESamir/elasticsearch,ivansun1010/elasticsearch,polyfractal/elasticsearch,wbowling/elasticsearch,i-am-Nathan/elasticsearch,spiegela/elasticsearch,mohit/elasticsearch,jpountz/elasticsearch,strapdata/elassandra5-rc,episerver/elasticsearch,nknize/elasticsearch,wangtuo/elasticsearch,jprante/elasticsearch,MaineC/elasticsearch,HonzaKral/elasticsearch,wenpos/elasticsearch,schonfeld/elasticsearch,JackyMai/elasticsearch,masaruh/elasticsearch,ZTE-PaaS/elasticsearch,polyfractal/elasticsearch,dpursehouse/elasticsearch,mikemccand/elasticsearch,Shepard1212/elasticsearch,zkidkid/elasticsearch,andrestc/elasticsearch,wenpos/elasticsearch,wbowling/elasticsearch,PhaedrusTheGreek/elasticsearch,nezirus/elasticsearch,glefloch/elasticsearch,nazarewk/elasticsearch,jprante/elasticsearch,wbowling/elasticsearch,sneivandt/elasticsearch,rmuir/elasticsearch,JackyMai/elasticsearch,palecur/elasticsearch,myelin/elasticsearch,umeshdangat/elasticsearch,mapr/elasticsearch,MisterAndersen/elasticsearch,PhaedrusTheGreek/elasticsearch,diendt/elasticsearch,MisterAndersen/elasticsearch,gmarz/elasticsearch,strapdata/elassandra,Stacey-Gammon/elasticsearch,mapr/elasticsearch,liweinan0423/elasticsearch,brandonkearby/elasticsearch,JervyShi/elasticsearch,palecur/elasticsearch,clintongormley/elasticsearch,wenpos/elasticsearch,gmarz/elasticsearch,Shepard1212/elasticsearch,markharwood/elasticsearch,F0lha/elasticsearch,tebriel/elasticsearch,camilojd/elasticsearch,gfyoung/elasticsearch,mjason3/elasticsearch,IanvsPoplicola/elasticsearch,fred84/elasticsearch,jchampion/elasticsearch,a2lin/elasticsearch,uschindler/elasticsearch,rajanm/elasticsearch,dongjoon-hyun/elasticsearch,maddin2016/elasticsearch,winstonewert/elasticsearch,camilojd/elasticsearch,rhoml/elasticsearch,jchampion/elasticsearch,camilojd/elasticsearch,njlawton/elasticsearch,mmaracic/elasticsearch,awislowski/elasticsearch,sreeramjayan/elasticsearch,LewayneNaidoo/elasticsearch,alexshadow007/elasticsearch,scorpionvicky/elasticsearch,jpountz/elasticsearch,markharwood/elasticsearch,wuranbo/elasticsearch,nazarewk/elasticsearch,ThiagoGarciaAlves/elasticsearch,jbertouch/elasticsearch,masaruh/elasticsearch,diendt/elasticsearch,clintongormley/elasticsearch,i-am-Nathan/elasticsearch,GlenRSmith/elasticsearch,a2lin/elasticsearch,robin13/elasticsearch,fred84/elasticsearch,AndreKR/elasticsearch,geidies/elasticsearch,yynil/elasticsearch,girirajsharma/elasticsearch,gingerwizard/elasticsearch,wbowling/elasticsearch,HonzaKral/elasticsearch,sreeramjayan/elasticsearch,andrestc/elasticsearch,mmaracic/elasticsearch,LewayneNaidoo/elasticsearch,alexshadow007/elasticsearch,coding0011/elasticsearch,masaruh/elasticsearch,wenpos/elasticsearch,GlenRSmith/elasticsearch,wangtuo/elasticsearch,ZTE-PaaS/elasticsearch,xuzha/elasticsearch,rhoml/elasticsearch,henakamaMSFT/elasticsearch,artnowo/elasticsearch,spiegela/elasticsearch,kalimatas/elasticsearch,fernandozhu/elasticsearch,s1monw/elasticsearch,umeshdangat/elasticsearch,masaruh/elasticsearch,davidvgalbraith/elasticsearch,shreejay/elasticsearch,PhaedrusTheGreek/elasticsearch,qwerty4030/elasticsearch,avikurapati/elasticsearch,nazarewk/elasticsearch,martinstuga/elasticsearch,sneivandt/elasticsearch,snikch/elasticsearch,yynil/elasticsearch,gingerwizard/elasticsearch,iacdingping/elasticsearch,zkidkid/elasticsearch,jchampion/elasticsearch,ZTE-PaaS/elasticsearch,mikemccand/elasticsearch,clintongormley/elasticsearch,jchampion/elasticsearch,episerver/elasticsearch,diendt/elasticsearch,AndreKR/elasticsearch,gingerwizard/elasticsearch,ivansun1010/elasticsearch,cwurm/elasticsearch,wuranbo/elasticsearch,fforbeck/elasticsearch,martinstuga/elasticsearch,ivansun1010/elasticsearch,rajanm/elasticsearch,nomoa/elasticsearch,drewr/elasticsearch,nilabhsagar/elasticsearch,AndreKR/elasticsearch,gingerwizard/elasticsearch,mapr/elasticsearch,markwalkom/elasticsearch,iacdingping/elasticsearch,sreeramjayan/elasticsearch,girirajsharma/elasticsearch,lks21c/elasticsearch,scorpionvicky/elasticsearch,trangvh/elasticsearch,snikch/elasticsearch,Helen-Zhao/elasticsearch,mortonsykes/elasticsearch,lks21c/elasticsearch,iacdingping/elasticsearch,yynil/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,F0lha/elasticsearch,scorpionvicky/elasticsearch,xuzha/elasticsearch,elasticdog/elasticsearch,fred84/elasticsearch,tebriel/elasticsearch,drewr/elasticsearch,JSCooke/elasticsearch,IanvsPoplicola/elasticsearch,C-Bish/elasticsearch,nilabhsagar/elasticsearch,jimczi/elasticsearch,ricardocerq/elasticsearch,ThiagoGarciaAlves/elasticsearch,polyfractal/elasticsearch,avikurapati/elasticsearch,andrestc/elasticsearch,glefloch/elasticsearch,clintongormley/elasticsearch,liweinan0423/elasticsearch,girirajsharma/elasticsearch,kalimatas/elasticsearch,tebriel/elasticsearch,LewayneNaidoo/elasticsearch,uschindler/elasticsearch,andrejserafim/elasticsearch,jbertouch/elasticsearch,yanjunh/elasticsearch,gfyoung/elasticsearch,snikch/elasticsearch,yanjunh/elasticsearch,clintongormley/elasticsearch,umeshdangat/elasticsearch,markharwood/elasticsearch,jimczi/elasticsearch,gingerwizard/elasticsearch,fred84/elasticsearch,ESamir/elasticsearch,glefloch/elasticsearch,maddin2016/elasticsearch,kalimatas/elasticsearch,kaneshin/elasticsearch,diendt/elasticsearch,schonfeld/elasticsearch,scottsom/elasticsearch,strapdata/elassandra,obourgain/elasticsearch,nazarewk/elasticsearch,i-am-Nathan/elasticsearch,jpountz/elasticsearch,davidvgalbraith/elasticsearch,StefanGor/elasticsearch,MisterAndersen/elasticsearch,njlawton/elasticsearch,andrejserafim/elasticsearch,HonzaKral/elasticsearch,awislowski/elasticsearch,geidies/elasticsearch,brandonkearby/elasticsearch,mohit/elasticsearch,tebriel/elasticsearch,shreejay/elasticsearch,Shepard1212/elasticsearch,JSCooke/elasticsearch,nezirus/elasticsearch,wbowling/elasticsearch,naveenhooda2000/elasticsearch,scottsom/elasticsearch,robin13/elasticsearch,awislowski/elasticsearch,PhaedrusTheGreek/elasticsearch,mjason3/elasticsearch,artnowo/elasticsearch,vroyer/elassandra,artnowo/elasticsearch,ESamir/elasticsearch,sreeramjayan/elasticsearch,LewayneNaidoo/elasticsearch,nilabhsagar/elasticsearch,mortonsykes/elasticsearch,ivansun1010/elasticsearch,pozhidaevak/elasticsearch,yanjunh/elasticsearch,diendt/elasticsearch,sreeramjayan/elasticsearch,camilojd/elasticsearch,ThiagoGarciaAlves/elasticsearch,rhoml/elasticsearch,girirajsharma/elasticsearch,bawse/elasticsearch,henakamaMSFT/elasticsearch,dongjoon-hyun/elasticsearch,mohit/elasticsearch,njlawton/elasticsearch,elasticdog/elasticsearch,kaneshin/elasticsearch,AndreKR/elasticsearch,gfyoung/elasticsearch,strapdata/elassandra,zkidkid/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,JervyShi/elasticsearch,Helen-Zhao/elasticsearch,a2lin/elasticsearch,a2lin/elasticsearch | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import java.io.IOException;
public class QueryParseContext {
private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions");
private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys");
private XContentParser parser;
//norelease this flag is also used in the QueryShardContext, we need to make sure we set it there correctly in doToQuery()
private ParseFieldMatcher parseFieldMatcher = ParseFieldMatcher.EMPTY;
//norelease this can eventually be deleted when context() method goes away
private final QueryShardContext shardContext;
private IndicesQueriesRegistry indicesQueriesRegistry;
public QueryParseContext(IndicesQueriesRegistry registry) {
this.indicesQueriesRegistry = registry;
this.shardContext = null;
}
QueryParseContext(QueryShardContext context) {
this.shardContext = context;
this.indicesQueriesRegistry = context.indexQueryParserService().indicesQueriesRegistry();
}
public void reset(XContentParser jp) {
this.parseFieldMatcher = ParseFieldMatcher.EMPTY;
this.parser = jp;
if (parser != null) {
this.parser.setParseFieldMatcher(parseFieldMatcher);
}
}
//norelease this is still used in BaseQueryParserTemp and FunctionScoreQueryParser, remove if not needed there anymore
@Deprecated
public QueryShardContext shardContext() {
return this.shardContext;
}
public XContentParser parser() {
return this.parser;
}
public void parseFieldMatcher(ParseFieldMatcher parseFieldMatcher) {
if (parseFieldMatcher == null) {
throw new IllegalArgumentException("parseFieldMatcher must not be null");
}
this.parseFieldMatcher = parseFieldMatcher;
}
public boolean isDeprecatedSetting(String setting) {
return parseFieldMatcher.match(setting, CACHE) || parseFieldMatcher.match(setting, CACHE_KEY);
}
/**
* @deprecated replaced by calls to parseInnerFilterToQueryBuilder() for the resulting queries
*/
@Nullable
@Deprecated
//norelease should be possible to remove after refactoring all queries
public Query parseInnerFilter() throws QueryShardException, IOException {
assert this.shardContext != null;
QueryBuilder builder = parseInnerFilterToQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
}
return result;
}
/**
* @deprecated replaced by calls to parseInnerQueryBuilder() for the resulting queries
*/
@Nullable
@Deprecated
//norelease this method will be removed once all queries are refactored
public Query parseInnerQuery() throws IOException, QueryShardException {
QueryBuilder builder = parseInnerQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
}
return result;
}
/**
* @return a new QueryBuilder based on the current state of the parser
*/
public QueryBuilder parseInnerQueryBuilder() throws IOException {
// move to START object
XContentParser.Token token;
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object");
}
}
token = parser.nextToken();
if (token == XContentParser.Token.END_OBJECT) {
// empty query
return EmptyQueryBuilder.PROTOTYPE;
}
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
String queryName = parser.currentName();
// move to the next START_OBJECT
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT && token != XContentParser.Token.START_ARRAY) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
QueryParser queryParser = queryParser(queryName);
if (queryParser == null) {
throw new ParsingException(parser.getTokenLocation(), "No query registered for [" + queryName + "]");
}
QueryBuilder result = queryParser.fromXContent(this);
if (parser.currentToken() == XContentParser.Token.END_OBJECT || parser.currentToken() == XContentParser.Token.END_ARRAY) {
// if we are at END_OBJECT, move to the next one...
parser.nextToken();
}
return result;
}
/**
* @return a new QueryBuilder based on the current state of the parser, but does so that the inner query
* is parsed to a filter
*/
//norelease setting and checking the isFilter Flag should completely be moved to toQuery/toFilter after query refactoring
public QueryBuilder parseInnerFilterToQueryBuilder() throws IOException {
final boolean originalIsFilter = this.shardContext.isFilter;
try {
this.shardContext.isFilter = true;
return parseInnerQueryBuilder();
} finally {
this.shardContext.isFilter = originalIsFilter;
}
}
//norelease setting and checking the isFilter Flag should completely be moved to toQuery/toFilter after query refactoring
public QueryBuilder parseInnerFilterToQueryBuilder(String queryName) throws IOException {
final boolean originalIsFilter = this.shardContext.isFilter;
try {
this.shardContext.isFilter = true;
QueryParser queryParser = queryParser(queryName);
if (queryParser == null) {
throw new ParsingException(parser.getTokenLocation(), "No query registered for [" + queryName + "]");
}
return queryParser.fromXContent(this);
} finally {
this.shardContext.isFilter = originalIsFilter;
}
}
public ParseFieldMatcher parseFieldMatcher() {
return parseFieldMatcher;
}
public void parser(XContentParser innerParser) {
this.parser = innerParser;
}
QueryParser queryParser(String name) {
return indicesQueriesRegistry.queryParsers().get(name);
}
}
| core/src/main/java/org/elasticsearch/index/query/QueryParseContext.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import java.io.IOException;
public class QueryParseContext {
private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions");
private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys");
private XContentParser parser;
//norelease this flag is also used in the QueryShardContext, we need to make sure we set it there correctly in doToQuery()
private ParseFieldMatcher parseFieldMatcher = ParseFieldMatcher.EMPTY;
//norelease this can eventually be deleted when context() method goes away
private final QueryShardContext shardContext;
private IndicesQueriesRegistry indicesQueriesRegistry;
public QueryParseContext(IndicesQueriesRegistry registry) {
this(null, registry); // NOCOMMIT - remove index
}
public QueryParseContext(Index index, IndicesQueriesRegistry registry) {
this.indicesQueriesRegistry = registry;
this.shardContext = null;
}
QueryParseContext(QueryShardContext context) {
this.shardContext = context;
this.indicesQueriesRegistry = context.indexQueryParserService().indicesQueriesRegistry();
}
public void reset(XContentParser jp) {
this.parseFieldMatcher = ParseFieldMatcher.EMPTY;
this.parser = jp;
if (parser != null) {
this.parser.setParseFieldMatcher(parseFieldMatcher);
}
}
//norelease this is still used in BaseQueryParserTemp and FunctionScoreQueryParser, remove if not needed there anymore
@Deprecated
public QueryShardContext shardContext() {
return this.shardContext;
}
public XContentParser parser() {
return this.parser;
}
public void parseFieldMatcher(ParseFieldMatcher parseFieldMatcher) {
if (parseFieldMatcher == null) {
throw new IllegalArgumentException("parseFieldMatcher must not be null");
}
this.parseFieldMatcher = parseFieldMatcher;
}
public boolean isDeprecatedSetting(String setting) {
return parseFieldMatcher.match(setting, CACHE) || parseFieldMatcher.match(setting, CACHE_KEY);
}
/**
* @deprecated replaced by calls to parseInnerFilterToQueryBuilder() for the resulting queries
*/
@Nullable
@Deprecated
//norelease should be possible to remove after refactoring all queries
public Query parseInnerFilter() throws QueryShardException, IOException {
assert this.shardContext != null;
QueryBuilder builder = parseInnerFilterToQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
}
return result;
}
/**
* @deprecated replaced by calls to parseInnerQueryBuilder() for the resulting queries
*/
@Nullable
@Deprecated
//norelease this method will be removed once all queries are refactored
public Query parseInnerQuery() throws IOException, QueryShardException {
QueryBuilder builder = parseInnerQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
}
return result;
}
/**
* @return a new QueryBuilder based on the current state of the parser
*/
public QueryBuilder parseInnerQueryBuilder() throws IOException {
// move to START object
XContentParser.Token token;
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object");
}
}
token = parser.nextToken();
if (token == XContentParser.Token.END_OBJECT) {
// empty query
return EmptyQueryBuilder.PROTOTYPE;
}
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
String queryName = parser.currentName();
// move to the next START_OBJECT
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT && token != XContentParser.Token.START_ARRAY) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
QueryParser queryParser = queryParser(queryName);
if (queryParser == null) {
throw new ParsingException(parser.getTokenLocation(), "No query registered for [" + queryName + "]");
}
QueryBuilder result = queryParser.fromXContent(this);
if (parser.currentToken() == XContentParser.Token.END_OBJECT || parser.currentToken() == XContentParser.Token.END_ARRAY) {
// if we are at END_OBJECT, move to the next one...
parser.nextToken();
}
return result;
}
/**
* @return a new QueryBuilder based on the current state of the parser, but does so that the inner query
* is parsed to a filter
*/
//norelease setting and checking the isFilter Flag should completely be moved to toQuery/toFilter after query refactoring
public QueryBuilder parseInnerFilterToQueryBuilder() throws IOException {
final boolean originalIsFilter = this.shardContext.isFilter;
try {
this.shardContext.isFilter = true;
return parseInnerQueryBuilder();
} finally {
this.shardContext.isFilter = originalIsFilter;
}
}
//norelease setting and checking the isFilter Flag should completely be moved to toQuery/toFilter after query refactoring
public QueryBuilder parseInnerFilterToQueryBuilder(String queryName) throws IOException {
final boolean originalIsFilter = this.shardContext.isFilter;
try {
this.shardContext.isFilter = true;
QueryParser queryParser = queryParser(queryName);
if (queryParser == null) {
throw new ParsingException(parser.getTokenLocation(), "No query registered for [" + queryName + "]");
}
return queryParser.fromXContent(this);
} finally {
this.shardContext.isFilter = originalIsFilter;
}
}
public ParseFieldMatcher parseFieldMatcher() {
return parseFieldMatcher;
}
public void parser(XContentParser innerParser) {
this.parser = innerParser;
}
QueryParser queryParser(String name) {
return indicesQueriesRegistry.queryParsers().get(name);
}
}
| remove index from QueryParseContext Constructor
| core/src/main/java/org/elasticsearch/index/query/QueryParseContext.java | remove index from QueryParseContext Constructor |
|
Java | apache-2.0 | 1c70210a1a32b1d908ae8029f066253cd869e97a | 0 | semonte/intellij-community,robovm/robovm-studio,fnouama/intellij-community,caot/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,allotria/intellij-community,apixandru/intellij-community,adedayo/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,apixandru/intellij-community,consulo/consulo,kool79/intellij-community,slisson/intellij-community,samthor/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,ernestp/consulo,ol-loginov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,consulo/consulo,holmes/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,semonte/intellij-community,da1z/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,signed/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,signed/intellij-community,FHannes/intellij-community,holmes/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,da1z/intellij-community,petteyg/intellij-community,dslomov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,samthor/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,petteyg/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,clumsy/intellij-community,izonder/intellij-community,akosyakov/intellij-community,da1z/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,diorcety/intellij-community,kdwink/intellij-community,caot/intellij-community,supersven/intellij-community,retomerz/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,kool79/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,amith01994/intellij-community,supersven/intellij-community,xfournet/intellij-community,xfournet/intellij-community,amith01994/intellij-community,asedunov/intellij-community,kool79/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,izonder/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,ibinti/intellij-community,izonder/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,petteyg/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,kool79/intellij-community,ibinti/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,kool79/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,hurricup/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,supersven/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,holmes/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,izonder/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,caot/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,amith01994/intellij-community,izonder/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,ernestp/consulo,joewalnes/idea-community,nicolargo/intellij-community,kool79/intellij-community,petteyg/intellij-community,ryano144/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,semonte/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,adedayo/intellij-community,amith01994/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,izonder/intellij-community,ryano144/intellij-community,robovm/robovm-studio,robovm/robovm-studio,salguarnieri/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,caot/intellij-community,robovm/robovm-studio,dslomov/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,caot/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,kdwink/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,ernestp/consulo,amith01994/intellij-community,amith01994/intellij-community,da1z/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ibinti/intellij-community,xfournet/intellij-community,jagguli/intellij-community,holmes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,vladmm/intellij-community,da1z/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,signed/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,allotria/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,robovm/robovm-studio,clumsy/intellij-community,supersven/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,joewalnes/idea-community,adedayo/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ernestp/consulo,TangHao1987/intellij-community,signed/intellij-community,ryano144/intellij-community,izonder/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,semonte/intellij-community,samthor/intellij-community,orekyuu/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,amith01994/intellij-community,caot/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,blademainer/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,samthor/intellij-community,kdwink/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,joewalnes/idea-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ibinti/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,slisson/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,blademainer/intellij-community,amith01994/intellij-community,blademainer/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,retomerz/intellij-community,jagguli/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,gnuhub/intellij-community,supersven/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,diorcety/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,izonder/intellij-community,hurricup/intellij-community,semonte/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,signed/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,signed/intellij-community,akosyakov/intellij-community,signed/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ernestp/consulo,da1z/intellij-community,suncycheng/intellij-community,caot/intellij-community,allotria/intellij-community,ryano144/intellij-community,slisson/intellij-community,wreckJ/intellij-community,kool79/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,signed/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,slisson/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,xfournet/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,jagguli/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,samthor/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,joewalnes/idea-community,semonte/intellij-community,caot/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,allotria/intellij-community,vladmm/intellij-community,robovm/robovm-studio,holmes/intellij-community,izonder/intellij-community,consulo/consulo,muntasirsyed/intellij-community,robovm/robovm-studio,samthor/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,hurricup/intellij-community,slisson/intellij-community,xfournet/intellij-community,samthor/intellij-community,clumsy/intellij-community,allotria/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,consulo/consulo,hurricup/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,signed/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,signed/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,diorcety/intellij-community,ibinti/intellij-community,retomerz/intellij-community,semonte/intellij-community,retomerz/intellij-community,allotria/intellij-community,ahb0327/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,robovm/robovm-studio,da1z/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.treeView;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.ui.LoadingNode;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Time;
import com.intellij.util.concurrency.WorkerThread;
import com.intellij.util.containers.HashSet;
import com.intellij.util.enumeration.EnumerationCopy;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.security.AccessControlException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
public class AbstractTreeUi {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.treeView.AbstractTreeBuilder");
protected JTree myTree;// protected for TestNG
@SuppressWarnings({"WeakerAccess"}) protected DefaultTreeModel myTreeModel;
private AbstractTreeStructure myTreeStructure;
private AbstractTreeUpdater myUpdater;
private Comparator<NodeDescriptor> myNodeDescriptorComparator;
private final Comparator<TreeNode> myNodeComparator = new Comparator<TreeNode>() {
public int compare(TreeNode n1, TreeNode n2) {
if (isLoadingNode(n1) || isLoadingNode(n2)) return 0;
NodeDescriptor nodeDescriptor1 = getDescriptorFrom(((DefaultMutableTreeNode)n1));
NodeDescriptor nodeDescriptor2 = getDescriptorFrom(((DefaultMutableTreeNode)n2));
return myNodeDescriptorComparator != null
? myNodeDescriptorComparator.compare(nodeDescriptor1, nodeDescriptor2)
: nodeDescriptor1.getIndex() - nodeDescriptor2.getIndex();
}
};
long myOwnComparatorStamp;
long myLastComparatorStamp;
private DefaultMutableTreeNode myRootNode;
private final HashMap<Object, Object> myElementToNodeMap = new HashMap<Object, Object>();
private final HashSet<DefaultMutableTreeNode> myUnbuiltNodes = new HashSet<DefaultMutableTreeNode>();
private TreeExpansionListener myExpansionListener;
private MySelectionListener mySelectionListener;
private WorkerThread myWorker = null;
private final Set<Runnable> myActiveWorkerTasks = new HashSet<Runnable>();
private ProgressIndicator myProgress;
private static final int WAIT_CURSOR_DELAY = 100;
private AbstractTreeNode<Object> TREE_NODE_WRAPPER;
private boolean myRootNodeWasInitialized = false;
private final Map<Object, List<NodeAction>> myNodeActions = new HashMap<Object, List<NodeAction>>();
private boolean myUpdateFromRootRequested;
private boolean myWasEverShown;
private boolean myUpdateIfInactive;
private final Map<Object, UpdateInfo> myLoadedInBackground = new HashMap<Object, UpdateInfo>();
private final Map<Object, List<NodeAction>> myNodeChildrenActions = new HashMap<Object, List<NodeAction>>();
private long myClearOnHideDelay = -1;
private final Map<AbstractTreeUi, Long> ourUi2Countdown = Collections.synchronizedMap(new WeakHashMap<AbstractTreeUi, Long>());
private final Set<Runnable> myDeferredSelections = new HashSet<Runnable>();
private final Set<Runnable> myDeferredExpansions = new HashSet<Runnable>();
private boolean myCanProcessDeferredSelections;
private UpdaterTreeState myUpdaterState;
private AbstractTreeBuilder myBuilder;
private boolean myReleaseRequested;
private final Set<DefaultMutableTreeNode> myUpdatingChildren = new HashSet<DefaultMutableTreeNode>();
private long myJanitorPollPeriod = Time.SECOND * 10;
private boolean myCheckStructure = false;
private boolean myCanYield = false;
private final List<TreeUpdatePass> myYeildingPasses = new ArrayList<TreeUpdatePass>();
private boolean myYeildingNow;
private final Set<DefaultMutableTreeNode> myPendingNodeActions = new HashSet<DefaultMutableTreeNode>();
private final Set<Runnable> myYeildingDoneRunnables = new HashSet<Runnable>();
private final Alarm myBusyAlarm = new Alarm();
private final Runnable myWaiterForReady = new Runnable() {
public void run() {
maybeSetBusyAndScheduleWaiterForReady(false);
}
};
private final RegistryValue myYeildingUpdate = Registry.get("ide.tree.yeildingUiUpdate");
private final RegistryValue myShowBusyIndicator = Registry.get("ide.tree.showBusyIndicator");
private final RegistryValue myWaitForReadyTime = Registry.get("ide.tree.waitForReadyTimout");
private boolean myWasEverIndexNotReady;
private boolean myShowing;
private FocusAdapter myFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
maybeReady();
}
};
private Set<DefaultMutableTreeNode> myNotForSmartExpand = new HashSet<DefaultMutableTreeNode>();
private TreePath myRequestedExpand;
private ActionCallback myInitialized = new ActionCallback();
private Map<Object, ActionCallback> myReadyCallbacks = new WeakHashMap<Object, ActionCallback>();
private boolean myPassthroughMode = false;
private Set<Object> myAutoExpandRoots = new HashSet<Object>();
private final RegistryValue myAutoExpandDepth = Registry.get("ide.tree.autoExpandMaxDepth");
private Set<DefaultMutableTreeNode> myWillBeExpaned = new HashSet<DefaultMutableTreeNode>();
private SimpleTimerTask myCleanupTask;
protected void init(AbstractTreeBuilder builder,
JTree tree,
DefaultTreeModel treeModel,
AbstractTreeStructure treeStructure,
@Nullable Comparator<NodeDescriptor> comparator,
boolean updateIfInactive) {
myBuilder = builder;
myTree = tree;
myTreeModel = treeModel;
addModelListenerToDianoseAccessOutsideEdt();
TREE_NODE_WRAPPER = getBuilder().createSearchingTreeNodeWrapper();
myTree.setModel(myTreeModel);
setRootNode((DefaultMutableTreeNode)treeModel.getRoot());
setTreeStructure(treeStructure);
myNodeDescriptorComparator = comparator;
myUpdateIfInactive = updateIfInactive;
myExpansionListener = new MyExpansionListener();
myTree.addTreeExpansionListener(myExpansionListener);
mySelectionListener = new MySelectionListener();
myTree.addTreeSelectionListener(mySelectionListener);
setUpdater(getBuilder().createUpdater());
myProgress = getBuilder().createProgressIndicator();
Disposer.register(getBuilder(), getUpdater());
final UiNotifyConnector uiNotify = new UiNotifyConnector(tree, new Activatable() {
public void showNotify() {
myShowing = true;
myWasEverShown = true;
if (!isReleaseRequested()) {
activate(true);
}
}
public void hideNotify() {
myShowing = false;
if (!validateReleaseRequested()) {
deactivate();
}
}
});
Disposer.register(getBuilder(), uiNotify);
myTree.addFocusListener(myFocusListener);
}
boolean isNodeActionsPending() {
return !myNodeActions.isEmpty() || !myNodeChildrenActions.isEmpty();
}
private void clearNodeActions() {
myNodeActions.clear();
myNodeChildrenActions.clear();
}
private void maybeSetBusyAndScheduleWaiterForReady(boolean forcedBusy) {
if (!myShowBusyIndicator.asBoolean() || !canYield()) return;
if (myTree instanceof com.intellij.ui.treeStructure.Tree) {
final com.intellij.ui.treeStructure.Tree tree = (Tree)myTree;
final boolean isBusy = !isReady() || forcedBusy;
if (isBusy && tree.isShowing()) {
tree.setPaintBusy(true);
myBusyAlarm.cancelAllRequests();
myBusyAlarm.addRequest(myWaiterForReady, myWaitForReadyTime.asInteger());
}
else {
tree.setPaintBusy(false);
}
}
}
private void cleanUpAll() {
final long now = System.currentTimeMillis();
final AbstractTreeUi[] uis = ourUi2Countdown.keySet().toArray(new AbstractTreeUi[ourUi2Countdown.size()]);
for (AbstractTreeUi eachUi : uis) {
if (eachUi == null) continue;
final Long timeToCleanup = ourUi2Countdown.get(eachUi);
if (timeToCleanup == null) continue;
if (now >= timeToCleanup.longValue()) {
ourUi2Countdown.remove(eachUi);
Runnable runnable = new Runnable() {
public void run() {
myCleanupTask = null;
getBuilder().cleanUp();
}
};
if (isPassthroughMode()) {
runnable.run();
} else {
UIUtil.invokeAndWaitIfNeeded(runnable);
}
}
}
}
protected void doCleanUp() {
Runnable cleanup = new Runnable() {
public void run() {
if (!isReleaseRequested()) {
cleanUpNow();
}
}
};
if (isPassthroughMode()) {
cleanup.run();
} else {
UIUtil.invokeLaterIfNeeded(cleanup);
}
}
private ActionCallback invokeLaterIfNeeded(@NotNull final Runnable runnable) {
final ActionCallback result = new ActionCallback();
Runnable actual = new Runnable() {
public void run() {
runnable.run();
result.setDone();
}
};
if (isPassthroughMode() || (!isEdt() && !isTreeShowing())) {
actual.run();
} else {
UIUtil.invokeLaterIfNeeded(actual);
}
return result;
}
public void activate(boolean byShowing) {
cancelCurrentCleanupTask();
myCanProcessDeferredSelections = true;
ourUi2Countdown.remove(this);
if (!myWasEverShown || myUpdateFromRootRequested || myUpdateIfInactive) {
getBuilder().updateFromRoot();
}
getUpdater().showNotify();
myWasEverShown |= byShowing;
}
private void cancelCurrentCleanupTask() {
if (myCleanupTask != null) {
myCleanupTask.cancel();
myCleanupTask = null;
}
}
public void deactivate() {
getUpdater().hideNotify();
myBusyAlarm.cancelAllRequests();
if (!myWasEverShown) return;
if (isNodeActionsPending()) {
cancelBackgroundLoading();
myUpdateFromRootRequested = true;
}
if (getClearOnHideDelay() >= 0) {
ourUi2Countdown.put(this, System.currentTimeMillis() + getClearOnHideDelay());
sheduleCleanUpAll();
}
}
private void sheduleCleanUpAll() {
cancelCurrentCleanupTask();
myCleanupTask = SimpleTimer.getInstance().setUp(new Runnable() {
public void run() {
cleanUpAll();
}
}, getClearOnHideDelay());
}
public void requestRelease() {
if (isReleaseRequested()) return;
assertIsDispatchThread();
myReleaseRequested = true;
getUpdater().requestRelease();
maybeReady();
}
private void releaseNow() {
myTree.removeTreeExpansionListener(myExpansionListener);
myTree.removeTreeSelectionListener(mySelectionListener);
myTree.removeFocusListener(myFocusListener);
disposeNode(getRootNode());
myElementToNodeMap.clear();
getUpdater().cancelAllRequests();
if (myWorker != null) {
myWorker.dispose(true);
clearWorkerTasks();
}
TREE_NODE_WRAPPER.setValue(null);
if (myProgress != null) {
myProgress.cancel();
}
cancelCurrentCleanupTask();
myTree = null;
setUpdater(null);
myWorker = null;
myTreeStructure = null;
myBuilder.releaseUi();
myBuilder = null;
clearNodeActions();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myYeildingDoneRunnables.clear();
}
public boolean isReleaseRequested() {
return myReleaseRequested;
}
public boolean validateReleaseRequested() {
if (isReleaseRequested()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
maybeReady();
}
});
return true;
} else {
return false;
}
}
public boolean isReleased() {
return myBuilder == null;
}
protected void doExpandNodeChildren(final DefaultMutableTreeNode node) {
if (!myUnbuiltNodes.contains(node)) return;
if (isLoadedInBackground(getElementFor(node))) return;
if (!isReleaseRequested()) {
getTreeStructure().commit();
addSubtreeToUpdate(node);
getUpdater().performUpdate();
} else {
processNodeActionsIfReady(node);
}
}
public final AbstractTreeStructure getTreeStructure() {
return myTreeStructure;
}
public final JTree getTree() {
return myTree;
}
@Nullable
private NodeDescriptor getDescriptorFrom(DefaultMutableTreeNode node) {
return (NodeDescriptor)node.getUserObject();
}
@Nullable
public final DefaultMutableTreeNode getNodeForElement(Object element, final boolean validateAgainstStructure) {
DefaultMutableTreeNode result = null;
if (validateAgainstStructure) {
int index = 0;
while (true) {
final DefaultMutableTreeNode node = findNode(element, index);
if (node == null) break;
if (isNodeValidForElement(element, node)) {
result = node;
break;
}
index++;
}
}
else {
result = getFirstNode(element);
}
if (result != null && !isNodeInStructure(result)) {
disposeNode(result);
result = null;
}
return result;
}
private boolean isNodeInStructure(DefaultMutableTreeNode node) {
return TreeUtil.isAncestor(getRootNode(), node) && getRootNode() == myTreeModel.getRoot();
}
private boolean isNodeValidForElement(final Object element, final DefaultMutableTreeNode node) {
return isSameHierarchy(element, node) || isValidChildOfParent(element, node);
}
private boolean isValidChildOfParent(final Object element, final DefaultMutableTreeNode node) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
final Object parentElement = getElementFor(parent);
if (!isInStructure(parentElement)) return false;
if (parent instanceof ElementNode) {
return ((ElementNode)parent).isValidChild(element);
}
else {
for (int i = 0; i < parent.getChildCount(); i++) {
final TreeNode child = parent.getChildAt(i);
final Object eachElement = getElementFor(child);
if (element.equals(eachElement)) return true;
}
}
return false;
}
private boolean isSameHierarchy(Object eachParent, DefaultMutableTreeNode eachParentNode) {
boolean valid = true;
while (true) {
if (eachParent == null) {
valid = eachParentNode == null;
break;
}
if (!eachParent.equals(getElementFor(eachParentNode))) {
valid = false;
break;
}
eachParent = getTreeStructure().getParentElement(eachParent);
eachParentNode = (DefaultMutableTreeNode)eachParentNode.getParent();
}
return valid;
}
public final DefaultMutableTreeNode getNodeForPath(Object[] path) {
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node == null) {
break;
}
}
return node;
}
public final void buildNodeForElement(Object element) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null) {
final java.util.List<Object> elements = new ArrayList<Object>();
while (true) {
element = getTreeStructure().getParentElement(element);
if (element == null) {
break;
}
elements.add(0, element);
}
for (final Object element1 : elements) {
node = getNodeForElement(element1, false);
if (node != null) {
expand(node, true);
}
}
}
}
public final void buildNodeForPath(Object[] path) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node != null && node != path[path.length - 1]) {
expand(node, true);
}
}
}
public final void setNodeDescriptorComparator(Comparator<NodeDescriptor> nodeDescriptorComparator) {
myNodeDescriptorComparator = nodeDescriptorComparator;
myLastComparatorStamp = -1;
getBuilder().queueUpdateFrom(getTreeStructure().getRootElement(), true);
}
protected AbstractTreeBuilder getBuilder() {
return myBuilder;
}
protected final void initRootNode() {
if (myUpdateIfInactive) {
activate(false);
}
else {
myUpdateFromRootRequested = true;
}
}
private boolean initRootNodeNowIfNeeded(final TreeUpdatePass pass) {
boolean wasCleanedUp = false;
if (myRootNodeWasInitialized) {
Object root = getTreeStructure().getRootElement();
assert root != null : "Root element cannot be null";
Object currentRoot = getElementFor(myRootNode);
if (Comparing.equal(root, currentRoot)) return false;
Object rootAgain = getTreeStructure().getRootElement();
if (root != rootAgain && !root.equals(rootAgain)) {
assert false : "getRootElement() if called twice must return either root1 == root2 or root1.equals(root2)";
}
cleanUpNow();
wasCleanedUp = true;
}
myRootNodeWasInitialized = true;
final Object rootElement = getTreeStructure().getRootElement();
addNodeAction(rootElement, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
processDeferredActions();
}
}, false);
final Ref<NodeDescriptor> rootDescriptor = new Ref<NodeDescriptor>(null);
final boolean bgLoading = getTreeStructure().isToBuildChildrenInBackground(rootElement);
Runnable build = new Runnable() {
public void run() {
rootDescriptor.set(getTreeStructure().createDescriptor(rootElement, null));
getRootNode().setUserObject(rootDescriptor.get());
update(rootDescriptor.get(), true);
}
};
Runnable update = new Runnable() {
public void run() {
if (getElementFromDescriptor(rootDescriptor.get()) != null) {
createMapping(getElementFromDescriptor(rootDescriptor.get()), getRootNode());
}
insertLoadingNode(getRootNode(), true);
boolean willUpdate = false;
if (isAutoExpand(rootDescriptor.get())) {
willUpdate = myUnbuiltNodes.contains(getRootNode());
expand(getRootNode(), true);
}
if (!willUpdate) {
updateNodeChildren(getRootNode(), pass, null, false, false, false, true);
}
if (getRootNode().getChildCount() == 0) {
myTreeModel.nodeChanged(getRootNode());
}
}
};
if (bgLoading) {
queueToBackground(build, update);
}
else {
build.run();
update.run();
}
return wasCleanedUp;
}
private boolean isAutoExpand(NodeDescriptor descriptor) {
return isAutoExpand(descriptor, true);
}
private boolean isAutoExpand(NodeDescriptor descriptor, boolean validate) {
if (descriptor == null) return false;
boolean autoExpand = getBuilder().isAutoExpandNode(descriptor);
Object element = getElementFromDescriptor(descriptor);
if (validate) {
autoExpand = validateAutoExpand(autoExpand, element);
}
if (!autoExpand && !myTree.isRootVisible()) {
if (element != null && element.equals(getTreeStructure().getRootElement())) return true;
}
return autoExpand;
}
private boolean validateAutoExpand(boolean autoExpand, Object element) {
if (autoExpand) {
int distance = getDistanceToAutoExpandRoot(element);
if (distance < 0) {
myAutoExpandRoots.add(element);
} else {
if (distance >= myAutoExpandDepth.asInteger() - 1) {
autoExpand = false;
}
}
if (autoExpand) {
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (isInVisibleAutoExpandChain(node)) {
autoExpand = true;
} else {
autoExpand = false;
}
}
}
return autoExpand;
}
private boolean isInVisibleAutoExpandChain(DefaultMutableTreeNode child) {
TreeNode eachParent = child;
while (eachParent != null) {
if (myRootNode == eachParent) return true;
NodeDescriptor eachDescriptor = getDescriptorFrom((DefaultMutableTreeNode)eachParent);
if (!isAutoExpand(eachDescriptor, false)) {
TreePath path = getPathFor(eachParent);
if (myWillBeExpaned.contains(path.getLastPathComponent()) || (myTree.isExpanded(path) && myTree.isVisible(path))) {
return true;
} else {
return false;
}
}
eachParent = eachParent.getParent();
}
return false;
}
private int getDistanceToAutoExpandRoot(Object element) {
int distance = 0;
Object eachParent = element;
while (eachParent != null) {
if (myAutoExpandRoots.contains(eachParent)) break;
eachParent = getTreeStructure().getParentElement(eachParent);
distance++;
}
return eachParent != null ? distance : -1;
}
private boolean isAutoExpand(DefaultMutableTreeNode node) {
return isAutoExpand(getDescriptorFrom(node));
}
private AsyncResult<Boolean> update(final NodeDescriptor nodeDescriptor, boolean now) {
final AsyncResult<Boolean> result = new AsyncResult<Boolean>();
if (now || isPassthroughMode()) {
return new AsyncResult<Boolean>().setDone(_update(nodeDescriptor));
}
Object element = getElementFromDescriptor(nodeDescriptor);
boolean bgLoading = getTreeStructure().isToBuildChildrenInBackground(element);
boolean edt = isEdt();
if (bgLoading) {
if (edt) {
final Ref<Boolean> changes = new Ref<Boolean>(false);
queueToBackground(new Runnable() {
public void run() {
changes.set(_update(nodeDescriptor));
}
}, new Runnable() {
public void run() {
result.setDone(changes.get());
}
});
}
else {
result.setDone(_update(nodeDescriptor));
}
}
else {
if (edt || !myWasEverShown) {
result.setDone(_update(nodeDescriptor));
}
else {
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
if (!validateReleaseRequested()) {
result.setDone(_update(nodeDescriptor));
}
else {
result.setRejected();
}
}
});
}
}
result.doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
if (changes) {
final long updateStamp = nodeDescriptor.getUpdateCount();
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
Object element = nodeDescriptor.getElement();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
TreePath path = getPathFor(node);
if (path != null && myTree.isVisible(path)) {
updateNodeImageAndPosition(node, false);
}
}
}
});
}
}
});
return result;
}
private boolean _update(NodeDescriptor nodeDescriptor) {
try {
nodeDescriptor.setUpdateCount(nodeDescriptor.getUpdateCount() + 1);
return getBuilder().updateNodeDescriptor(nodeDescriptor);
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady();
return false;
}
}
private void assertIsDispatchThread() {
if (isPassthroughMode()) return;
if (isTreeShowing() && !isEdt()) {
LOG.error("Must be in event-dispatch thread");
}
}
private boolean isEdt() {
return SwingUtilities.isEventDispatchThread();
}
private boolean isTreeShowing() {
return myShowing;
}
private void assertNotDispatchThread() {
if (isPassthroughMode()) return;
if (isEdt()) {
LOG.error("Must not be in event-dispatch thread");
}
}
private void processDeferredActions() {
processDeferredActions(myDeferredSelections);
processDeferredActions(myDeferredExpansions);
}
private void processDeferredActions(Set<Runnable> actions) {
final Runnable[] runnables = actions.toArray(new Runnable[actions.size()]);
actions.clear();
for (Runnable runnable : runnables) {
runnable.run();
}
}
//todo: to make real callback
public ActionCallback queueUpdate(Object element) {
AbstractTreeUpdater updater = getUpdater();
if (updater == null) {
return new ActionCallback.Rejected();
}
final ActionCallback result = new ActionCallback();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
addSubtreeToUpdate(node);
}
else {
addSubtreeToUpdate(getRootNode());
}
updater.runAfterUpdate(new Runnable() {
public void run() {
result.setDone();
}
});
return result;
}
public void doUpdateFromRoot() {
updateSubtree(getRootNode(), false);
}
public ActionCallback doUpdateFromRootCB() {
final ActionCallback cb = new ActionCallback();
getUpdater().runAfterUpdate(new Runnable() {
public void run() {
cb.setDone();
}
});
updateSubtree(getRootNode(), false);
return cb;
}
public final void updateSubtree(DefaultMutableTreeNode node, boolean canSmartExpand) {
updateSubtree(new TreeUpdatePass(node), canSmartExpand);
}
public final void updateSubtree(TreeUpdatePass pass, boolean canSmartExpand) {
if (getUpdater() != null) {
getUpdater().addSubtreeToUpdate(pass);
}
else {
updateSubtreeNow(pass, canSmartExpand);
}
}
final void updateSubtreeNow(TreeUpdatePass pass, boolean canSmartExpand) {
maybeSetBusyAndScheduleWaiterForReady(true);
boolean consumed = initRootNodeNowIfNeeded(pass);
if (consumed) return;
final DefaultMutableTreeNode node = pass.getNode();
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
setUpdaterState(new UpdaterTreeState(this)).beforeSubtreeUpdate();
boolean forceUpdate = true;
TreePath path = getPathFor(node);
boolean invisible = !myTree.isExpanded(path) && (path.getParentPath() == null || !myTree.isExpanded(path.getParentPath()));
if (invisible && myUnbuiltNodes.contains(node)) {
forceUpdate = false;
}
updateNodeChildren(node, pass, null, false, canSmartExpand, forceUpdate, false);
}
private boolean isToBuildInBackground(NodeDescriptor descriptor) {
return getTreeStructure().isToBuildChildrenInBackground(getBuilder().getTreeStructureElement(descriptor));
}
@NotNull
UpdaterTreeState setUpdaterState(UpdaterTreeState state) {
if (myUpdaterState != null && myUpdaterState.equals(state)) return state;
final UpdaterTreeState oldState = myUpdaterState;
if (oldState == null) {
myUpdaterState = state;
return state;
}
else {
oldState.addAll(state);
return oldState;
}
}
protected void doUpdateNode(final DefaultMutableTreeNode node) {
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
final NodeDescriptor descriptor = getDescriptorFrom(node);
final Object prevElement = getElementFromDescriptor(descriptor);
if (prevElement == null) return;
update(descriptor, false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
if (!isValid(descriptor)) {
if (isInStructure(prevElement)) {
getUpdater().addSubtreeToUpdateByElement(getTreeStructure().getParentElement(prevElement));
return;
}
}
if (changes) {
updateNodeImageAndPosition(node, true);
}
}
});
}
public Object getElementFromDescriptor(NodeDescriptor descriptor) {
return getBuilder().getTreeStructureElement(descriptor);
}
private void updateNodeChildren(final DefaultMutableTreeNode node,
final TreeUpdatePass pass,
@Nullable LoadedChildren loadedChildren,
boolean forcedNow,
final boolean toSmartExpand,
boolean forceUpdate,
final boolean descriptorIsUpToDate) {
try {
getTreeStructure().commit();
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) {
removeLoading(node, true);
return;
}
final boolean wasExpanded = myTree.isExpanded(new TreePath(node.getPath())) || isAutoExpand(node);
final boolean wasLeaf = node.getChildCount() == 0;
boolean bgBuild = isToBuildInBackground(descriptor);
boolean notRequiredToUpdateChildren = !forcedNow && !wasExpanded;
if (notRequiredToUpdateChildren && forceUpdate && !wasExpanded) {
boolean alwaysPlus = getBuilder().isAlwaysShowPlus(descriptor);
if (alwaysPlus && wasLeaf) {
notRequiredToUpdateChildren = false;
} else {
notRequiredToUpdateChildren = alwaysPlus;
}
}
final Ref<LoadedChildren> preloaded = new Ref<LoadedChildren>(loadedChildren);
boolean descriptorWasUpdated = descriptorIsUpToDate;
if (notRequiredToUpdateChildren) {
if (myUnbuiltNodes.contains(node) && node.getChildCount() == 0) {
insertLoadingNode(node, true);
}
return;
}
if (!forcedNow) {
if (!bgBuild) {
if (myUnbuiltNodes.contains(node)) {
if (!descriptorWasUpdated) {
update(descriptor, true);
descriptorWasUpdated = true;
}
if (processAlwaysLeaf(node)) return;
Pair<Boolean, LoadedChildren> unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null);
if (unbuilt.getFirst()) return;
preloaded.set(unbuilt.getSecond());
}
}
}
final boolean childForceUpdate = isChildNodeForceUpdate(node, forceUpdate, wasExpanded);
if (!forcedNow && isToBuildInBackground(descriptor)) {
if (processAlwaysLeaf(node)) return;
queueBackgroundUpdate(
new UpdateInfo(descriptor, pass, canSmartExpand(node, toSmartExpand), wasExpanded, childForceUpdate, descriptorWasUpdated), node);
return;
}
else {
if (!descriptorWasUpdated) {
update(descriptor, false).doWhenDone(new Runnable() {
public void run() {
if (processAlwaysLeaf(node)) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, wasLeaf, childForceUpdate);
}
});
}
else {
if (processAlwaysLeaf(node)) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, wasLeaf, childForceUpdate);
}
}
}
finally {
processNodeActionsIfReady(node);
}
}
private boolean processAlwaysLeaf(DefaultMutableTreeNode node) {
Object element = getElementFor(node);
NodeDescriptor desc = getDescriptorFrom(node);
if (desc == null) return false;
if (getTreeStructure().isAlwaysLeaf(element)) {
removeLoading(node, true);
if (node.getChildCount() > 0) {
final TreeNode[] children = new TreeNode[node.getChildCount()];
for (int i = 0; i < node.getChildCount(); i++) {
children[i] = node.getChildAt(i);
}
if (isSelectionInside(node)) {
addSelectionPath(getPathFor(node), true, Condition.TRUE, null);
}
processInnerChange(new Runnable() {
public void run() {
for (TreeNode each : children) {
removeNodeFromParent((MutableTreeNode)each, true);
disposeNode((DefaultMutableTreeNode)each);
}
}
});
}
removeFromUnbuilt(node);
desc.setWasDeclaredAlwaysLeaf(true);
processNodeActionsIfReady(node);
return true;
} else {
boolean wasLeaf = desc.isWasDeclaredAlwaysLeaf();
desc.setWasDeclaredAlwaysLeaf(false);
if (wasLeaf) {
insertLoadingNode(node, true);
}
return false;
}
}
private boolean isChildNodeForceUpdate(DefaultMutableTreeNode node, boolean parentForceUpdate, boolean parentExpanded) {
TreePath path = getPathFor(node);
return parentForceUpdate && (parentExpanded || myTree.isExpanded(path));
}
private void updateNodeChildrenNow(final DefaultMutableTreeNode node,
final TreeUpdatePass pass,
final LoadedChildren preloadedChildren,
final boolean toSmartExpand,
final boolean wasExpanded,
final boolean wasLeaf,
final boolean forceUpdate) {
final NodeDescriptor descriptor = getDescriptorFrom(node);
final MutualMap<Object, Integer> elementToIndexMap = loadElementsFromStructure(descriptor, preloadedChildren);
final LoadedChildren loadedChildren =
preloadedChildren != null ? preloadedChildren : new LoadedChildren(elementToIndexMap.getKeys().toArray());
addToUpdating(node);
pass.setCurrentNode(node);
final boolean canSmartExpand = canSmartExpand(node, toSmartExpand);
processExistingNodes(node, elementToIndexMap, pass, canSmartExpand(node, toSmartExpand), forceUpdate, wasExpanded, preloadedChildren)
.doWhenDone(new Runnable() {
public void run() {
if (isDisposed(node)) {
removeFromUpdating(node);
return;
}
removeLoading(node, false);
final boolean expanded = isExpanded(node, wasExpanded);
if (expanded) {
myWillBeExpaned.add(node);
} else {
myWillBeExpaned.remove(node);
}
collectNodesToInsert(descriptor, elementToIndexMap, node, expanded, loadedChildren)
.doWhenDone(new AsyncResult.Handler<ArrayList<TreeNode>>() {
public void run(ArrayList<TreeNode> nodesToInsert) {
insertNodesInto(nodesToInsert, node);
updateNodesToInsert(nodesToInsert, pass, canSmartExpand, isChildNodeForceUpdate(node, forceUpdate, expanded));
removeLoading(node, true);
removeFromUpdating(node);
if (node.getChildCount() > 0) {
if (expanded ) {
expand(node, canSmartExpand);
}
}
final Object element = getElementFor(node);
addNodeAction(element, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
removeLoading(node, false);
}
}, false);
processNodeActionsIfReady(node);
}
}).doWhenProcessed(new Runnable() {
public void run() {
myWillBeExpaned.remove(node);
removeFromUpdating(node);
processNodeActionsIfReady(node);
}
});
}
}).doWhenRejected(new Runnable() {
public void run() {
removeFromUpdating(node);
processNodeActionsIfReady(node);
}
});
}
private boolean isDisposed(DefaultMutableTreeNode node) {
return !node.isNodeAncestor((DefaultMutableTreeNode)myTree.getModel().getRoot());
}
private void expand(DefaultMutableTreeNode node, boolean canSmartExpand) {
expand(new TreePath(node.getPath()), canSmartExpand);
}
private void expand(final TreePath path, boolean canSmartExpand) {
if (path == null) return;
final Object last = path.getLastPathComponent();
boolean isLeaf = myTree.getModel().isLeaf(path.getLastPathComponent());
final boolean isRoot = last == myTree.getModel().getRoot();
final TreePath parent = path.getParentPath();
if (isRoot && !myTree.isExpanded(path)) {
if (myTree.isRootVisible() || myUnbuiltNodes.contains(last)) {
insertLoadingNode((DefaultMutableTreeNode)last, false);
}
expandPath(path, canSmartExpand);
}
else if (myTree.isExpanded(path) || (isLeaf && parent != null && myTree.isExpanded(parent) && !myUnbuiltNodes.contains(last))) {
if (last instanceof DefaultMutableTreeNode) {
processNodeActionsIfReady((DefaultMutableTreeNode)last);
}
}
else {
if (isLeaf && myUnbuiltNodes.contains(last)) {
insertLoadingNode((DefaultMutableTreeNode)last, true);
expandPath(path, canSmartExpand);
}
else if (isLeaf && parent != null) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent.getLastPathComponent();
if (parentNode != null) {
addToUnbuilt(parentNode);
}
expandPath(parent, canSmartExpand);
}
else {
expandPath(path, canSmartExpand);
}
}
}
private void addToUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.add(node);
}
private void removeFromUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.remove(node);
}
private Pair<Boolean, LoadedChildren> processUnbuilt(final DefaultMutableTreeNode node,
final NodeDescriptor descriptor,
final TreeUpdatePass pass,
boolean isExpanded,
final LoadedChildren loadedChildren) {
if (!isExpanded && getBuilder().isAlwaysShowPlus(descriptor)) {
return new Pair<Boolean, LoadedChildren>(true, null);
}
final Object element = getElementFor(node);
final LoadedChildren children = loadedChildren != null ? loadedChildren : new LoadedChildren(getChildrenFor(element));
boolean processed;
if (children.getElements().size() == 0) {
removeLoading(node, true);
processed = true;
}
else {
if (isAutoExpand(node)) {
addNodeAction(getElementFor(node), new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
final TreePath path = new TreePath(node.getPath());
if (getTree().isExpanded(path) || children.getElements().size() == 0) {
removeLoading(node, false);
}
else {
maybeYeild(new ActiveRunnable() {
public ActionCallback run() {
expand(element, null);
return new ActionCallback.Done();
}
}, pass, node);
}
}
}, false);
}
processed = false;
}
processNodeActionsIfReady(node);
return new Pair<Boolean, LoadedChildren>(processed, children);
}
private boolean removeIfLoading(TreeNode node) {
if (isLoadingNode(node)) {
moveSelectionToParentIfNeeded(node);
removeNodeFromParent((MutableTreeNode)node, false);
return true;
}
return false;
}
private void moveSelectionToParentIfNeeded(TreeNode node) {
TreePath path = getPathFor(node);
if (myTree.getSelectionModel().isPathSelected(path)) {
TreePath parentPath = path.getParentPath();
myTree.getSelectionModel().removeSelectionPath(path);
if (parentPath != null) {
myTree.getSelectionModel().addSelectionPath(parentPath);
}
}
}
//todo [kirillk] temporary consistency check
private Object[] getChildrenFor(final Object element) {
final Object[] passOne;
try {
passOne = getTreeStructure().getChildElements(element);
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady();
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
if (!myCheckStructure) return passOne;
final Object[] passTwo = getTreeStructure().getChildElements(element);
final HashSet two = new HashSet(Arrays.asList(passTwo));
if (passOne.length != passTwo.length) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
}
else {
for (Object eachInOne : passOne) {
if (!two.contains(eachInOne)) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
break;
}
}
}
return passOne;
}
private void warnOnIndexNotReady() {
if (!myWasEverIndexNotReady) {
myWasEverIndexNotReady = true;
LOG.warn("Tree is not dumb-mode-aware; treeBuilder=" + getBuilder() + " treeStructure=" + getTreeStructure());
}
}
private void updateNodesToInsert(final ArrayList<TreeNode> nodesToInsert,
TreeUpdatePass pass,
boolean canSmartExpand,
boolean forceUpdate) {
for (TreeNode aNodesToInsert : nodesToInsert) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)aNodesToInsert;
updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true);
}
}
private ActionCallback processExistingNodes(final DefaultMutableTreeNode node,
final MutualMap<Object, Integer> elementToIndexMap,
final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
final boolean wasExpaned,
final LoadedChildren preloaded) {
final ArrayList<TreeNode> childNodes = TreeUtil.childrenToArray(node);
return maybeYeild(new ActiveRunnable() {
public ActionCallback run() {
if (pass.isExpired()) return new ActionCallback.Rejected();
if (childNodes.size() == 0) return new ActionCallback.Done();
final ActionCallback result = new ActionCallback(childNodes.size());
for (TreeNode each : childNodes) {
final DefaultMutableTreeNode eachChild = (DefaultMutableTreeNode)each;
if (isLoadingNode(eachChild)) {
result.setDone();
continue;
}
final boolean childForceUpdate = isChildNodeForceUpdate(eachChild, forceUpdate, wasExpaned);
maybeYeild(new ActiveRunnable() {
@Override
public ActionCallback run() {
return processExistingNode(eachChild, getDescriptorFrom(eachChild), node, elementToIndexMap, pass, canSmartExpand,
childForceUpdate, preloaded);
}
}, pass, node).notify(result);
if (result.isRejected()) {
break;
}
}
return result;
}
}, pass, node);
}
private boolean isRerunNeeded(TreeUpdatePass pass) {
if (pass.isExpired()) return false;
final boolean rerunBecauseTreeIsHidden = !pass.isExpired() && !isTreeShowing() && getUpdater().isInPostponeMode();
return rerunBecauseTreeIsHidden || getUpdater().isRerunNeededFor(pass);
}
private ActionCallback maybeYeild(final ActiveRunnable processRunnable, final TreeUpdatePass pass, final DefaultMutableTreeNode node) {
final ActionCallback result = new ActionCallback();
if (isRerunNeeded(pass)) {
getUpdater().addSubtreeToUpdate(pass);
result.setRejected();
}
else {
if (isToYieldUpdateFor(node)) {
pass.setCurrentNode(node);
boolean wasRun = yieldAndRun(new Runnable() {
public void run() {
if (validateReleaseRequested()) {
result.setRejected();
return;
}
if (pass.isExpired()) {
result.setRejected();
return;
}
if (isRerunNeeded(pass)) {
runDone(new Runnable() {
public void run() {
if (!pass.isExpired()) {
getUpdater().addSubtreeToUpdate(pass);
}
}
});
result.setRejected();
}
else {
try {
processRunnable.run().notify(result);
}
catch (ProcessCanceledException e) {
pass.expire();
result.setRejected();
}
}
}
}, pass);
if (!wasRun) {
result.setRejected();
}
}
else {
try {
processRunnable.run().notify(result);
}
catch (ProcessCanceledException e) {
pass.expire();
result.setRejected();
}
}
}
return result;
}
private boolean yieldAndRun(final Runnable runnable, final TreeUpdatePass pass) {
if (validateReleaseRequested()) return false;
myYeildingPasses.add(pass);
myYeildingNow = true;
yield(new Runnable() {
public void run() {
runOnYieldingDone(new Runnable() {
public void run() {
executeYieldingRequest(runnable, pass);
}
});
}
});
return true;
}
public boolean isYeildingNow() {
return myYeildingNow;
}
private boolean hasSheduledUpdates() {
return getUpdater().hasNodesToUpdate() || isLoadingInBackgroundNow();
}
public boolean isReady() {
return isIdle() && !hasPendingWork() && !isNodeActionsPending();
}
public boolean hasPendingWork() {
return hasNodesToUpdate() || (myUpdaterState != null && myUpdaterState.isProcessingNow());
}
public boolean isIdle() {
return !isYeildingNow() && !isWorkerBusy() && (!hasSheduledUpdates() || getUpdater().isInPostponeMode());
}
private void executeYieldingRequest(Runnable runnable, TreeUpdatePass pass) {
try {
myYeildingPasses.remove(pass);
runnable.run();
}
finally {
maybeYeildingFinished();
}
}
private void maybeYeildingFinished() {
if (myYeildingPasses.size() == 0) {
myYeildingNow = false;
flushPendingNodeActions();
}
}
void maybeReady() {
if (isReleased()) return;
if (isReady()) {
if (isReleaseRequested()) {
releaseNow();
return;
}
if (myTree.isShowing() || myUpdateIfInactive) {
myInitialized.setDone();
}
if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) {
UpdaterTreeState oldState = myUpdaterState;
if (!myUpdaterState.restore(null)) {
setUpdaterState(oldState);
}
if (!isReady()) {
return;
}
}
if (myTree.isShowing()) {
if (getBuilder().isToEnsureSelectionOnFocusGained() && Registry.is("ide.tree.ensureSelectionOnFocusGained")) {
TreeUtil.ensureSelection(myTree);
}
}
if (myInitialized.isDone()) {
for (ActionCallback each : getReadyCallbacks(true)) {
each.setDone();
}
}
}
}
private void flushPendingNodeActions() {
final DefaultMutableTreeNode[] nodes = myPendingNodeActions.toArray(new DefaultMutableTreeNode[myPendingNodeActions.size()]);
myPendingNodeActions.clear();
for (DefaultMutableTreeNode each : nodes) {
processNodeActionsIfReady(each);
}
final Runnable[] actions = myYeildingDoneRunnables.toArray(new Runnable[myYeildingDoneRunnables.size()]);
for (Runnable each : actions) {
if (!isYeildingNow()) {
myYeildingDoneRunnables.remove(each);
each.run();
}
}
maybeReady();
}
protected void runOnYieldingDone(Runnable onDone) {
getBuilder().runOnYeildingDone(onDone);
}
protected void yield(Runnable runnable) {
getBuilder().yield(runnable);
}
private boolean isToYieldUpdateFor(final DefaultMutableTreeNode node) {
if (!canYield()) return false;
return getBuilder().isToYieldUpdateFor(node);
}
private MutualMap<Object, Integer> loadElementsFromStructure(final NodeDescriptor descriptor,
@Nullable LoadedChildren preloadedChildren) {
MutualMap<Object, Integer> elementToIndexMap = new MutualMap<Object, Integer>(true);
List children = preloadedChildren != null
? preloadedChildren.getElements()
: Arrays.asList(getChildrenFor(getBuilder().getTreeStructureElement(descriptor)));
int index = 0;
for (Object child : children) {
if (!isValid(child)) continue;
elementToIndexMap.put(child, Integer.valueOf(index));
index++;
}
return elementToIndexMap;
}
private void expand(final DefaultMutableTreeNode node,
final NodeDescriptor descriptor,
final boolean wasLeaf,
final boolean canSmartExpand) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
alarm.addRequest(new Runnable() {
public void run() {
myTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}, WAIT_CURSOR_DELAY);
if (wasLeaf && isAutoExpand(descriptor)) {
expand(node, canSmartExpand);
}
ArrayList<TreeNode> nodes = TreeUtil.childrenToArray(node);
for (TreeNode node1 : nodes) {
final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)node1;
if (isLoadingNode(childNode)) continue;
NodeDescriptor childDescr = getDescriptorFrom(childNode);
if (isAutoExpand(childDescr)) {
addNodeAction(getElementFor(childNode), new NodeAction() {
public void onReady(DefaultMutableTreeNode node) {
expand(childNode, canSmartExpand);
}
}, false);
addSubtreeToUpdate(childNode);
}
}
int n = alarm.cancelAllRequests();
if (n == 0) {
myTree.setCursor(Cursor.getDefaultCursor());
}
}
public static boolean isLoadingNode(final Object node) {
return node instanceof LoadingNode;
}
private AsyncResult<ArrayList<TreeNode>> collectNodesToInsert(final NodeDescriptor descriptor,
final MutualMap<Object, Integer> elementToIndexMap,
final DefaultMutableTreeNode parent,
final boolean addLoadingNode,
@NotNull final LoadedChildren loadedChildren) {
final AsyncResult<ArrayList<TreeNode>> result = new AsyncResult<ArrayList<TreeNode>>();
final ArrayList<TreeNode> nodesToInsert = new ArrayList<TreeNode>();
final Collection<Object> allElements = elementToIndexMap.getKeys();
final ActionCallback processingDone = new ActionCallback(allElements.size());
for (final Object child : allElements) {
Integer index = elementToIndexMap.getValue(child);
final Ref<NodeDescriptor> childDescr = new Ref<NodeDescriptor>(loadedChildren.getDescriptor(child));
boolean needToUpdate = false;
if (childDescr.get() == null) {
childDescr.set(getTreeStructure().createDescriptor(child, descriptor));
needToUpdate = true;
}
if (childDescr.get() == null) {
processingDone.setDone();
continue;
}
childDescr.get().setIndex(index.intValue());
final ActionCallback update = new ActionCallback();
if (needToUpdate) {
update(childDescr.get(), false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
loadedChildren.putDescriptor(child, childDescr.get(), changes);
update.setDone();
}
});
}
else {
update.setDone();
}
update.doWhenDone(new Runnable() {
public void run() {
Object element = getElementFromDescriptor(childDescr.get());
if (element == null) {
processingDone.setDone();
}
else {
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null || node.getParent() != parent) {
final DefaultMutableTreeNode childNode = createChildNode(childDescr.get());
if (addLoadingNode || getBuilder().isAlwaysShowPlus(childDescr.get())) {
insertLoadingNode(childNode, true);
}
else {
addToUnbuilt(childNode);
}
nodesToInsert.add(childNode);
createMapping(element, childNode);
}
processingDone.setDone();
}
}
});
}
processingDone.doWhenDone(new Runnable() {
public void run() {
result.setDone(nodesToInsert);
}
});
return result;
}
protected DefaultMutableTreeNode createChildNode(final NodeDescriptor descriptor) {
return new ElementNode(this, descriptor);
}
protected boolean canYield() {
return myCanYield && myYeildingUpdate.asBoolean();
}
public long getClearOnHideDelay() {
return myClearOnHideDelay > 0 ? myClearOnHideDelay : Registry.intValue("ide.tree.clearOnHideTime");
}
public ActionCallback getInitialized() {
return myInitialized;
}
public ActionCallback getReady(Object requestor) {
if (isReady()) {
return new ActionCallback.Done();
}
else {
return addReadyCallback(requestor);
}
}
private void addToUpdating(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.add(node);
}
}
private void removeFromUpdating(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.remove(node);
}
}
public boolean isUpdatingNow(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
return myUpdatingChildren.contains(node);
}
}
boolean hasUpdatingNow() {
synchronized (myUpdatingChildren) {
return myUpdatingChildren.size() > 0;
}
}
public Map getNodeActions() {
return myNodeActions;
}
public List<Object> getLoadedChildrenFor(Object element) {
List<Object> result = new ArrayList<Object>();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)getNodeForElement(element, false);
if (node != null) {
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode each = node.getChildAt(i);
if (isLoadingNode(each)) continue;
result.add(getElementFor(each));
}
}
return result;
}
public boolean hasNodesToUpdate() {
return getUpdater().hasNodesToUpdate() || hasUpdatingNow() || isLoadingInBackgroundNow();
}
public List<Object> getExpandedElements() {
List<Object> result = new ArrayList<Object>();
Enumeration<TreePath> enumeration = myTree.getExpandedDescendants(getPathFor(getRootNode()));
while (enumeration.hasMoreElements()) {
TreePath each = enumeration.nextElement();
Object eachElement = getElementFor(each.getLastPathComponent());
if (eachElement != null) {
result.add(eachElement);
}
}
return result;
}
static class ElementNode extends DefaultMutableTreeNode {
Set<Object> myElements = new HashSet<Object>();
AbstractTreeUi myUi;
ElementNode(AbstractTreeUi ui, NodeDescriptor descriptor) {
super(descriptor);
myUi = ui;
}
@Override
public void insert(final MutableTreeNode newChild, final int childIndex) {
super.insert(newChild, childIndex);
final Object element = myUi.getElementFor(newChild);
if (element != null) {
myElements.add(element);
}
}
@Override
public void remove(final int childIndex) {
final TreeNode node = getChildAt(childIndex);
super.remove(childIndex);
final Object element = myUi.getElementFor(node);
if (element != null) {
myElements.remove(element);
}
}
boolean isValidChild(Object childElement) {
return myElements.contains(childElement);
}
@Override
public String toString() {
return String.valueOf(getUserObject());
}
}
private boolean isUpdatingParent(DefaultMutableTreeNode kid) {
return getUpdatingParent(kid) != null;
}
private DefaultMutableTreeNode getUpdatingParent(DefaultMutableTreeNode kid) {
DefaultMutableTreeNode eachParent = kid;
while (eachParent != null) {
if (isUpdatingNow(eachParent)) return eachParent;
eachParent = (DefaultMutableTreeNode)eachParent.getParent();
}
return null;
}
private boolean isLoadedInBackground(Object element) {
return getLoadedInBackground(element) != null;
}
private UpdateInfo getLoadedInBackground(Object element) {
synchronized (myLoadedInBackground) {
return myLoadedInBackground.get(element);
}
}
private void addToLoadedInBackground(Object element, UpdateInfo info) {
synchronized (myLoadedInBackground) {
myLoadedInBackground.put(element, info);
}
}
private void removeFromLoadedInBackground(final Object element) {
synchronized (myLoadedInBackground) {
myLoadedInBackground.remove(element);
}
}
private boolean isLoadingInBackgroundNow() {
synchronized (myLoadedInBackground) {
return myLoadedInBackground.size() > 0;
}
}
private boolean queueBackgroundUpdate(final UpdateInfo updateInfo, final DefaultMutableTreeNode node) {
assertIsDispatchThread();
if (validateReleaseRequested()) return false;
final Object oldElementFromDescriptor = getElementFromDescriptor(updateInfo.getDescriptor());
UpdateInfo loaded = getLoadedInBackground(oldElementFromDescriptor);
if (loaded != null) {
loaded.apply(updateInfo);
return false;
}
addToLoadedInBackground(oldElementFromDescriptor, updateInfo);
if (!isNodeBeingBuilt(node)) {
LoadingNode loadingNode = new LoadingNode(getLoadingNodeText());
myTreeModel.insertNodeInto(loadingNode, node, node.getChildCount());
}
final Ref<LoadedChildren> children = new Ref<LoadedChildren>();
final Ref<Object> elementFromDescriptor = new Ref<Object>();
final DefaultMutableTreeNode[] nodeToProcessActions = new DefaultMutableTreeNode[1];
final Runnable finalizeRunnable = new Runnable() {
public void run() {
invokeLaterIfNeeded(new Runnable() {
public void run() {
removeLoading(node, true);
removeFromLoadedInBackground(elementFromDescriptor.get());
removeFromLoadedInBackground(oldElementFromDescriptor);
if (nodeToProcessActions[0] != null) {
processNodeActionsIfReady(nodeToProcessActions[0]);
}
}
});
}
};
Runnable buildRunnable = new Runnable() {
public void run() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (!updateInfo.isDescriptorIsUpToDate()) {
update(updateInfo.getDescriptor(), true);
}
Object element = getElementFromDescriptor(updateInfo.getDescriptor());
if (element == null) {
removeFromLoadedInBackground(oldElementFromDescriptor);
finalizeRunnable.run();
return;
}
elementFromDescriptor.set(element);
Object[] loadedElements = getChildrenFor(getBuilder().getTreeStructureElement(updateInfo.getDescriptor()));
LoadedChildren loaded = new LoadedChildren(loadedElements);
for (Object each : loadedElements) {
NodeDescriptor eachChildDescriptor = getTreeStructure().createDescriptor(each, updateInfo.getDescriptor());
loaded.putDescriptor(each, eachChildDescriptor, update(eachChildDescriptor, true).getResult());
}
children.set(loaded);
}
};
Runnable updateRunnable = new Runnable() {
public void run() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (children.get() == null) {
finalizeRunnable.run();
return;
}
if (isRerunNeeded(updateInfo.getPass())) {
removeFromLoadedInBackground(elementFromDescriptor.get());
getUpdater().addSubtreeToUpdate(updateInfo.getPass());
return;
}
removeFromLoadedInBackground(elementFromDescriptor.get());
if (myUnbuiltNodes.contains(node)) {
Pair<Boolean, LoadedChildren> unbuilt =
processUnbuilt(node, updateInfo.getDescriptor(), updateInfo.getPass(), isExpanded(node, updateInfo.isWasExpanded()),
children.get());
if (unbuilt.getFirst()) {
nodeToProcessActions[0] = node;
return;
}
}
updateNodeChildren(node, updateInfo.getPass(), children.get(), true, updateInfo.isCanSmartExpand(), updateInfo.isForceUpdate(),
true);
if (isRerunNeeded(updateInfo.getPass())) {
getUpdater().addSubtreeToUpdate(updateInfo.getPass());
return;
}
Object element = elementFromDescriptor.get();
if (element != null) {
removeLoading(node, true);
nodeToProcessActions[0] = node;
}
}
};
queueToBackground(buildRunnable, updateRunnable).doWhenProcessed(finalizeRunnable).doWhenRejected(new Runnable() {
public void run() {
updateInfo.getPass().expire();
}
});
return true;
}
private boolean isExpanded(DefaultMutableTreeNode node, boolean isExpanded) {
return isExpanded || myTree.isExpanded(getPathFor(node));
}
private void removeLoading(DefaultMutableTreeNode parent, boolean removeFromUnbuilt) {
for (int i = 0; i < parent.getChildCount(); i++) {
TreeNode child = parent.getChildAt(i);
if (removeIfLoading(child)) {
i--;
}
}
if (removeFromUnbuilt) {
removeFromUnbuilt(parent);
}
if (parent == getRootNode() && !myTree.isRootVisible() && parent.getChildCount() == 0) {
insertLoadingNode(parent, false);
}
maybeReady();
}
private void processNodeActionsIfReady(final DefaultMutableTreeNode node) {
assertIsDispatchThread();
if (isNodeBeingBuilt(node)) return;
final Object o = node.getUserObject();
if (!(o instanceof NodeDescriptor)) return;
if (isYeildingNow()) {
myPendingNodeActions.add(node);
return;
}
final Object element = getBuilder().getTreeStructureElement((NodeDescriptor)o);
boolean childrenReady = !isLoadedInBackground(element);
processActions(node, element, myNodeActions, childrenReady ? myNodeChildrenActions : null);
if (childrenReady) {
processActions(node, element, myNodeChildrenActions, null);
}
if (!isUpdatingParent(node) && !isWorkerBusy()) {
final UpdaterTreeState state = myUpdaterState;
if (myNodeActions.size() == 0 && state != null && !state.isProcessingNow()) {
if (!state.restore(childrenReady ? node : null)) {
setUpdaterState(state);
}
}
}
maybeReady();
}
private void processActions(DefaultMutableTreeNode node, Object element, final Map<Object, List<NodeAction>> nodeActions, @Nullable final Map<Object, List<NodeAction>> secondaryNodeAction) {
final List<NodeAction> actions = nodeActions.get(element);
if (actions != null) {
nodeActions.remove(element);
List<NodeAction> secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null;
for (NodeAction each : actions) {
if (secondary != null && secondary.contains(each)) {
secondary.remove(each);
}
each.onReady(node);
}
}
}
private boolean canSmartExpand(DefaultMutableTreeNode node, boolean canSmartExpand) {
if (!getBuilder().isSmartExpand()) return false;
boolean smartExpand = !myNotForSmartExpand.contains(node) && canSmartExpand;
return smartExpand ? validateAutoExpand(smartExpand, getElementFor(node)) : false;
}
private void processSmartExpand(final DefaultMutableTreeNode node, final boolean canSmartExpand, boolean forced) {
if (!getBuilder().isSmartExpand()) return;
boolean can = canSmartExpand(node, canSmartExpand);
if (!can && !forced) return;
if (isNodeBeingBuilt(node) && !forced) {
addNodeAction(getElementFor(node), new NodeAction() {
public void onReady(DefaultMutableTreeNode node) {
processSmartExpand(node, canSmartExpand, true);
}
}, true);
}
else {
TreeNode child = getChildForSmartExpand(node);
if (child != null) {
final TreePath childPath = new TreePath(node.getPath()).pathByAddingChild(child);
processInnerChange(new Runnable() {
public void run() {
myTree.expandPath(childPath);
}
});
}
}
}
@Nullable
private TreeNode getChildForSmartExpand(DefaultMutableTreeNode node) {
int realChildCount = 0;
TreeNode nodeToExpand = null;
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode eachChild = node.getChildAt(i);
if (!isLoadingNode(eachChild)) {
realChildCount++;
if (nodeToExpand == null) {
nodeToExpand = eachChild;
}
}
if (realChildCount > 1) {
nodeToExpand = null;
break;
}
}
return nodeToExpand;
}
public boolean isLoadingChildrenFor(final Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return false;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
int loadingNodes = 0;
for (int i = 0; i < Math.min(node.getChildCount(), 2); i++) {
TreeNode child = node.getChildAt(i);
if (isLoadingNode(child)) {
loadingNodes++;
}
}
return loadingNodes > 0 && loadingNodes == node.getChildCount();
}
private boolean isParentLoading(Object nodeObject) {
return getParentLoading(nodeObject) != null;
}
private DefaultMutableTreeNode getParentLoading(Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
TreeNode eachParent = node.getParent();
while (eachParent != null) {
eachParent = eachParent.getParent();
if (eachParent instanceof DefaultMutableTreeNode) {
final Object eachElement = getElementFor((DefaultMutableTreeNode)eachParent);
if (isLoadedInBackground(eachElement)) return (DefaultMutableTreeNode)eachParent;
}
}
return null;
}
protected String getLoadingNodeText() {
return IdeBundle.message("progress.searching");
}
private ActionCallback processExistingNode(final DefaultMutableTreeNode childNode,
final NodeDescriptor childDescriptor,
final DefaultMutableTreeNode parentNode,
final MutualMap<Object, Integer> elementToIndexMap,
final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
LoadedChildren parentPreloadedChildren) {
final ActionCallback result = new ActionCallback();
if (pass.isExpired()) {
return new ActionCallback.Rejected();
}
final Ref<NodeDescriptor> childDesc = new Ref<NodeDescriptor>(childDescriptor);
if (childDesc.get() == null) {
pass.expire();
return new ActionCallback.Rejected();
}
final Object oldElement = getElementFromDescriptor(childDesc.get());
if (oldElement == null) {
pass.expire();
return new ActionCallback.Rejected();
}
AsyncResult<Boolean> update = new AsyncResult<Boolean>();
if (parentPreloadedChildren != null && parentPreloadedChildren.getDescriptor(oldElement) != null) {
update.setDone(parentPreloadedChildren.isUpdated(oldElement));
}
else {
update = update(childDesc.get(), false);
}
update.doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean isChanged) {
final Ref<Boolean> changes = new Ref<Boolean>(isChanged);
final Ref<Boolean> forceRemapping = new Ref<Boolean>(false);
final Ref<Object> newElement = new Ref<Object>(getElementFromDescriptor(childDesc.get()));
final Integer index = newElement.get() != null ? elementToIndexMap.getValue(getBuilder().getTreeStructureElement(childDesc.get())) : null;
final AsyncResult<Boolean> updateIndexDone = new AsyncResult<Boolean>();
final ActionCallback indexReady = new ActionCallback();
if (index != null) {
final Object elementFromMap = elementToIndexMap.getKey(index);
if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) {
if (isInStructure(elementFromMap) && isInStructure(newElement.get())) {
if (parentNode.getUserObject() instanceof NodeDescriptor) {
final NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor));
childNode.setUserObject(childDesc.get());
newElement.set(elementFromMap);
forceRemapping.set(true);
update(childDesc.get(), false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean isChanged) {
changes.set(isChanged);
updateIndexDone.setDone(isChanged);
}
});
}
}
else {
updateIndexDone.setDone(changes.get());
}
} else {
updateIndexDone.setDone(changes.get());
}
updateIndexDone.doWhenDone(new Runnable() {
public void run() {
if (childDesc.get().getIndex() != index.intValue()) {
changes.set(true);
}
childDesc.get().setIndex(index.intValue());
indexReady.setDone();
}
});
}
else {
updateIndexDone.setDone();
}
updateIndexDone.doWhenDone(new Runnable() {
public void run() {
if (index != null && changes.get()) {
updateNodeImageAndPosition(childNode, false);
}
if (!oldElement.equals(newElement.get()) | forceRemapping.get()) {
removeMapping(oldElement, childNode, newElement.get());
if (newElement.get() != null) {
createMapping(newElement.get(), childNode);
}
NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
if (parentDescriptor != null) {
parentDescriptor.setChildrenSortingStamp(-1);
}
}
if (index == null) {
int selectedIndex = -1;
if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) {
selectedIndex = parentNode.getIndex(childNode);
}
if (childNode.getParent() instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent();
if (myTree.isExpanded(new TreePath(parent.getPath()))) {
if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) {
insertLoadingNode(parent, false);
}
}
}
Object disposedElement = getElementFor(childNode);
removeNodeFromParent(childNode, selectedIndex >= 0);
disposeNode(childNode);
adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement);
}
else {
elementToIndexMap.remove(getBuilder().getTreeStructureElement(childDesc.get()));
updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true);
}
if (parentNode.equals(getRootNode())) {
myTreeModel.nodeChanged(getRootNode());
}
result.setDone();
}
});
}
});
return result;
}
private void adjustSelectionOnChildRemove(DefaultMutableTreeNode parentNode, int selectedIndex, Object disposedElement) {
DefaultMutableTreeNode node = getNodeForElement(disposedElement, false);
if (node != null && isValidForSelectionAdjusting(node)) {
Object newElement = getElementFor(node);
addSelectionPath(getPathFor(node), true, getExpiredElementCondition(newElement), disposedElement);
return;
}
if (selectedIndex >= 0) {
if (parentNode.getChildCount() > 0) {
if (parentNode.getChildCount() > selectedIndex) {
TreeNode newChildNode = parentNode.getChildAt(selectedIndex);
if (isValidForSelectionAdjusting(newChildNode)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChildNode)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
else {
TreeNode newChild = parentNode.getChildAt(parentNode.getChildCount() - 1);
if (isValidForSelectionAdjusting(newChild)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChild)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
}
else {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(parentNode)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
}
private boolean isValidForSelectionAdjusting(TreeNode node) {
if (!myTree.isRootVisible() && getRootNode() == node) return false;
if (isLoadingNode(node)) return true;
final Object elementInTree = getElementFor(node);
if (elementInTree == null) return false;
final TreeNode parentNode = node.getParent();
final Object parentElementInTree = getElementFor(parentNode);
if (parentElementInTree == null) return false;
final Object parentElement = getTreeStructure().getParentElement(elementInTree);
return parentElementInTree.equals(parentElement);
}
public Condition getExpiredElementCondition(final Object element) {
return new Condition() {
public boolean value(final Object o) {
return isInStructure(element);
}
};
}
private void addSelectionPath(final TreePath path, final boolean isAdjustedSelection, final Condition isExpiredAdjustement, @Nullable final Object adjustmentCause) {
processInnerChange(new Runnable() {
public void run() {
TreePath toSelect = null;
if (isLoadingNode(path.getLastPathComponent())) {
final TreePath parentPath = path.getParentPath();
if (parentPath != null) {
if (isValidForSelectionAdjusting((TreeNode)parentPath.getLastPathComponent())) {
toSelect = parentPath;
}
else {
toSelect = null;
}
}
}
else {
toSelect = path;
}
if (toSelect != null) {
myTree.addSelectionPath(toSelect);
if (isAdjustedSelection && myUpdaterState != null) {
final Object toSelectElement = getElementFor(toSelect.getLastPathComponent());
myUpdaterState.addAdjustedSelection(toSelectElement, isExpiredAdjustement, adjustmentCause);
}
}
}
});
}
private static TreePath getPathFor(TreeNode node) {
if (node instanceof DefaultMutableTreeNode) {
return new TreePath(((DefaultMutableTreeNode)node).getPath());
}
else {
ArrayList nodes = new ArrayList();
TreeNode eachParent = node;
while (eachParent != null) {
nodes.add(eachParent);
eachParent = eachParent.getParent();
}
return new TreePath(ArrayUtil.toObjectArray(nodes));
}
}
private void removeNodeFromParent(final MutableTreeNode node, final boolean willAdjustSelection) {
processInnerChange(new Runnable() {
public void run() {
if (willAdjustSelection) {
final TreePath path = getPathFor(node);
if (myTree.isPathSelected(path)) {
myTree.removeSelectionPath(path);
}
}
if (node.getParent() != null) {
myTreeModel.removeNodeFromParent(node);
}
}
});
}
private void expandPath(final TreePath path, final boolean canSmartExpand) {
processInnerChange(new Runnable() {
public void run() {
if (path.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getChildCount() > 0 && !myTree.isExpanded(path)) {
if (!canSmartExpand) {
myNotForSmartExpand.add(node);
}
try {
myRequestedExpand = path;
myTree.expandPath(path);
processSmartExpand(node, canSmartExpand, false);
}
finally {
myNotForSmartExpand.remove(node);
myRequestedExpand = null;
}
}
else {
processNodeActionsIfReady(node);
}
}
}
});
}
private void processInnerChange(Runnable runnable) {
if (myUpdaterState == null) {
setUpdaterState(new UpdaterTreeState(this));
}
myUpdaterState.process(runnable);
}
private boolean isInnerChange() {
return myUpdaterState != null && myUpdaterState.isProcessingNow();
}
protected boolean doUpdateNodeDescriptor(final NodeDescriptor descriptor) {
return descriptor.update();
}
private void makeLoadingOrLeafIfNoChildren(final DefaultMutableTreeNode node) {
TreePath path = getPathFor(node);
if (path == null) return;
insertLoadingNode(node, true);
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
descriptor.setChildrenSortingStamp(-1);
if (getBuilder().isAlwaysShowPlus(descriptor)) return;
TreePath parentPath = path.getParentPath();
if (myTree.isVisible(path) || (parentPath != null && myTree.isExpanded(parentPath))) {
if (myTree.isExpanded(path)) {
addSubtreeToUpdate(node);
}
else {
insertLoadingNode(node, false);
}
}
}
private boolean isValid(DefaultMutableTreeNode node) {
if (node == null) return false;
final Object object = node.getUserObject();
if (object instanceof NodeDescriptor) {
return isValid((NodeDescriptor)object);
}
return false;
}
private boolean isValid(NodeDescriptor descriptor) {
if (descriptor == null) return false;
return isValid(getElementFromDescriptor(descriptor));
}
private boolean isValid(Object element) {
if (element instanceof ValidateableNode) {
if (!((ValidateableNode)element).isValid()) return false;
}
return getBuilder().validateNode(element);
}
private void insertLoadingNode(final DefaultMutableTreeNode node, boolean addToUnbuilt) {
if (!isLoadingChildrenFor(node)) {
myTreeModel.insertNodeInto(new LoadingNode(), node, 0);
}
if (addToUnbuilt) {
addToUnbuilt(node);
}
}
protected ActionCallback queueToBackground(@NotNull final Runnable bgBuildAction,
@Nullable final Runnable edtPostRunnable) {
if (validateReleaseRequested()) return new ActionCallback.Rejected();
final ActionCallback result = new ActionCallback();
final Ref<Boolean> fail = new Ref<Boolean>(false);
final Runnable finalizer = new Runnable() {
public void run() {
if (fail.get()) {
result.setRejected();
} else {
result.setDone();
}
}
};
registerWorkerTask(bgBuildAction);
final Runnable pooledThreadWithProgressRunnable = new Runnable() {
public void run() {
final AbstractTreeBuilder builder = getBuilder();
builder.runBackgroundLoading(new Runnable() {
public void run() {
assertNotDispatchThread();
try {
bgBuildAction.run();
if (edtPostRunnable != null) {
builder.updateAfterLoadedInBackground(new Runnable() {
public void run() {
try {
assertIsDispatchThread();
edtPostRunnable.run();
} catch (ProcessCanceledException e) {
fail.set(true);
}
finally {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
});
}
else {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
catch (ProcessCanceledException e) {
fail.set(true);
unregisterWorkerTask(bgBuildAction, finalizer);
}
catch (Throwable t) {
unregisterWorkerTask(bgBuildAction, finalizer);
throw new RuntimeException(t);
}
}
});
}
};
Runnable pooledThreadRunnable = new Runnable() {
public void run() {
try {
if (myProgress != null) {
ProgressManager.getInstance().runProcess(pooledThreadWithProgressRunnable, myProgress);
}
else {
pooledThreadWithProgressRunnable.run();
}
}
catch (ProcessCanceledException e) {
fail.set(true);
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
};
if (isPassthroughMode()) {
} else {
if (myWorker == null || myWorker.isDisposed()) {
myWorker = new WorkerThread("AbstractTreeBuilder.Worker", 1);
myWorker.start();
myWorker.addTaskFirst(pooledThreadRunnable);
myWorker.dispose(false);
}
else {
myWorker.addTaskFirst(pooledThreadRunnable);
}
}
return result;
}
private void registerWorkerTask(Runnable runnable) {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.add(runnable);
}
}
private void unregisterWorkerTask(Runnable runnable, @Nullable Runnable finalizeRunnable) {
boolean wasRemoved;
synchronized (myActiveWorkerTasks) {
wasRemoved = myActiveWorkerTasks.remove(runnable);
}
if (wasRemoved && finalizeRunnable != null) {
finalizeRunnable.run();
}
maybeReady();
}
public boolean isWorkerBusy() {
synchronized (myActiveWorkerTasks) {
return myActiveWorkerTasks.size() > 0;
}
}
private void clearWorkerTasks() {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.clear();
}
}
private void updateNodeImageAndPosition(final DefaultMutableTreeNode node, boolean updatePosition) {
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (getElementFromDescriptor(descriptor) == null) return;
boolean notified = false;
if (updatePosition) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)node.getParent();
if (parentNode != null) {
int oldIndex = parentNode.getIndex(node);
int newIndex = oldIndex;
if (isLoadingChildrenFor(node.getParent()) || getBuilder().isChildrenResortingNeeded(descriptor)) {
final ArrayList<TreeNode> children = new ArrayList<TreeNode>(parentNode.getChildCount());
for (int i = 0; i < parentNode.getChildCount(); i++) {
children.add(parentNode.getChildAt(i));
}
sortChildren(node, children, true, false);
newIndex = children.indexOf(node);
}
if (oldIndex != newIndex) {
List<Object> pathsToExpand = new ArrayList<Object>();
List<Object> selectionPaths = new ArrayList<Object>();
TreeBuilderUtil.storePaths(getBuilder(), node, pathsToExpand, selectionPaths, false);
removeNodeFromParent(node, false);
myTreeModel.insertNodeInto(node, parentNode, newIndex);
TreeBuilderUtil.restorePaths(getBuilder(), pathsToExpand, selectionPaths, false);
notified = true;
}
else {
myTreeModel.nodeChanged(node);
notified = true;
}
}
else {
myTreeModel.nodeChanged(node);
notified = true;
}
}
if (!notified) {
myTreeModel.nodeChanged(node);
}
}
public DefaultTreeModel getTreeModel() {
return myTreeModel;
}
private void insertNodesInto(final ArrayList<TreeNode> toInsert, final DefaultMutableTreeNode parentNode) {
sortChildren(parentNode, toInsert, false, true);
final ArrayList<TreeNode> all = new ArrayList<TreeNode>(toInsert.size() + parentNode.getChildCount());
all.addAll(toInsert);
all.addAll(TreeUtil.childrenToArray(parentNode));
if (toInsert.size() > 0) {
sortChildren(parentNode, all, true, true);
int[] newNodeIndices = new int[toInsert.size()];
int eachNewNodeIndex = 0;
TreeMap<Integer, TreeNode> insertSet = new TreeMap<Integer, TreeNode>();
for (int i = 0; i < toInsert.size(); i++) {
TreeNode eachNewNode = toInsert.get(i);
while (all.get(eachNewNodeIndex) != eachNewNode) {
eachNewNodeIndex++;
}
newNodeIndices[i] = eachNewNodeIndex;
insertSet.put(eachNewNodeIndex, eachNewNode);
}
Iterator<Integer> indices = insertSet.keySet().iterator();
while (indices.hasNext()) {
Integer eachIndex = indices.next();
TreeNode eachNode = insertSet.get(eachIndex);
parentNode.insert((MutableTreeNode)eachNode, eachIndex);
}
myTreeModel.nodesWereInserted(parentNode, newNodeIndices);
}
else {
ArrayList<TreeNode> before = new ArrayList<TreeNode>();
before.addAll(all);
sortChildren(parentNode, all, true, false);
if (!before.equals(all)) {
processInnerChange(new Runnable() {
public void run() {
parentNode.removeAllChildren();
for (TreeNode each : all) {
parentNode.add((MutableTreeNode)each);
}
myTreeModel.nodeStructureChanged(parentNode);
}
});
}
}
}
private void sortChildren(DefaultMutableTreeNode node, ArrayList<TreeNode> children, boolean updateStamp, boolean forceSort) {
NodeDescriptor descriptor = getDescriptorFrom(node);
assert descriptor != null;
if (descriptor.getChildrenSortingStamp() >= getComparatorStamp() && !forceSort) return;
if (children.size() > 0) {
getBuilder().sortChildren(myNodeComparator, node, children);
}
if (updateStamp) {
descriptor.setChildrenSortingStamp(getComparatorStamp());
}
}
private void disposeNode(DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
if (parent instanceof DefaultMutableTreeNode) {
addToUnbuilt((DefaultMutableTreeNode)parent);
}
if (node.getChildCount() > 0) {
for (DefaultMutableTreeNode _node = (DefaultMutableTreeNode)node.getFirstChild(); _node != null; _node = _node.getNextSibling()) {
disposeNode(_node);
}
}
removeFromUpdating(node);
removeFromUnbuilt(node);
if (isLoadingNode(node)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
final Object element = getElementFromDescriptor(descriptor);
removeMapping(element, node, null);
myAutoExpandRoots.remove(element);
node.setUserObject(null);
node.removeAllChildren();
}
public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root) {
return addSubtreeToUpdate(root, null);
}
public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root, Runnable runAfterUpdate) {
Object element = getElementFor(root);
if (getTreeStructure().isAlwaysLeaf(element)) {
removeLoading(root, true);
if (runAfterUpdate != null) {
getReady(this).doWhenDone(runAfterUpdate);
}
return false;
}
if (isReleaseRequested()) {
processNodeActionsIfReady(root);
} else {
getUpdater().runAfterUpdate(runAfterUpdate);
getUpdater().addSubtreeToUpdate(root);
}
return true;
}
public boolean wasRootNodeInitialized() {
return myRootNodeWasInitialized;
}
private boolean isRootNodeBuilt() {
return myRootNodeWasInitialized && isNodeBeingBuilt(myRootNode);
}
public void select(final Object[] elements, @Nullable final Runnable onDone) {
select(elements, onDone, false);
}
public void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection) {
select(elements, onDone, addToSelection, false);
}
public void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection, boolean deferred) {
_select(elements, onDone, addToSelection, true, false, true, deferred, false, false);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure) {
_select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, true, false, false, false);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure,
final boolean scrollToVisible) {
_select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, false, false, false);
}
public void userSelect(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
boolean scroll) {
_select(elements, onDone, addToSelection, true, false, scroll, false, true, true);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure,
final boolean scrollToVisible,
final boolean deferred,
final boolean canSmartExpand,
final boolean mayQueue) {
AbstractTreeUpdater updater = getUpdater();
if (mayQueue && updater != null) {
updater.queueSelection(new SelectionRequest(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, deferred, canSmartExpand));
return;
}
boolean willAffectSelection = elements.length > 0 || (elements.length == 0 && addToSelection);
if (!willAffectSelection) {
runDone(onDone);
return;
}
final boolean oldCanProcessDeferredSelection = myCanProcessDeferredSelections;
if (!deferred && wasRootNodeInitialized() && willAffectSelection) {
myCanProcessDeferredSelections = false;
}
if (!checkDeferred(deferred, onDone)) return;
if (!deferred && oldCanProcessDeferredSelection && !myCanProcessDeferredSelections) {
getTree().clearSelection();
}
runDone(new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
final Set<Object> currentElements = getSelectedElements();
if (checkCurrentSelection && currentElements.size() > 0 && elements.length == currentElements.size()) {
boolean runSelection = false;
for (Object eachToSelect : elements) {
if (!currentElements.contains(eachToSelect)) {
runSelection = true;
break;
}
}
if (!runSelection) {
if (elements.length > 0) {
selectVisible(elements[0], onDone, true, true, scrollToVisible);
}
return;
}
}
Set<Object> toSelect = new HashSet<Object>();
myTree.clearSelection();
toSelect.addAll(Arrays.asList(elements));
if (addToSelection) {
toSelect.addAll(currentElements);
}
if (checkIfInStructure) {
final Iterator<Object> allToSelect = toSelect.iterator();
while (allToSelect.hasNext()) {
Object each = allToSelect.next();
if (!isInStructure(each)) {
allToSelect.remove();
}
}
}
final Object[] elementsToSelect = ArrayUtil.toObjectArray(toSelect);
if (wasRootNodeInitialized()) {
final int[] originalRows = myTree.getSelectionRows();
if (!addToSelection) {
myTree.clearSelection();
}
addNext(elementsToSelect, 0, new Runnable() {
public void run() {
if (getTree().isSelectionEmpty()) {
processInnerChange(new Runnable() {
public void run() {
restoreSelection(currentElements);
}
});
}
runDone(onDone);
}
}, originalRows, deferred, scrollToVisible, canSmartExpand);
}
else {
addToDeferred(elementsToSelect, onDone);
}
}
});
}
private void restoreSelection(Set<Object> selection) {
for (Object each : selection) {
DefaultMutableTreeNode node = getNodeForElement(each, false);
if (node != null && isValidForSelectionAdjusting(node)) {
addSelectionPath(getPathFor(node), false, null, null);
}
}
}
private void addToDeferred(final Object[] elementsToSelect, final Runnable onDone) {
myDeferredSelections.clear();
myDeferredSelections.add(new Runnable() {
public void run() {
select(elementsToSelect, onDone, false, true);
}
});
}
private boolean checkDeferred(boolean isDeferred, @Nullable Runnable onDone) {
if (!isDeferred || myCanProcessDeferredSelections || !wasRootNodeInitialized()) {
return true;
}
else {
runDone(onDone);
return false;
}
}
@NotNull
final Set<Object> getSelectedElements() {
final TreePath[] paths = myTree.getSelectionPaths();
Set<Object> result = new HashSet<Object>();
if (paths != null) {
for (TreePath eachPath : paths) {
if (eachPath.getLastPathComponent() instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode eachNode = (DefaultMutableTreeNode)eachPath.getLastPathComponent();
final Object eachElement = getElementFor(eachNode);
if (eachElement != null) {
result.add(eachElement);
}
}
}
}
return result;
}
private void addNext(final Object[] elements,
final int i,
@Nullable final Runnable onDone,
final int[] originalRows,
final boolean deferred,
final boolean scrollToVisible,
final boolean canSmartExpand) {
if (i >= elements.length) {
if (myTree.isSelectionEmpty()) {
myTree.setSelectionRows(originalRows);
}
runDone(onDone);
}
else {
if (!checkDeferred(deferred, onDone)) {
return;
}
doSelect(elements[i], new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
addNext(elements, i + 1, onDone, originalRows, deferred, scrollToVisible, canSmartExpand);
}
}, true, deferred, i == 0, scrollToVisible, canSmartExpand);
}
}
public void select(final Object element, @Nullable final Runnable onDone) {
select(element, onDone, false);
}
public void select(final Object element, @Nullable final Runnable onDone, boolean addToSelection) {
_select(new Object[]{element}, onDone, addToSelection, true, false);
}
private void doSelect(final Object element,
final Runnable onDone,
final boolean addToSelection,
final boolean deferred,
final boolean canBeCentered,
final boolean scrollToVisible,
boolean canSmartExpand) {
final Runnable _onDone = new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
selectVisible(element, onDone, addToSelection, canBeCentered, scrollToVisible);
}
};
_expand(element, _onDone, true, false, canSmartExpand);
}
public void scrollSelectionToVisible(@Nullable Runnable onDone, boolean shouldBeCentered) {
int[] rows = myTree.getSelectionRows();
if (rows == null || rows.length == 0) {
runDone(onDone);
return;
}
Object toSelect = null;
for (int eachRow : rows) {
TreePath path = myTree.getPathForRow(eachRow);
toSelect = getElementFor(path.getLastPathComponent());
if (toSelect != null) break;
}
if (toSelect != null) {
selectVisible(toSelect, onDone, true, shouldBeCentered, true);
}
}
private void selectVisible(Object element, final Runnable onDone, boolean addToSelection, boolean canBeCentered, final boolean scroll) {
final DefaultMutableTreeNode toSelect = getNodeForElement(element, false);
if (toSelect == null) {
runDone(onDone);
return;
}
if (getRootNode() == toSelect && !myTree.isRootVisible()) {
runDone(onDone);
return;
}
final int row = myTree.getRowForPath(new TreePath(toSelect.getPath()));
if (myUpdaterState != null) {
myUpdaterState.addSelection(element);
}
if (Registry.is("ide.tree.autoscrollToVCenter") && canBeCentered) {
runDone(new Runnable() {
public void run() {
TreeUtil.showRowCentered(myTree, row, false, scroll).doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
});
}
});
}
else {
TreeUtil.showAndSelect(myTree, row - 2, row + 2, row, -1, addToSelection, scroll).doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
});
}
}
public void expand(final Object element, @Nullable final Runnable onDone) {
expand(new Object[]{element}, onDone);
}
public void expand(final Object[] element, @Nullable final Runnable onDone) {
expand(element, onDone, false);
}
void expand(final Object element, @Nullable final Runnable onDone, boolean checkIfInStructure) {
_expand(new Object[]{element}, onDone == null ? new EmptyRunnable() : onDone, false, checkIfInStructure, false);
}
void expand(final Object[] element, @Nullable final Runnable onDone, boolean checkIfInStructure) {
_expand(element, onDone == null ? new EmptyRunnable() : onDone, false, checkIfInStructure, false);
}
void _expand(final Object[] element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
final boolean checkIfInStructure,
final boolean canSmartExpand) {
runDone(new Runnable() {
public void run() {
if (element.length == 0) {
runDone(onDone);
return;
}
if (myUpdaterState != null) {
myUpdaterState.clearExpansion();
}
final ActionCallback done = new ActionCallback(element.length);
done.doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
}).doWhenRejected(new Runnable() {
public void run() {
runDone(onDone);
}
});
expandNext(element, 0, parentsOnly, checkIfInStructure, canSmartExpand, done);
}
});
}
private void expandNext(final Object[] elements, final int index, final boolean parentsOnly, final boolean checkIfInStricture, final boolean canSmartExpand, final ActionCallback done) {
if (elements.length <= 0) {
done.setDone();
return;
}
if (index >= elements.length) {
return;
}
_expand(elements[index], new Runnable() {
public void run() {
done.setDone();
expandNext(elements, index + 1, parentsOnly, checkIfInStricture, canSmartExpand, done);
}
}, parentsOnly, checkIfInStricture, canSmartExpand);
}
public void collapseChildren(final Object element, @Nullable final Runnable onDone) {
runDone(new Runnable() {
public void run() {
final DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
getTree().collapsePath(new TreePath(node.getPath()));
runDone(onDone);
}
}
});
}
private void runDone(@Nullable Runnable done) {
if (done == null) return;
if (isYeildingNow()) {
if (!myYeildingDoneRunnables.contains(done)) {
myYeildingDoneRunnables.add(done);
}
}
else {
done.run();
}
}
private void _expand(final Object element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
boolean checkIfInStructure,
boolean canSmartExpand) {
if (checkIfInStructure && !isInStructure(element)) {
runDone(onDone);
return;
}
if (wasRootNodeInitialized()) {
List<Object> kidsToExpand = new ArrayList<Object>();
Object eachElement = element;
DefaultMutableTreeNode firstVisible = null;
while (true) {
if (!isValid(eachElement)) break;
firstVisible = getNodeForElement(eachElement, true);
if (eachElement != element || !parentsOnly) {
assert !kidsToExpand.contains(eachElement) :
"Not a valid tree structure, walking up the structure gives many entries for element=" +
eachElement +
", root=" +
getTreeStructure().getRootElement();
kidsToExpand.add(eachElement);
}
if (firstVisible != null) break;
eachElement = eachElement != null ? getTreeStructure().getParentElement(eachElement) : null;
if (eachElement == null) {
firstVisible = null;
break;
}
}
if (firstVisible == null) {
runDone(onDone);
}
else if (kidsToExpand.size() == 0) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)firstVisible.getParent();
if (parentNode != null) {
final TreePath parentPath = new TreePath(parentNode.getPath());
if (!myTree.isExpanded(parentPath)) {
expand(parentPath, canSmartExpand);
}
}
runDone(onDone);
}
else {
processExpand(firstVisible, kidsToExpand, kidsToExpand.size() - 1, onDone, canSmartExpand);
}
}
else {
deferExpansion(element, onDone, parentsOnly, canSmartExpand);
}
}
private void deferExpansion(final Object element, final Runnable onDone, final boolean parentsOnly, final boolean canSmartExpand) {
myDeferredExpansions.add(new Runnable() {
public void run() {
_expand(element, onDone, parentsOnly, false, canSmartExpand);
}
});
}
private void processExpand(final DefaultMutableTreeNode toExpand,
final List kidsToExpand,
final int expandIndex,
@NotNull final Runnable onDone,
final boolean canSmartExpand) {
final Object element = getElementFor(toExpand);
if (element == null) {
runDone(onDone);
return;
}
addNodeAction(element, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
if (node.getChildCount() > 0 && !myTree.isExpanded(new TreePath(node.getPath()))) {
if (!isAutoExpand(node)) {
expand(node, canSmartExpand);
}
}
if (expandIndex <= 0) {
runDone(onDone);
return;
}
final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false);
if (nextNode != null) {
processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand);
}
else {
runDone(onDone);
}
}
}, true);
boolean childrenToUpdate = areChildrenToBeUpdated(toExpand);
boolean expanded = myTree.isExpanded(getPathFor(toExpand));
boolean unbuilt = myUnbuiltNodes.contains(toExpand);
if (expanded) {
if (unbuilt && !childrenToUpdate) {
addSubtreeToUpdate(toExpand);
}
} else {
expand(toExpand, canSmartExpand);
}
if (!unbuilt && !childrenToUpdate) {
processNodeActionsIfReady(toExpand);
}
}
private boolean areChildrenToBeUpdated(DefaultMutableTreeNode node) {
return getUpdater().isEnqueuedToUpdate(node) || isUpdatingParent(node);
}
private String asString(DefaultMutableTreeNode node) {
if (node == null) return null;
StringBuffer children = new StringBuffer(node.toString());
children.append(" [");
for (int i = 0; i < node.getChildCount(); i++) {
children.append(node.getChildAt(i));
if (i < node.getChildCount() - 1) {
children.append(",");
}
}
children.append("]");
return children.toString();
}
@Nullable
public Object getElementFor(Object node) {
if (!(node instanceof DefaultMutableTreeNode)) return null;
return getElementFor((DefaultMutableTreeNode)node);
}
@Nullable
Object getElementFor(DefaultMutableTreeNode node) {
if (node != null) {
final Object o = node.getUserObject();
if (o instanceof NodeDescriptor) {
return getElementFromDescriptor(((NodeDescriptor)o));
}
}
return null;
}
public final boolean isNodeBeingBuilt(final TreePath path) {
return isNodeBeingBuilt(path.getLastPathComponent());
}
public final boolean isNodeBeingBuilt(Object node) {
if (isReleaseRequested()) return false;
return getParentBuiltNode(node) != null;
}
public final DefaultMutableTreeNode getParentBuiltNode(Object node) {
DefaultMutableTreeNode parent = getParentLoading(node);
if (parent != null) return parent;
if (isLoadingParent(node)) return (DefaultMutableTreeNode)node;
final boolean childrenAreNoLoadedYet = myUnbuiltNodes.contains(node);
if (childrenAreNoLoadedYet) {
if (node instanceof DefaultMutableTreeNode) {
final TreePath nodePath = new TreePath(((DefaultMutableTreeNode)node).getPath());
if (!myTree.isExpanded(nodePath)) return null;
}
return (DefaultMutableTreeNode)node;
}
return null;
}
private boolean isLoadingParent(Object node) {
if (!(node instanceof DefaultMutableTreeNode)) return false;
return isLoadedInBackground(getElementFor((DefaultMutableTreeNode)node));
}
public void setTreeStructure(final AbstractTreeStructure treeStructure) {
myTreeStructure = treeStructure;
clearUpdaterState();
}
public AbstractTreeUpdater getUpdater() {
return myUpdater;
}
public void setUpdater(final AbstractTreeUpdater updater) {
myUpdater = updater;
if (updater != null && myUpdateIfInactive) {
updater.showNotify();
}
if (myUpdater != null) {
myUpdater.setPassThroughMode(myPassthroughMode);
}
}
public DefaultMutableTreeNode getRootNode() {
return myRootNode;
}
public void setRootNode(@NotNull final DefaultMutableTreeNode rootNode) {
myRootNode = rootNode;
}
private void dropUpdaterStateIfExternalChange() {
if (!isInnerChange()) {
clearUpdaterState();
myAutoExpandRoots.clear();
}
}
void clearUpdaterState() {
myUpdaterState = null;
}
private void createMapping(Object element, DefaultMutableTreeNode node) {
if (!myElementToNodeMap.containsKey(element)) {
myElementToNodeMap.put(element, node);
}
else {
final Object value = myElementToNodeMap.get(element);
final List<DefaultMutableTreeNode> nodes;
if (value instanceof DefaultMutableTreeNode) {
nodes = new ArrayList<DefaultMutableTreeNode>();
nodes.add((DefaultMutableTreeNode)value);
myElementToNodeMap.put(element, nodes);
}
else {
nodes = (List<DefaultMutableTreeNode>)value;
}
nodes.add(node);
}
}
private void removeMapping(Object element, DefaultMutableTreeNode node, @Nullable Object elementToPutNodeActionsFor) {
final Object value = myElementToNodeMap.get(element);
if (value != null) {
if (value instanceof DefaultMutableTreeNode) {
if (value.equals(node)) {
myElementToNodeMap.remove(element);
}
}
else {
List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
final boolean reallyRemoved = nodes.remove(node);
if (reallyRemoved) {
if (nodes.isEmpty()) {
myElementToNodeMap.remove(element);
}
}
}
}
remapNodeActions(element, elementToPutNodeActionsFor);
}
private void remapNodeActions(Object element, Object elementToPutNodeActionsFor) {
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeActions);
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeChildrenActions);
}
private void _remapNodeActions(Object element, Object elementToPutNodeActionsFor, final Map<Object, List<NodeAction>> nodeActions) {
final List<NodeAction> actions = nodeActions.get(element);
nodeActions.remove(element);
if (elementToPutNodeActionsFor != null && actions != null) {
nodeActions.put(elementToPutNodeActionsFor, actions);
}
}
private DefaultMutableTreeNode getFirstNode(Object element) {
return findNode(element, 0);
}
private DefaultMutableTreeNode findNode(final Object element, int startIndex) {
final Object value = getBuilder().findNodeByElement(element);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
return startIndex == 0 ? (DefaultMutableTreeNode)value : null;
}
final List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
return startIndex < nodes.size() ? nodes.get(startIndex) : null;
}
protected Object findNodeByElement(Object element) {
if (myElementToNodeMap.containsKey(element)) {
return myElementToNodeMap.get(element);
}
try {
TREE_NODE_WRAPPER.setValue(element);
return myElementToNodeMap.get(TREE_NODE_WRAPPER);
}
finally {
TREE_NODE_WRAPPER.setValue(null);
}
}
private DefaultMutableTreeNode findNodeForChildElement(DefaultMutableTreeNode parentNode, Object element) {
final Object value = myElementToNodeMap.get(element);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode elementNode = (DefaultMutableTreeNode)value;
return parentNode.equals(elementNode.getParent()) ? elementNode : null;
}
final List<DefaultMutableTreeNode> allNodesForElement = (List<DefaultMutableTreeNode>)value;
for (final DefaultMutableTreeNode elementNode : allNodesForElement) {
if (parentNode.equals(elementNode.getParent())) {
return elementNode;
}
}
return null;
}
public void cancelBackgroundLoading() {
if (myWorker != null) {
myWorker.cancelTasks();
clearWorkerTasks();
}
clearNodeActions();
}
private void addNodeAction(Object element, NodeAction action, boolean shouldChildrenBeReady) {
_addNodeAction(element, action, myNodeActions);
if (shouldChildrenBeReady) {
_addNodeAction(element, action, myNodeChildrenActions);
}
}
private void _addNodeAction(Object element, NodeAction action, Map<Object, List<NodeAction>> map) {
maybeSetBusyAndScheduleWaiterForReady(true);
List<NodeAction> list = map.get(element);
if (list == null) {
list = new ArrayList<NodeAction>();
map.put(element, list);
}
list.add(action);
}
private void cleanUpNow() {
if (isReleaseRequested()) return;
final UpdaterTreeState state = new UpdaterTreeState(this);
myTree.collapsePath(new TreePath(myTree.getModel().getRoot()));
myTree.clearSelection();
getRootNode().removeAllChildren();
myRootNodeWasInitialized = false;
clearNodeActions();
myElementToNodeMap.clear();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myLoadedInBackground.clear();
myUnbuiltNodes.clear();
myUpdateFromRootRequested = true;
if (myWorker != null) {
Disposer.dispose(myWorker);
myWorker = null;
}
myTree.invalidate();
state.restore(null);
}
public AbstractTreeUi setClearOnHideDelay(final long clearOnHideDelay) {
myClearOnHideDelay = clearOnHideDelay;
return this;
}
public void setJantorPollPeriod(final long time) {
myJanitorPollPeriod = time;
}
public void setCheckStructure(final boolean checkStructure) {
myCheckStructure = checkStructure;
}
private class MySelectionListener implements TreeSelectionListener {
public void valueChanged(final TreeSelectionEvent e) {
dropUpdaterStateIfExternalChange();
}
}
private class MyExpansionListener implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent event) {
dropUpdaterStateIfExternalChange();
TreePath path = event.getPath();
if (myRequestedExpand != null && !myRequestedExpand.equals(path)) return;
//myRequestedExpand = null;
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (!myUnbuiltNodes.contains(node)) {
removeLoading(node, false);
Set<DefaultMutableTreeNode> childrenToUpdate = new HashSet<DefaultMutableTreeNode>();
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode each = (DefaultMutableTreeNode)node.getChildAt(i);
if (myUnbuiltNodes.contains(each)) {
makeLoadingOrLeafIfNoChildren(each);
childrenToUpdate.add(each);
}
}
if (childrenToUpdate.size() > 0) {
for (DefaultMutableTreeNode each : childrenToUpdate) {
maybeUpdateSubtreeToUpdate(each);
}
}
}
else {
getBuilder().expandNodeChildren(node);
}
processSmartExpand(node, canSmartExpand(node, true), false);
processNodeActionsIfReady(node);
}
public void treeCollapsed(TreeExpansionEvent e) {
dropUpdaterStateIfExternalChange();
final TreePath path = e.getPath();
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
TreePath pathToSelect = null;
if (isSelectionInside(node)) {
pathToSelect = new TreePath(node.getPath());
}
NodeDescriptor descriptor = getDescriptorFrom(node);
if (getBuilder().isDisposeOnCollapsing(descriptor)) {
runDone(new Runnable() {
public void run() {
if (isDisposed(node)) return;
TreePath nodePath = new TreePath(node.getPath());
if (myTree.isExpanded(nodePath)) return;
removeChildren(node);
makeLoadingOrLeafIfNoChildren(node);
}
});
if (node.equals(getRootNode())) {
if (myTree.isRootVisible()) {
//todo kirillk to investigate -- should be done by standard selction move
//addSelectionPath(new TreePath(getRootNode().getPath()), true, Condition.FALSE);
}
}
else {
myTreeModel.reload(node);
}
}
if (pathToSelect != null && myTree.isSelectionEmpty()) {
addSelectionPath(pathToSelect, true, Condition.FALSE, null);
}
}
private void removeChildren(DefaultMutableTreeNode node) {
EnumerationCopy copy = new EnumerationCopy(node.children());
while (copy.hasMoreElements()) {
disposeNode((DefaultMutableTreeNode)copy.nextElement());
}
node.removeAllChildren();
myTreeModel.nodeStructureChanged(node);
}
}
private void maybeUpdateSubtreeToUpdate(final DefaultMutableTreeNode subtreeRoot) {
if (!myUnbuiltNodes.contains(subtreeRoot)) return;
TreePath path = getPathFor(subtreeRoot);
if (myTree.getRowForPath(path) == -1) return;
DefaultMutableTreeNode parent = getParentBuiltNode(subtreeRoot);
if (parent == null) {
addSubtreeToUpdate(subtreeRoot);
} else if (parent != subtreeRoot) {
addNodeAction(getElementFor(subtreeRoot), new NodeAction() {
public void onReady(DefaultMutableTreeNode parent) {
maybeUpdateSubtreeToUpdate(subtreeRoot);
}
}, true);
}
}
private boolean isSelectionInside(DefaultMutableTreeNode parent) {
TreePath path = new TreePath(myTreeModel.getPathToRoot(parent));
TreePath[] paths = myTree.getSelectionPaths();
if (paths == null) return false;
for (TreePath path1 : paths) {
if (path.isDescendant(path1)) return true;
}
return false;
}
public boolean isInStructure(@Nullable Object element) {
Object eachParent = element;
while (eachParent != null) {
if (getTreeStructure().getRootElement().equals(eachParent)) return true;
eachParent = getTreeStructure().getParentElement(eachParent);
}
return false;
}
interface NodeAction {
void onReady(DefaultMutableTreeNode node);
}
public void setCanYield(final boolean canYield) {
myCanYield = canYield;
}
public Collection<TreeUpdatePass> getYeildingPasses() {
return myYeildingPasses;
}
public boolean isBuilt(Object element) {
if (!myElementToNodeMap.containsKey(element)) return false;
final Object node = myElementToNodeMap.get(element);
return !myUnbuiltNodes.contains(node);
}
static class LoadedChildren {
private List myElements;
private Map<Object, NodeDescriptor> myDescriptors = new HashMap<Object, NodeDescriptor>();
private Map<NodeDescriptor, Boolean> myChanges = new HashMap<NodeDescriptor, Boolean>();
LoadedChildren(Object[] elements) {
myElements = Arrays.asList(elements != null ? elements : ArrayUtil.EMPTY_OBJECT_ARRAY);
}
void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) {
assert myElements.contains(element);
myDescriptors.put(element, descriptor);
myChanges.put(descriptor, isChanged);
}
List getElements() {
return myElements;
}
NodeDescriptor getDescriptor(Object element) {
return myDescriptors.get(element);
}
@Override
public String toString() {
return Arrays.asList(myElements) + "->" + myChanges;
}
public boolean isUpdated(Object element) {
NodeDescriptor desc = getDescriptor(element);
return myChanges.get(desc);
}
}
UpdaterTreeState getUpdaterState() {
return myUpdaterState;
}
private ActionCallback addReadyCallback(Object requestor) {
synchronized (myReadyCallbacks) {
ActionCallback cb = myReadyCallbacks.get(requestor);
if (cb == null) {
cb = new ActionCallback();
myReadyCallbacks.put(requestor, cb);
}
return cb;
}
}
private ActionCallback[] getReadyCallbacks(boolean clear) {
synchronized (myReadyCallbacks) {
ActionCallback[] result = myReadyCallbacks.values().toArray(new ActionCallback[myReadyCallbacks.size()]);
if (clear) {
myReadyCallbacks.clear();
}
return result;
}
}
private long getComparatorStamp() {
if (myNodeDescriptorComparator instanceof NodeDescriptor.NodeComparator) {
long currentComparatorStamp = ((NodeDescriptor.NodeComparator)myNodeDescriptorComparator).getStamp();
if (currentComparatorStamp > myLastComparatorStamp) {
myOwnComparatorStamp = Math.max(myOwnComparatorStamp, currentComparatorStamp) + 1;
}
myLastComparatorStamp = currentComparatorStamp;
return Math.max(currentComparatorStamp, myOwnComparatorStamp);
}
else {
return myOwnComparatorStamp;
}
}
public void incComparatorStamp() {
myOwnComparatorStamp = getComparatorStamp() + 1;
}
public static class UpdateInfo {
NodeDescriptor myDescriptor;
TreeUpdatePass myPass;
boolean myCanSmartExpand;
boolean myWasExpanded;
boolean myForceUpdate;
boolean myDescriptorIsUpToDate;
public UpdateInfo(NodeDescriptor descriptor,
TreeUpdatePass pass,
boolean canSmartExpand,
boolean wasExpanded,
boolean forceUpdate,
boolean descriptorIsUpToDate) {
myDescriptor = descriptor;
myPass = pass;
myCanSmartExpand = canSmartExpand;
myWasExpanded = wasExpanded;
myForceUpdate = forceUpdate;
myDescriptorIsUpToDate = descriptorIsUpToDate;
}
synchronized NodeDescriptor getDescriptor() {
return myDescriptor;
}
synchronized TreeUpdatePass getPass() {
return myPass;
}
synchronized boolean isCanSmartExpand() {
return myCanSmartExpand;
}
synchronized boolean isWasExpanded() {
return myWasExpanded;
}
synchronized boolean isForceUpdate() {
return myForceUpdate;
}
synchronized boolean isDescriptorIsUpToDate() {
return myDescriptorIsUpToDate;
}
public synchronized void apply(UpdateInfo updateInfo) {
myDescriptor = updateInfo.myDescriptor;
myPass = updateInfo.myPass;
myCanSmartExpand = updateInfo.myCanSmartExpand;
myWasExpanded = updateInfo.myWasExpanded;
myForceUpdate = updateInfo.myForceUpdate;
myDescriptorIsUpToDate = updateInfo.myDescriptorIsUpToDate;
}
public String toString() {
return "UpdateInfo: desc=" + myDescriptor + " pass=" + myPass + " canSmartExpand=" + myCanSmartExpand + " wasExpanded=" + myWasExpanded + " forceUpdate=" + myForceUpdate + " descriptorUpToDate=" + myDescriptorIsUpToDate;
}
}
public void setPassthroughMode(boolean passthrough) {
myPassthroughMode = passthrough;
AbstractTreeUpdater updater = getUpdater();
if (updater != null) {
updater.setPassThroughMode(myPassthroughMode);
}
if (!isUnitTestingMode() && passthrough) {
// TODO: this assertion should be restored back as soon as possible [JamTreeTableView should be rewritten, etc]
//LOG.error("Pass-through mode for TreeUi is allowed only for unit test mode");
}
}
public boolean isPassthroughMode() {
return myPassthroughMode;
}
private boolean isUnitTestingMode() {
Application app = ApplicationManager.getApplication();
return app != null && app.isUnitTestMode();
}
private void addModelListenerToDianoseAccessOutsideEdt() {
myTreeModel.addTreeModelListener(new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeNodesInserted(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeNodesRemoved(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeStructureChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
});
}
}
| platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.treeView;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.ui.LoadingNode;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Time;
import com.intellij.util.concurrency.WorkerThread;
import com.intellij.util.containers.HashSet;
import com.intellij.util.enumeration.EnumerationCopy;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.security.AccessControlException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
public class AbstractTreeUi {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.treeView.AbstractTreeBuilder");
protected JTree myTree;// protected for TestNG
@SuppressWarnings({"WeakerAccess"}) protected DefaultTreeModel myTreeModel;
private AbstractTreeStructure myTreeStructure;
private AbstractTreeUpdater myUpdater;
private Comparator<NodeDescriptor> myNodeDescriptorComparator;
private final Comparator<TreeNode> myNodeComparator = new Comparator<TreeNode>() {
public int compare(TreeNode n1, TreeNode n2) {
if (isLoadingNode(n1) || isLoadingNode(n2)) return 0;
NodeDescriptor nodeDescriptor1 = getDescriptorFrom(((DefaultMutableTreeNode)n1));
NodeDescriptor nodeDescriptor2 = getDescriptorFrom(((DefaultMutableTreeNode)n2));
return myNodeDescriptorComparator != null
? myNodeDescriptorComparator.compare(nodeDescriptor1, nodeDescriptor2)
: nodeDescriptor1.getIndex() - nodeDescriptor2.getIndex();
}
};
long myOwnComparatorStamp;
long myLastComparatorStamp;
private DefaultMutableTreeNode myRootNode;
private final HashMap<Object, Object> myElementToNodeMap = new HashMap<Object, Object>();
private final HashSet<DefaultMutableTreeNode> myUnbuiltNodes = new HashSet<DefaultMutableTreeNode>();
private TreeExpansionListener myExpansionListener;
private MySelectionListener mySelectionListener;
private WorkerThread myWorker = null;
private final Set<Runnable> myActiveWorkerTasks = new HashSet<Runnable>();
private ProgressIndicator myProgress;
private static final int WAIT_CURSOR_DELAY = 100;
private AbstractTreeNode<Object> TREE_NODE_WRAPPER;
private boolean myRootNodeWasInitialized = false;
private final Map<Object, List<NodeAction>> myNodeActions = new HashMap<Object, List<NodeAction>>();
private boolean myUpdateFromRootRequested;
private boolean myWasEverShown;
private boolean myUpdateIfInactive;
private final Map<Object, UpdateInfo> myLoadedInBackground = new HashMap<Object, UpdateInfo>();
private final Map<Object, List<NodeAction>> myNodeChildrenActions = new HashMap<Object, List<NodeAction>>();
private long myClearOnHideDelay = -1;
private final Map<AbstractTreeUi, Long> ourUi2Countdown = Collections.synchronizedMap(new WeakHashMap<AbstractTreeUi, Long>());
private final Set<Runnable> myDeferredSelections = new HashSet<Runnable>();
private final Set<Runnable> myDeferredExpansions = new HashSet<Runnable>();
private boolean myCanProcessDeferredSelections;
private UpdaterTreeState myUpdaterState;
private AbstractTreeBuilder myBuilder;
private boolean myReleaseRequested;
private final Set<DefaultMutableTreeNode> myUpdatingChildren = new HashSet<DefaultMutableTreeNode>();
private long myJanitorPollPeriod = Time.SECOND * 10;
private boolean myCheckStructure = false;
private boolean myCanYield = false;
private final List<TreeUpdatePass> myYeildingPasses = new ArrayList<TreeUpdatePass>();
private boolean myYeildingNow;
private final Set<DefaultMutableTreeNode> myPendingNodeActions = new HashSet<DefaultMutableTreeNode>();
private final Set<Runnable> myYeildingDoneRunnables = new HashSet<Runnable>();
private final Alarm myBusyAlarm = new Alarm();
private final Runnable myWaiterForReady = new Runnable() {
public void run() {
maybeSetBusyAndScheduleWaiterForReady(false);
}
};
private final RegistryValue myYeildingUpdate = Registry.get("ide.tree.yeildingUiUpdate");
private final RegistryValue myShowBusyIndicator = Registry.get("ide.tree.showBusyIndicator");
private final RegistryValue myWaitForReadyTime = Registry.get("ide.tree.waitForReadyTimout");
private boolean myWasEverIndexNotReady;
private boolean myShowing;
private FocusAdapter myFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
maybeReady();
}
};
private Set<DefaultMutableTreeNode> myNotForSmartExpand = new HashSet<DefaultMutableTreeNode>();
private TreePath myRequestedExpand;
private ActionCallback myInitialized = new ActionCallback();
private Map<Object, ActionCallback> myReadyCallbacks = new WeakHashMap<Object, ActionCallback>();
private boolean myPassthroughMode = false;
private Set<Object> myAutoExpandRoots = new HashSet<Object>();
private final RegistryValue myAutoExpandDepth = Registry.get("ide.tree.autoExpandMaxDepth");
private Set<DefaultMutableTreeNode> myWillBeExpaned = new HashSet<DefaultMutableTreeNode>();
private SimpleTimerTask myCleanupTask;
protected void init(AbstractTreeBuilder builder,
JTree tree,
DefaultTreeModel treeModel,
AbstractTreeStructure treeStructure,
@Nullable Comparator<NodeDescriptor> comparator,
boolean updateIfInactive) {
myBuilder = builder;
myTree = tree;
myTreeModel = treeModel;
addModelListenerToDianoseAccessOutsideEdt();
TREE_NODE_WRAPPER = getBuilder().createSearchingTreeNodeWrapper();
myTree.setModel(myTreeModel);
setRootNode((DefaultMutableTreeNode)treeModel.getRoot());
setTreeStructure(treeStructure);
myNodeDescriptorComparator = comparator;
myUpdateIfInactive = updateIfInactive;
myExpansionListener = new MyExpansionListener();
myTree.addTreeExpansionListener(myExpansionListener);
mySelectionListener = new MySelectionListener();
myTree.addTreeSelectionListener(mySelectionListener);
setUpdater(getBuilder().createUpdater());
myProgress = getBuilder().createProgressIndicator();
Disposer.register(getBuilder(), getUpdater());
final UiNotifyConnector uiNotify = new UiNotifyConnector(tree, new Activatable() {
public void showNotify() {
myShowing = true;
myWasEverShown = true;
if (!isReleaseRequested()) {
activate(true);
}
}
public void hideNotify() {
myShowing = false;
if (!validateReleaseRequested()) {
deactivate();
}
}
});
Disposer.register(getBuilder(), uiNotify);
myTree.addFocusListener(myFocusListener);
}
boolean isNodeActionsPending() {
return !myNodeActions.isEmpty() || !myNodeChildrenActions.isEmpty();
}
private void clearNodeActions() {
myNodeActions.clear();
myNodeChildrenActions.clear();
}
private void maybeSetBusyAndScheduleWaiterForReady(boolean forcedBusy) {
if (!myShowBusyIndicator.asBoolean() || !canYield()) return;
if (myTree instanceof com.intellij.ui.treeStructure.Tree) {
final com.intellij.ui.treeStructure.Tree tree = (Tree)myTree;
final boolean isBusy = !isReady() || forcedBusy;
if (isBusy && tree.isShowing()) {
tree.setPaintBusy(true);
myBusyAlarm.cancelAllRequests();
myBusyAlarm.addRequest(myWaiterForReady, myWaitForReadyTime.asInteger());
}
else {
tree.setPaintBusy(false);
}
}
}
private void cleanUpAll() {
final long now = System.currentTimeMillis();
final AbstractTreeUi[] uis = ourUi2Countdown.keySet().toArray(new AbstractTreeUi[ourUi2Countdown.size()]);
for (AbstractTreeUi eachUi : uis) {
if (eachUi == null) continue;
final Long timeToCleanup = ourUi2Countdown.get(eachUi);
if (timeToCleanup == null) continue;
if (now >= timeToCleanup.longValue()) {
ourUi2Countdown.remove(eachUi);
Runnable runnable = new Runnable() {
public void run() {
myCleanupTask = null;
getBuilder().cleanUp();
}
};
if (isPassthroughMode()) {
runnable.run();
} else {
UIUtil.invokeAndWaitIfNeeded(runnable);
}
}
}
}
protected void doCleanUp() {
Runnable cleanup = new Runnable() {
public void run() {
if (!isReleaseRequested()) {
cleanUpNow();
}
}
};
if (isPassthroughMode()) {
cleanup.run();
} else {
UIUtil.invokeLaterIfNeeded(cleanup);
}
}
private ActionCallback invokeLaterIfNeeded(@NotNull final Runnable runnable) {
final ActionCallback result = new ActionCallback();
Runnable actual = new Runnable() {
public void run() {
runnable.run();
result.setDone();
}
};
if (isPassthroughMode() || (!isEdt() && !isTreeShowing())) {
actual.run();
} else {
UIUtil.invokeLaterIfNeeded(actual);
}
return result;
}
public void activate(boolean byShowing) {
cancelCurrentCleanupTask();
myCanProcessDeferredSelections = true;
ourUi2Countdown.remove(this);
if (!myWasEverShown || myUpdateFromRootRequested || myUpdateIfInactive) {
getBuilder().updateFromRoot();
}
getUpdater().showNotify();
myWasEverShown |= byShowing;
}
private void cancelCurrentCleanupTask() {
if (myCleanupTask != null) {
myCleanupTask.cancel();
myCleanupTask = null;
}
}
public void deactivate() {
getUpdater().hideNotify();
myBusyAlarm.cancelAllRequests();
if (!myWasEverShown) return;
if (isNodeActionsPending()) {
cancelBackgroundLoading();
myUpdateFromRootRequested = true;
}
if (getClearOnHideDelay() >= 0) {
ourUi2Countdown.put(this, System.currentTimeMillis() + getClearOnHideDelay());
sheduleCleanUpAll();
}
}
private void sheduleCleanUpAll() {
cancelCurrentCleanupTask();
myCleanupTask = SimpleTimer.getInstance().setUp(new Runnable() {
public void run() {
cleanUpAll();
}
}, getClearOnHideDelay());
}
public void requestRelease() {
if (isReleaseRequested()) return;
assertIsDispatchThread();
myReleaseRequested = true;
getUpdater().requestRelease();
maybeReady();
}
private void releaseNow() {
myTree.removeTreeExpansionListener(myExpansionListener);
myTree.removeTreeSelectionListener(mySelectionListener);
myTree.removeFocusListener(myFocusListener);
disposeNode(getRootNode());
myElementToNodeMap.clear();
getUpdater().cancelAllRequests();
if (myWorker != null) {
myWorker.dispose(true);
clearWorkerTasks();
}
TREE_NODE_WRAPPER.setValue(null);
if (myProgress != null) {
myProgress.cancel();
}
cancelCurrentCleanupTask();
myTree = null;
setUpdater(null);
myWorker = null;
myTreeStructure = null;
myBuilder.releaseUi();
myBuilder = null;
clearNodeActions();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myYeildingDoneRunnables.clear();
}
public boolean isReleaseRequested() {
return myReleaseRequested;
}
public boolean validateReleaseRequested() {
if (isReleaseRequested()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
maybeReady();
}
});
return true;
} else {
return false;
}
}
public boolean isReleased() {
return myBuilder == null;
}
protected void doExpandNodeChildren(final DefaultMutableTreeNode node) {
if (!myUnbuiltNodes.contains(node)) return;
if (isLoadedInBackground(getElementFor(node))) return;
if (!isReleaseRequested()) {
getTreeStructure().commit();
addSubtreeToUpdate(node);
getUpdater().performUpdate();
} else {
processNodeActionsIfReady(node);
}
}
public final AbstractTreeStructure getTreeStructure() {
return myTreeStructure;
}
public final JTree getTree() {
return myTree;
}
@Nullable
private NodeDescriptor getDescriptorFrom(DefaultMutableTreeNode node) {
return (NodeDescriptor)node.getUserObject();
}
@Nullable
public final DefaultMutableTreeNode getNodeForElement(Object element, final boolean validateAgainstStructure) {
DefaultMutableTreeNode result = null;
if (validateAgainstStructure) {
int index = 0;
while (true) {
final DefaultMutableTreeNode node = findNode(element, index);
if (node == null) break;
if (isNodeValidForElement(element, node)) {
result = node;
break;
}
index++;
}
}
else {
result = getFirstNode(element);
}
if (result != null && !isNodeInStructure(result)) {
disposeNode(result);
result = null;
}
return result;
}
private boolean isNodeInStructure(DefaultMutableTreeNode node) {
return TreeUtil.isAncestor(getRootNode(), node) && getRootNode() == myTreeModel.getRoot();
}
private boolean isNodeValidForElement(final Object element, final DefaultMutableTreeNode node) {
return isSameHierarchy(element, node) || isValidChildOfParent(element, node);
}
private boolean isValidChildOfParent(final Object element, final DefaultMutableTreeNode node) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
final Object parentElement = getElementFor(parent);
if (!isInStructure(parentElement)) return false;
if (parent instanceof ElementNode) {
return ((ElementNode)parent).isValidChild(element);
}
else {
for (int i = 0; i < parent.getChildCount(); i++) {
final TreeNode child = parent.getChildAt(i);
final Object eachElement = getElementFor(child);
if (element.equals(eachElement)) return true;
}
}
return false;
}
private boolean isSameHierarchy(Object eachParent, DefaultMutableTreeNode eachParentNode) {
boolean valid = true;
while (true) {
if (eachParent == null) {
valid = eachParentNode == null;
break;
}
if (!eachParent.equals(getElementFor(eachParentNode))) {
valid = false;
break;
}
eachParent = getTreeStructure().getParentElement(eachParent);
eachParentNode = (DefaultMutableTreeNode)eachParentNode.getParent();
}
return valid;
}
public final DefaultMutableTreeNode getNodeForPath(Object[] path) {
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node == null) {
break;
}
}
return node;
}
public final void buildNodeForElement(Object element) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null) {
final java.util.List<Object> elements = new ArrayList<Object>();
while (true) {
element = getTreeStructure().getParentElement(element);
if (element == null) {
break;
}
elements.add(0, element);
}
for (final Object element1 : elements) {
node = getNodeForElement(element1, false);
if (node != null) {
expand(node, true);
}
}
}
}
public final void buildNodeForPath(Object[] path) {
getUpdater().performUpdate();
DefaultMutableTreeNode node = null;
for (final Object pathElement : path) {
node = node == null ? getFirstNode(pathElement) : findNodeForChildElement(node, pathElement);
if (node != null && node != path[path.length - 1]) {
expand(node, true);
}
}
}
public final void setNodeDescriptorComparator(Comparator<NodeDescriptor> nodeDescriptorComparator) {
myNodeDescriptorComparator = nodeDescriptorComparator;
myLastComparatorStamp = -1;
getBuilder().queueUpdateFrom(getTreeStructure().getRootElement(), true);
}
protected AbstractTreeBuilder getBuilder() {
return myBuilder;
}
protected final void initRootNode() {
if (myUpdateIfInactive) {
activate(false);
}
else {
myUpdateFromRootRequested = true;
}
}
private boolean initRootNodeNowIfNeeded(final TreeUpdatePass pass) {
boolean wasCleanedUp = false;
if (myRootNodeWasInitialized) {
Object root = getTreeStructure().getRootElement();
assert root != null : "Root element cannot be null";
Object currentRoot = getElementFor(myRootNode);
if (Comparing.equal(root, currentRoot)) return false;
Object rootAgain = getTreeStructure().getRootElement();
if (root != rootAgain && !root.equals(rootAgain)) {
assert false : "getRootElement() if called twice must return either root1 == root2 or root1.equals(root2)";
}
cleanUpNow();
wasCleanedUp = true;
}
myRootNodeWasInitialized = true;
final Object rootElement = getTreeStructure().getRootElement();
addNodeAction(rootElement, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
processDeferredActions();
}
}, false);
final Ref<NodeDescriptor> rootDescriptor = new Ref<NodeDescriptor>(null);
final boolean bgLoading = getTreeStructure().isToBuildChildrenInBackground(rootElement);
Runnable build = new Runnable() {
public void run() {
rootDescriptor.set(getTreeStructure().createDescriptor(rootElement, null));
getRootNode().setUserObject(rootDescriptor.get());
update(rootDescriptor.get(), true);
}
};
Runnable update = new Runnable() {
public void run() {
if (getElementFromDescriptor(rootDescriptor.get()) != null) {
createMapping(getElementFromDescriptor(rootDescriptor.get()), getRootNode());
}
insertLoadingNode(getRootNode(), true);
boolean willUpdate = false;
if (isAutoExpand(rootDescriptor.get())) {
willUpdate = myUnbuiltNodes.contains(getRootNode());
expand(getRootNode(), true);
}
if (!willUpdate) {
updateNodeChildren(getRootNode(), pass, null, false, false, false, true);
}
if (getRootNode().getChildCount() == 0) {
myTreeModel.nodeChanged(getRootNode());
}
}
};
if (bgLoading) {
queueToBackground(build, update);
}
else {
build.run();
update.run();
}
return wasCleanedUp;
}
private boolean isAutoExpand(NodeDescriptor descriptor) {
return isAutoExpand(descriptor, true);
}
private boolean isAutoExpand(NodeDescriptor descriptor, boolean validate) {
if (descriptor == null) return false;
boolean autoExpand = getBuilder().isAutoExpandNode(descriptor);
Object element = getElementFromDescriptor(descriptor);
if (validate) {
autoExpand = validateAutoExpand(autoExpand, element);
}
if (!autoExpand && !myTree.isRootVisible()) {
if (element != null && element.equals(getTreeStructure().getRootElement())) return true;
}
return autoExpand;
}
private boolean validateAutoExpand(boolean autoExpand, Object element) {
if (autoExpand) {
int distance = getDistanceToAutoExpandRoot(element);
if (distance < 0) {
myAutoExpandRoots.add(element);
} else {
if (distance >= myAutoExpandDepth.asInteger() - 1) {
autoExpand = false;
}
}
if (autoExpand) {
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (isInVisibleAutoExpandChain(node)) {
autoExpand = true;
} else {
autoExpand = false;
}
}
}
return autoExpand;
}
private boolean isInVisibleAutoExpandChain(DefaultMutableTreeNode child) {
TreeNode eachParent = child;
while (eachParent != null) {
if (myRootNode == eachParent) return true;
NodeDescriptor eachDescriptor = getDescriptorFrom((DefaultMutableTreeNode)eachParent);
if (!isAutoExpand(eachDescriptor, false)) {
TreePath path = getPathFor(eachParent);
if (myWillBeExpaned.contains(path.getLastPathComponent()) || (myTree.isExpanded(path) && myTree.isVisible(path))) {
return true;
} else {
return false;
}
}
eachParent = eachParent.getParent();
}
return false;
}
private int getDistanceToAutoExpandRoot(Object element) {
int distance = 0;
Object eachParent = element;
while (eachParent != null) {
if (myAutoExpandRoots.contains(eachParent)) break;
eachParent = getTreeStructure().getParentElement(eachParent);
distance++;
}
return eachParent != null ? distance : -1;
}
private boolean isAutoExpand(DefaultMutableTreeNode node) {
return isAutoExpand(getDescriptorFrom(node));
}
private AsyncResult<Boolean> update(final NodeDescriptor nodeDescriptor, boolean now) {
final AsyncResult<Boolean> result = new AsyncResult<Boolean>();
if (now || isPassthroughMode()) {
return new AsyncResult<Boolean>().setDone(_update(nodeDescriptor));
}
Object element = getElementFromDescriptor(nodeDescriptor);
boolean bgLoading = getTreeStructure().isToBuildChildrenInBackground(element);
boolean edt = isEdt();
if (bgLoading) {
if (edt) {
final Ref<Boolean> changes = new Ref<Boolean>(false);
queueToBackground(new Runnable() {
public void run() {
changes.set(_update(nodeDescriptor));
}
}, new Runnable() {
public void run() {
result.setDone(changes.get());
}
});
}
else {
result.setDone(_update(nodeDescriptor));
}
}
else {
if (edt || !myWasEverShown) {
result.setDone(_update(nodeDescriptor));
}
else {
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
if (!validateReleaseRequested()) {
result.setDone(_update(nodeDescriptor));
}
else {
result.setRejected();
}
}
});
}
}
result.doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
if (changes) {
final long updateStamp = nodeDescriptor.getUpdateCount();
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
Object element = nodeDescriptor.getElement();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
TreePath path = getPathFor(node);
if (path != null && myTree.isVisible(path)) {
updateNodeImageAndPosition(node, false);
}
}
}
});
}
}
});
return result;
}
private boolean _update(NodeDescriptor nodeDescriptor) {
try {
nodeDescriptor.setUpdateCount(nodeDescriptor.getUpdateCount() + 1);
return getBuilder().updateNodeDescriptor(nodeDescriptor);
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady();
return false;
}
}
private void assertIsDispatchThread() {
if (isPassthroughMode()) return;
if (isTreeShowing() && !isEdt()) {
LOG.error("Must be in event-dispatch thread");
}
}
private boolean isEdt() {
return SwingUtilities.isEventDispatchThread();
}
private boolean isTreeShowing() {
return myShowing;
}
private void assertNotDispatchThread() {
if (isPassthroughMode()) return;
if (isEdt()) {
LOG.error("Must not be in event-dispatch thread");
}
}
private void processDeferredActions() {
processDeferredActions(myDeferredSelections);
processDeferredActions(myDeferredExpansions);
}
private void processDeferredActions(Set<Runnable> actions) {
final Runnable[] runnables = actions.toArray(new Runnable[actions.size()]);
actions.clear();
for (Runnable runnable : runnables) {
runnable.run();
}
}
//todo: to make real callback
public ActionCallback queueUpdate(Object element) {
AbstractTreeUpdater updater = getUpdater();
if (updater == null) {
return new ActionCallback.Rejected();
}
final ActionCallback result = new ActionCallback();
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
addSubtreeToUpdate(node);
}
else {
addSubtreeToUpdate(getRootNode());
}
updater.runAfterUpdate(new Runnable() {
public void run() {
result.setDone();
}
});
return result;
}
public void doUpdateFromRoot() {
updateSubtree(getRootNode(), false);
}
public ActionCallback doUpdateFromRootCB() {
final ActionCallback cb = new ActionCallback();
getUpdater().runAfterUpdate(new Runnable() {
public void run() {
cb.setDone();
}
});
updateSubtree(getRootNode(), false);
return cb;
}
public final void updateSubtree(DefaultMutableTreeNode node, boolean canSmartExpand) {
updateSubtree(new TreeUpdatePass(node), canSmartExpand);
}
public final void updateSubtree(TreeUpdatePass pass, boolean canSmartExpand) {
if (getUpdater() != null) {
getUpdater().addSubtreeToUpdate(pass);
}
else {
updateSubtreeNow(pass, canSmartExpand);
}
}
final void updateSubtreeNow(TreeUpdatePass pass, boolean canSmartExpand) {
maybeSetBusyAndScheduleWaiterForReady(true);
boolean consumed = initRootNodeNowIfNeeded(pass);
if (consumed) return;
final DefaultMutableTreeNode node = pass.getNode();
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
setUpdaterState(new UpdaterTreeState(this)).beforeSubtreeUpdate();
boolean forceUpdate = true;
TreePath path = getPathFor(node);
boolean invisible = !myTree.isExpanded(path) && (path.getParentPath() == null || !myTree.isExpanded(path.getParentPath()));
if (invisible && myUnbuiltNodes.contains(node)) {
forceUpdate = false;
}
updateNodeChildren(node, pass, null, false, canSmartExpand, forceUpdate, false);
}
private boolean isToBuildInBackground(NodeDescriptor descriptor) {
return getTreeStructure().isToBuildChildrenInBackground(getBuilder().getTreeStructureElement(descriptor));
}
@NotNull
UpdaterTreeState setUpdaterState(UpdaterTreeState state) {
if (myUpdaterState != null && myUpdaterState.equals(state)) return state;
final UpdaterTreeState oldState = myUpdaterState;
if (oldState == null) {
myUpdaterState = state;
return state;
}
else {
oldState.addAll(state);
return oldState;
}
}
protected void doUpdateNode(final DefaultMutableTreeNode node) {
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
final NodeDescriptor descriptor = getDescriptorFrom(node);
final Object prevElement = getElementFromDescriptor(descriptor);
if (prevElement == null) return;
update(descriptor, false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
if (!isValid(descriptor)) {
if (isInStructure(prevElement)) {
getUpdater().addSubtreeToUpdateByElement(getTreeStructure().getParentElement(prevElement));
return;
}
}
if (changes) {
updateNodeImageAndPosition(node, true);
}
}
});
}
public Object getElementFromDescriptor(NodeDescriptor descriptor) {
return getBuilder().getTreeStructureElement(descriptor);
}
private void updateNodeChildren(final DefaultMutableTreeNode node,
final TreeUpdatePass pass,
@Nullable LoadedChildren loadedChildren,
boolean forcedNow,
final boolean toSmartExpand,
boolean forceUpdate,
final boolean descriptorIsUpToDate) {
try {
getTreeStructure().commit();
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) {
removeLoading(node, true);
return;
}
final boolean wasExpanded = myTree.isExpanded(new TreePath(node.getPath())) || isAutoExpand(node);
final boolean wasLeaf = node.getChildCount() == 0;
boolean bgBuild = isToBuildInBackground(descriptor);
boolean notRequiredToUpdateChildren = !forcedNow && !wasExpanded;
if (notRequiredToUpdateChildren && forceUpdate && !wasExpanded) {
boolean alwaysPlus = getBuilder().isAlwaysShowPlus(descriptor);
if (alwaysPlus && wasLeaf) {
notRequiredToUpdateChildren = false;
} else {
notRequiredToUpdateChildren = alwaysPlus;
}
}
final Ref<LoadedChildren> preloaded = new Ref<LoadedChildren>(loadedChildren);
boolean descriptorWasUpdated = descriptorIsUpToDate;
if (notRequiredToUpdateChildren) {
if (myUnbuiltNodes.contains(node) && node.getChildCount() == 0) {
insertLoadingNode(node, true);
}
return;
}
if (!forcedNow) {
if (!bgBuild) {
if (myUnbuiltNodes.contains(node)) {
if (!descriptorWasUpdated) {
update(descriptor, true);
descriptorWasUpdated = true;
}
if (processAlwaysLeaf(node)) return;
Pair<Boolean, LoadedChildren> unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null);
if (unbuilt.getFirst()) return;
preloaded.set(unbuilt.getSecond());
}
}
}
final boolean childForceUpdate = isChildNodeForceUpdate(node, forceUpdate, wasExpanded);
if (!forcedNow && isToBuildInBackground(descriptor)) {
if (processAlwaysLeaf(node)) return;
queueBackgroundUpdate(
new UpdateInfo(descriptor, pass, canSmartExpand(node, toSmartExpand), wasExpanded, childForceUpdate, descriptorWasUpdated), node);
return;
}
else {
if (!descriptorWasUpdated) {
update(descriptor, false).doWhenDone(new Runnable() {
public void run() {
if (processAlwaysLeaf(node)) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, wasLeaf, childForceUpdate);
}
});
}
else {
if (processAlwaysLeaf(node)) return;
updateNodeChildrenNow(node, pass, preloaded.get(), toSmartExpand, wasExpanded, wasLeaf, childForceUpdate);
}
}
}
finally {
processNodeActionsIfReady(node);
}
}
private boolean processAlwaysLeaf(DefaultMutableTreeNode node) {
Object element = getElementFor(node);
NodeDescriptor desc = getDescriptorFrom(node);
if (desc == null) return false;
if (getTreeStructure().isAlwaysLeaf(element)) {
removeLoading(node, true);
if (node.getChildCount() > 0) {
final TreeNode[] children = new TreeNode[node.getChildCount()];
for (int i = 0; i < node.getChildCount(); i++) {
children[i] = node.getChildAt(i);
}
if (isSelectionInside(node)) {
addSelectionPath(getPathFor(node), true, Condition.TRUE, null);
}
processInnerChange(new Runnable() {
public void run() {
for (TreeNode each : children) {
removeNodeFromParent((MutableTreeNode)each, true);
disposeNode((DefaultMutableTreeNode)each);
}
}
});
}
removeFromUnbuilt(node);
desc.setWasDeclaredAlwaysLeaf(true);
processNodeActionsIfReady(node);
return true;
} else {
boolean wasLeaf = desc.isWasDeclaredAlwaysLeaf();
desc.setWasDeclaredAlwaysLeaf(false);
if (wasLeaf) {
insertLoadingNode(node, true);
}
return false;
}
}
private boolean isChildNodeForceUpdate(DefaultMutableTreeNode node, boolean parentForceUpdate, boolean parentExpanded) {
TreePath path = getPathFor(node);
return parentForceUpdate && (parentExpanded || myTree.isExpanded(path));
}
private void updateNodeChildrenNow(final DefaultMutableTreeNode node,
final TreeUpdatePass pass,
final LoadedChildren preloadedChildren,
final boolean toSmartExpand,
final boolean wasExpanded,
final boolean wasLeaf,
final boolean forceUpdate) {
final NodeDescriptor descriptor = getDescriptorFrom(node);
final MutualMap<Object, Integer> elementToIndexMap = loadElementsFromStructure(descriptor, preloadedChildren);
final LoadedChildren loadedChildren =
preloadedChildren != null ? preloadedChildren : new LoadedChildren(elementToIndexMap.getKeys().toArray());
addToUpdating(node);
pass.setCurrentNode(node);
final boolean canSmartExpand = canSmartExpand(node, toSmartExpand);
processExistingNodes(node, elementToIndexMap, pass, canSmartExpand(node, toSmartExpand), forceUpdate, wasExpanded, preloadedChildren)
.doWhenDone(new Runnable() {
public void run() {
if (isDisposed(node)) {
removeFromUpdating(node);
return;
}
removeLoading(node, false);
final boolean expanded = isExpanded(node, wasExpanded);
if (expanded) {
myWillBeExpaned.add(node);
} else {
myWillBeExpaned.remove(node);
}
collectNodesToInsert(descriptor, elementToIndexMap, node, expanded, loadedChildren)
.doWhenDone(new AsyncResult.Handler<ArrayList<TreeNode>>() {
public void run(ArrayList<TreeNode> nodesToInsert) {
insertNodesInto(nodesToInsert, node);
updateNodesToInsert(nodesToInsert, pass, canSmartExpand, isChildNodeForceUpdate(node, forceUpdate, expanded));
removeLoading(node, true);
removeFromUpdating(node);
if (node.getChildCount() > 0) {
if (expanded ) {
expand(node, canSmartExpand);
}
}
final Object element = getElementFor(node);
addNodeAction(element, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
removeLoading(node, false);
}
}, false);
processNodeActionsIfReady(node);
}
}).doWhenProcessed(new Runnable() {
public void run() {
myWillBeExpaned.remove(node);
removeFromUpdating(node);
processNodeActionsIfReady(node);
}
});
}
}).doWhenRejected(new Runnable() {
public void run() {
removeFromUpdating(node);
processNodeActionsIfReady(node);
}
});
}
private boolean isDisposed(DefaultMutableTreeNode node) {
return !node.isNodeAncestor((DefaultMutableTreeNode)myTree.getModel().getRoot());
}
private void expand(DefaultMutableTreeNode node, boolean canSmartExpand) {
expand(new TreePath(node.getPath()), canSmartExpand);
}
private void expand(final TreePath path, boolean canSmartExpand) {
if (path == null) return;
final Object last = path.getLastPathComponent();
boolean isLeaf = myTree.getModel().isLeaf(path.getLastPathComponent());
final boolean isRoot = last == myTree.getModel().getRoot();
final TreePath parent = path.getParentPath();
if (isRoot && !myTree.isExpanded(path)) {
if (myTree.isRootVisible() || myUnbuiltNodes.contains(last)) {
insertLoadingNode((DefaultMutableTreeNode)last, false);
}
expandPath(path, canSmartExpand);
}
else if (myTree.isExpanded(path) || (isLeaf && parent != null && myTree.isExpanded(parent) && !myUnbuiltNodes.contains(last))) {
if (last instanceof DefaultMutableTreeNode) {
processNodeActionsIfReady((DefaultMutableTreeNode)last);
}
}
else {
if (isLeaf && myUnbuiltNodes.contains(last)) {
insertLoadingNode((DefaultMutableTreeNode)last, true);
expandPath(path, canSmartExpand);
}
else if (isLeaf && parent != null) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent.getLastPathComponent();
if (parentNode != null) {
addToUnbuilt(parentNode);
}
expandPath(parent, canSmartExpand);
}
else {
expandPath(path, canSmartExpand);
}
}
}
private void addToUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.add(node);
}
private void removeFromUnbuilt(DefaultMutableTreeNode node) {
myUnbuiltNodes.remove(node);
}
private Pair<Boolean, LoadedChildren> processUnbuilt(final DefaultMutableTreeNode node,
final NodeDescriptor descriptor,
final TreeUpdatePass pass,
boolean isExpanded,
final LoadedChildren loadedChildren) {
if (!isExpanded && getBuilder().isAlwaysShowPlus(descriptor)) {
return new Pair<Boolean, LoadedChildren>(true, null);
}
final Object element = getElementFor(node);
final LoadedChildren children = loadedChildren != null ? loadedChildren : new LoadedChildren(getChildrenFor(element));
boolean processed;
if (children.getElements().size() == 0) {
removeLoading(node, true);
processed = true;
}
else {
if (isAutoExpand(node)) {
addNodeAction(getElementFor(node), new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
final TreePath path = new TreePath(node.getPath());
if (getTree().isExpanded(path) || children.getElements().size() == 0) {
removeLoading(node, false);
}
else {
maybeYeild(new ActiveRunnable() {
public ActionCallback run() {
expand(element, null);
return new ActionCallback.Done();
}
}, pass, node);
}
}
}, false);
}
processed = false;
}
processNodeActionsIfReady(node);
return new Pair<Boolean, LoadedChildren>(processed, children);
}
private boolean removeIfLoading(TreeNode node) {
if (isLoadingNode(node)) {
moveSelectionToParentIfNeeded(node);
removeNodeFromParent((MutableTreeNode)node, false);
return true;
}
return false;
}
private void moveSelectionToParentIfNeeded(TreeNode node) {
TreePath path = getPathFor(node);
if (myTree.getSelectionModel().isPathSelected(path)) {
TreePath parentPath = path.getParentPath();
myTree.getSelectionModel().removeSelectionPath(path);
if (parentPath != null) {
myTree.getSelectionModel().addSelectionPath(parentPath);
}
}
}
//todo [kirillk] temporary consistency check
private Object[] getChildrenFor(final Object element) {
final Object[] passOne;
try {
passOne = getTreeStructure().getChildElements(element);
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady();
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
if (!myCheckStructure) return passOne;
final Object[] passTwo = getTreeStructure().getChildElements(element);
final HashSet two = new HashSet(Arrays.asList(passTwo));
if (passOne.length != passTwo.length) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
}
else {
for (Object eachInOne : passOne) {
if (!two.contains(eachInOne)) {
LOG.error(
"AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" +
element);
break;
}
}
}
return passOne;
}
private void warnOnIndexNotReady() {
if (!myWasEverIndexNotReady) {
myWasEverIndexNotReady = true;
LOG.warn("Tree is not dumb-mode-aware; treeBuilder=" + getBuilder() + " treeStructure=" + getTreeStructure());
}
}
private void updateNodesToInsert(final ArrayList<TreeNode> nodesToInsert,
TreeUpdatePass pass,
boolean canSmartExpand,
boolean forceUpdate) {
for (TreeNode aNodesToInsert : nodesToInsert) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)aNodesToInsert;
updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true);
}
}
private ActionCallback processExistingNodes(final DefaultMutableTreeNode node,
final MutualMap<Object, Integer> elementToIndexMap,
final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
final boolean wasExpaned,
final LoadedChildren preloaded) {
final ArrayList<TreeNode> childNodes = TreeUtil.childrenToArray(node);
return maybeYeild(new ActiveRunnable() {
public ActionCallback run() {
if (pass.isExpired()) return new ActionCallback.Rejected();
if (childNodes.size() == 0) return new ActionCallback.Done();
final ActionCallback result = new ActionCallback(childNodes.size());
for (TreeNode each : childNodes) {
final DefaultMutableTreeNode eachChild = (DefaultMutableTreeNode)each;
if (isLoadingNode(eachChild)) {
result.setDone();
continue;
}
final boolean childForceUpdate = isChildNodeForceUpdate(eachChild, forceUpdate, wasExpaned);
maybeYeild(new ActiveRunnable() {
@Override
public ActionCallback run() {
return processExistingNode(eachChild, getDescriptorFrom(eachChild), node, elementToIndexMap, pass, canSmartExpand,
childForceUpdate, preloaded);
}
}, pass, node).notify(result);
if (result.isRejected()) {
break;
}
}
return result;
}
}, pass, node);
}
private boolean isRerunNeeded(TreeUpdatePass pass) {
if (pass.isExpired()) return false;
final boolean rerunBecauseTreeIsHidden = !pass.isExpired() && !isTreeShowing() && getUpdater().isInPostponeMode();
return rerunBecauseTreeIsHidden || getUpdater().isRerunNeededFor(pass);
}
private ActionCallback maybeYeild(final ActiveRunnable processRunnable, final TreeUpdatePass pass, final DefaultMutableTreeNode node) {
final ActionCallback result = new ActionCallback();
if (isRerunNeeded(pass)) {
getUpdater().addSubtreeToUpdate(pass);
result.setRejected();
}
else {
if (isToYieldUpdateFor(node)) {
pass.setCurrentNode(node);
boolean wasRun = yieldAndRun(new Runnable() {
public void run() {
if (validateReleaseRequested()) {
result.setRejected();
return;
}
if (pass.isExpired()) {
result.setRejected();
return;
}
if (isRerunNeeded(pass)) {
runDone(new Runnable() {
public void run() {
if (!pass.isExpired()) {
getUpdater().addSubtreeToUpdate(pass);
}
}
});
result.setRejected();
}
else {
try {
processRunnable.run().notify(result);
}
catch (ProcessCanceledException e) {
pass.expire();
result.setRejected();
}
}
}
}, pass);
if (!wasRun) {
result.setRejected();
}
}
else {
try {
processRunnable.run().notify(result);
}
catch (ProcessCanceledException e) {
pass.expire();
result.setRejected();
}
}
}
return result;
}
private boolean yieldAndRun(final Runnable runnable, final TreeUpdatePass pass) {
if (validateReleaseRequested()) return false;
myYeildingPasses.add(pass);
myYeildingNow = true;
yield(new Runnable() {
public void run() {
runOnYieldingDone(new Runnable() {
public void run() {
executeYieldingRequest(runnable, pass);
}
});
}
});
return true;
}
public boolean isYeildingNow() {
return myYeildingNow;
}
private boolean hasSheduledUpdates() {
return getUpdater().hasNodesToUpdate() || isLoadingInBackgroundNow();
}
public boolean isReady() {
return isIdle() && !hasPendingWork() && !isNodeActionsPending();
}
public boolean hasPendingWork() {
return hasNodesToUpdate() || (myUpdaterState != null && myUpdaterState.isProcessingNow());
}
public boolean isIdle() {
return !isYeildingNow() && !isWorkerBusy() && (!hasSheduledUpdates() || getUpdater().isInPostponeMode());
}
private void executeYieldingRequest(Runnable runnable, TreeUpdatePass pass) {
try {
myYeildingPasses.remove(pass);
runnable.run();
}
finally {
maybeYeildingFinished();
}
}
private void maybeYeildingFinished() {
if (myYeildingPasses.size() == 0) {
myYeildingNow = false;
flushPendingNodeActions();
}
}
void maybeReady() {
if (isReleased()) return;
if (isReady()) {
if (isReleaseRequested()) {
releaseNow();
return;
}
if (myTree.isShowing() || myUpdateIfInactive) {
myInitialized.setDone();
}
if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) {
UpdaterTreeState oldState = myUpdaterState;
if (!myUpdaterState.restore(null)) {
setUpdaterState(oldState);
}
if (!isReady()) {
return;
}
}
if (myTree.isShowing()) {
if (getBuilder().isToEnsureSelectionOnFocusGained() && Registry.is("ide.tree.ensureSelectionOnFocusGained")) {
TreeUtil.ensureSelection(myTree);
}
}
if (myInitialized.isDone()) {
for (ActionCallback each : getReadyCallbacks(true)) {
each.setDone();
}
}
}
}
private void flushPendingNodeActions() {
final DefaultMutableTreeNode[] nodes = myPendingNodeActions.toArray(new DefaultMutableTreeNode[myPendingNodeActions.size()]);
myPendingNodeActions.clear();
for (DefaultMutableTreeNode each : nodes) {
processNodeActionsIfReady(each);
}
final Runnable[] actions = myYeildingDoneRunnables.toArray(new Runnable[myYeildingDoneRunnables.size()]);
for (Runnable each : actions) {
if (!isYeildingNow()) {
myYeildingDoneRunnables.remove(each);
each.run();
}
}
maybeReady();
}
protected void runOnYieldingDone(Runnable onDone) {
getBuilder().runOnYeildingDone(onDone);
}
protected void yield(Runnable runnable) {
getBuilder().yield(runnable);
}
private boolean isToYieldUpdateFor(final DefaultMutableTreeNode node) {
if (!canYield()) return false;
return getBuilder().isToYieldUpdateFor(node);
}
private MutualMap<Object, Integer> loadElementsFromStructure(final NodeDescriptor descriptor,
@Nullable LoadedChildren preloadedChildren) {
MutualMap<Object, Integer> elementToIndexMap = new MutualMap<Object, Integer>(true);
List children = preloadedChildren != null
? preloadedChildren.getElements()
: Arrays.asList(getChildrenFor(getBuilder().getTreeStructureElement(descriptor)));
int index = 0;
for (Object child : children) {
if (!isValid(child)) continue;
elementToIndexMap.put(child, Integer.valueOf(index));
index++;
}
return elementToIndexMap;
}
private void expand(final DefaultMutableTreeNode node,
final NodeDescriptor descriptor,
final boolean wasLeaf,
final boolean canSmartExpand) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
alarm.addRequest(new Runnable() {
public void run() {
myTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}, WAIT_CURSOR_DELAY);
if (wasLeaf && isAutoExpand(descriptor)) {
expand(node, canSmartExpand);
}
ArrayList<TreeNode> nodes = TreeUtil.childrenToArray(node);
for (TreeNode node1 : nodes) {
final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)node1;
if (isLoadingNode(childNode)) continue;
NodeDescriptor childDescr = getDescriptorFrom(childNode);
if (isAutoExpand(childDescr)) {
addNodeAction(getElementFor(childNode), new NodeAction() {
public void onReady(DefaultMutableTreeNode node) {
expand(childNode, canSmartExpand);
}
}, false);
addSubtreeToUpdate(childNode);
}
}
int n = alarm.cancelAllRequests();
if (n == 0) {
myTree.setCursor(Cursor.getDefaultCursor());
}
}
public static boolean isLoadingNode(final Object node) {
return node instanceof LoadingNode;
}
private AsyncResult<ArrayList<TreeNode>> collectNodesToInsert(final NodeDescriptor descriptor,
final MutualMap<Object, Integer> elementToIndexMap,
final DefaultMutableTreeNode parent,
final boolean addLoadingNode,
@NotNull final LoadedChildren loadedChildren) {
final AsyncResult<ArrayList<TreeNode>> result = new AsyncResult<ArrayList<TreeNode>>();
final ArrayList<TreeNode> nodesToInsert = new ArrayList<TreeNode>();
final Collection<Object> allElements = elementToIndexMap.getKeys();
final ActionCallback processingDone = new ActionCallback(allElements.size());
for (final Object child : allElements) {
Integer index = elementToIndexMap.getValue(child);
final Ref<NodeDescriptor> childDescr = new Ref<NodeDescriptor>(loadedChildren.getDescriptor(child));
boolean needToUpdate = false;
if (childDescr.get() == null) {
childDescr.set(getTreeStructure().createDescriptor(child, descriptor));
needToUpdate = true;
}
if (childDescr.get() == null) {
processingDone.setDone();
continue;
}
childDescr.get().setIndex(index.intValue());
final ActionCallback update = new ActionCallback();
if (needToUpdate) {
update(childDescr.get(), false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean changes) {
loadedChildren.putDescriptor(child, childDescr.get(), changes);
update.setDone();
}
});
}
else {
update.setDone();
}
update.doWhenDone(new Runnable() {
public void run() {
Object element = getElementFromDescriptor(childDescr.get());
if (element == null) {
processingDone.setDone();
}
else {
DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node == null || node.getParent() != parent) {
final DefaultMutableTreeNode childNode = createChildNode(childDescr.get());
if (addLoadingNode || getBuilder().isAlwaysShowPlus(childDescr.get())) {
insertLoadingNode(childNode, true);
}
else {
addToUnbuilt(childNode);
}
nodesToInsert.add(childNode);
createMapping(element, childNode);
}
processingDone.setDone();
}
}
});
}
processingDone.doWhenDone(new Runnable() {
public void run() {
result.setDone(nodesToInsert);
}
});
return result;
}
protected DefaultMutableTreeNode createChildNode(final NodeDescriptor descriptor) {
return new ElementNode(this, descriptor);
}
protected boolean canYield() {
return myCanYield && myYeildingUpdate.asBoolean();
}
public long getClearOnHideDelay() {
return myClearOnHideDelay > 0 ? myClearOnHideDelay : Registry.intValue("ide.tree.clearOnHideTime");
}
public ActionCallback getInitialized() {
return myInitialized;
}
public ActionCallback getReady(Object requestor) {
if (isReady()) {
return new ActionCallback.Done();
}
else {
return addReadyCallback(requestor);
}
}
private void addToUpdating(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.add(node);
}
}
private void removeFromUpdating(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
myUpdatingChildren.remove(node);
}
}
public boolean isUpdatingNow(DefaultMutableTreeNode node) {
synchronized (myUpdatingChildren) {
return myUpdatingChildren.contains(node);
}
}
boolean hasUpdatingNow() {
synchronized (myUpdatingChildren) {
return myUpdatingChildren.size() > 0;
}
}
public Map getNodeActions() {
return myNodeActions;
}
public List<Object> getLoadedChildrenFor(Object element) {
List<Object> result = new ArrayList<Object>();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)getNodeForElement(element, false);
if (node != null) {
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode each = node.getChildAt(i);
if (isLoadingNode(each)) continue;
result.add(getElementFor(each));
}
}
return result;
}
public boolean hasNodesToUpdate() {
return getUpdater().hasNodesToUpdate() || hasUpdatingNow() || isLoadingInBackgroundNow();
}
public List<Object> getExpandedElements() {
List<Object> result = new ArrayList<Object>();
Enumeration<TreePath> enumeration = myTree.getExpandedDescendants(getPathFor(getRootNode()));
while (enumeration.hasMoreElements()) {
TreePath each = enumeration.nextElement();
Object eachElement = getElementFor(each.getLastPathComponent());
if (eachElement != null) {
result.add(eachElement);
}
}
return result;
}
static class ElementNode extends DefaultMutableTreeNode {
Set<Object> myElements = new HashSet<Object>();
AbstractTreeUi myUi;
ElementNode(AbstractTreeUi ui, NodeDescriptor descriptor) {
super(descriptor);
myUi = ui;
}
@Override
public void insert(final MutableTreeNode newChild, final int childIndex) {
super.insert(newChild, childIndex);
final Object element = myUi.getElementFor(newChild);
if (element != null) {
myElements.add(element);
}
}
@Override
public void remove(final int childIndex) {
final TreeNode node = getChildAt(childIndex);
super.remove(childIndex);
final Object element = myUi.getElementFor(node);
if (element != null) {
myElements.remove(element);
}
}
boolean isValidChild(Object childElement) {
return myElements.contains(childElement);
}
@Override
public String toString() {
return String.valueOf(getUserObject());
}
}
private boolean isUpdatingParent(DefaultMutableTreeNode kid) {
return getUpdatingParent(kid) != null;
}
private DefaultMutableTreeNode getUpdatingParent(DefaultMutableTreeNode kid) {
DefaultMutableTreeNode eachParent = kid;
while (eachParent != null) {
if (isUpdatingNow(eachParent)) return eachParent;
eachParent = (DefaultMutableTreeNode)eachParent.getParent();
}
return null;
}
private boolean isLoadedInBackground(Object element) {
return getLoadedInBackground(element) != null;
}
private UpdateInfo getLoadedInBackground(Object element) {
synchronized (myLoadedInBackground) {
return myLoadedInBackground.get(element);
}
}
private void addToLoadedInBackground(Object element, UpdateInfo info) {
synchronized (myLoadedInBackground) {
myLoadedInBackground.put(element, info);
}
}
private void removeFromLoadedInBackground(final Object element) {
synchronized (myLoadedInBackground) {
myLoadedInBackground.remove(element);
}
}
private boolean isLoadingInBackgroundNow() {
synchronized (myLoadedInBackground) {
return myLoadedInBackground.size() > 0;
}
}
private boolean queueBackgroundUpdate(final UpdateInfo updateInfo, final DefaultMutableTreeNode node) {
assertIsDispatchThread();
if (validateReleaseRequested()) return false;
final Object oldElementFromDescriptor = getElementFromDescriptor(updateInfo.getDescriptor());
UpdateInfo loaded = getLoadedInBackground(oldElementFromDescriptor);
if (loaded != null) {
loaded.apply(updateInfo);
return false;
}
addToLoadedInBackground(oldElementFromDescriptor, updateInfo);
if (!isNodeBeingBuilt(node)) {
LoadingNode loadingNode = new LoadingNode(getLoadingNodeText());
myTreeModel.insertNodeInto(loadingNode, node, node.getChildCount());
}
final Ref<LoadedChildren> children = new Ref<LoadedChildren>();
final Ref<Object> elementFromDescriptor = new Ref<Object>();
final DefaultMutableTreeNode[] nodeToProcessActions = new DefaultMutableTreeNode[1];
final Runnable finalizeRunnable = new Runnable() {
public void run() {
invokeLaterIfNeeded(new Runnable() {
public void run() {
removeLoading(node, true);
removeFromLoadedInBackground(elementFromDescriptor.get());
removeFromLoadedInBackground(oldElementFromDescriptor);
if (nodeToProcessActions[0] != null) {
processNodeActionsIfReady(nodeToProcessActions[0]);
}
}
});
}
};
Runnable buildRunnable = new Runnable() {
public void run() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (!updateInfo.isDescriptorIsUpToDate()) {
update(updateInfo.getDescriptor(), true);
}
Object element = getElementFromDescriptor(updateInfo.getDescriptor());
if (element == null) {
removeFromLoadedInBackground(oldElementFromDescriptor);
finalizeRunnable.run();
return;
}
elementFromDescriptor.set(element);
Object[] loadedElements = getChildrenFor(getBuilder().getTreeStructureElement(updateInfo.getDescriptor()));
LoadedChildren loaded = new LoadedChildren(loadedElements);
for (Object each : loadedElements) {
NodeDescriptor eachChildDescriptor = getTreeStructure().createDescriptor(each, updateInfo.getDescriptor());
loaded.putDescriptor(each, eachChildDescriptor, update(eachChildDescriptor, true).getResult());
}
children.set(loaded);
}
};
Runnable updateRunnable = new Runnable() {
public void run() {
if (updateInfo.getPass().isExpired()) {
finalizeRunnable.run();
return;
}
if (children.get() == null) {
finalizeRunnable.run();
return;
}
if (isRerunNeeded(updateInfo.getPass())) {
removeFromLoadedInBackground(elementFromDescriptor.get());
getUpdater().addSubtreeToUpdate(updateInfo.getPass());
return;
}
removeFromLoadedInBackground(elementFromDescriptor.get());
if (myUnbuiltNodes.contains(node)) {
Pair<Boolean, LoadedChildren> unbuilt =
processUnbuilt(node, updateInfo.getDescriptor(), updateInfo.getPass(), isExpanded(node, updateInfo.isWasExpanded()),
children.get());
if (unbuilt.getFirst()) {
nodeToProcessActions[0] = node;
return;
}
}
updateNodeChildren(node, updateInfo.getPass(), children.get(), true, updateInfo.isCanSmartExpand(), updateInfo.isForceUpdate(),
true);
if (isRerunNeeded(updateInfo.getPass())) {
getUpdater().addSubtreeToUpdate(updateInfo.getPass());
return;
}
Object element = elementFromDescriptor.get();
if (element != null) {
removeLoading(node, true);
nodeToProcessActions[0] = node;
}
}
};
queueToBackground(buildRunnable, updateRunnable).doWhenProcessed(finalizeRunnable).doWhenRejected(new Runnable() {
public void run() {
updateInfo.getPass().expire();
}
});
return true;
}
private boolean isExpanded(DefaultMutableTreeNode node, boolean isExpanded) {
return isExpanded || myTree.isExpanded(getPathFor(node));
}
private void removeLoading(DefaultMutableTreeNode parent, boolean removeFromUnbuilt) {
for (int i = 0; i < parent.getChildCount(); i++) {
TreeNode child = parent.getChildAt(i);
if (removeIfLoading(child)) {
i--;
}
}
if (removeFromUnbuilt) {
removeFromUnbuilt(parent);
}
if (parent == getRootNode() && !myTree.isRootVisible() && parent.getChildCount() == 0) {
insertLoadingNode(parent, false);
}
maybeReady();
}
private void processNodeActionsIfReady(final DefaultMutableTreeNode node) {
assertIsDispatchThread();
if (isNodeBeingBuilt(node)) return;
final Object o = node.getUserObject();
if (!(o instanceof NodeDescriptor)) return;
if (isYeildingNow()) {
myPendingNodeActions.add(node);
return;
}
final Object element = getBuilder().getTreeStructureElement((NodeDescriptor)o);
boolean childrenReady = !isLoadedInBackground(element);
processActions(node, element, myNodeActions, childrenReady ? myNodeChildrenActions : null);
if (childrenReady) {
processActions(node, element, myNodeChildrenActions, null);
}
if (!isUpdatingParent(node) && !isWorkerBusy()) {
final UpdaterTreeState state = myUpdaterState;
if (myNodeActions.size() == 0 && state != null && !state.isProcessingNow()) {
if (!state.restore(childrenReady ? node : null)) {
setUpdaterState(state);
}
}
}
maybeReady();
}
private void processActions(DefaultMutableTreeNode node, Object element, final Map<Object, List<NodeAction>> nodeActions, @Nullable final Map<Object, List<NodeAction>> secondaryNodeAction) {
final List<NodeAction> actions = nodeActions.get(element);
if (actions != null) {
nodeActions.remove(element);
List<NodeAction> secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null;
for (NodeAction each : actions) {
if (secondary != null && secondary.contains(each)) {
secondary.remove(each);
}
each.onReady(node);
}
}
}
private boolean canSmartExpand(DefaultMutableTreeNode node, boolean canSmartExpand) {
if (!getBuilder().isSmartExpand()) return false;
boolean smartExpand = !myNotForSmartExpand.contains(node) && canSmartExpand;
return smartExpand ? validateAutoExpand(smartExpand, getElementFor(node)) : false;
}
private void processSmartExpand(final DefaultMutableTreeNode node, final boolean canSmartExpand, boolean forced) {
if (!getBuilder().isSmartExpand()) return;
boolean can = canSmartExpand(node, canSmartExpand);
if (!can && !forced) return;
if (isNodeBeingBuilt(node) && !forced) {
addNodeAction(getElementFor(node), new NodeAction() {
public void onReady(DefaultMutableTreeNode node) {
processSmartExpand(node, canSmartExpand, true);
}
}, true);
}
else {
TreeNode child = getChildForSmartExpand(node);
if (child != null) {
final TreePath childPath = new TreePath(node.getPath()).pathByAddingChild(child);
processInnerChange(new Runnable() {
public void run() {
myTree.expandPath(childPath);
}
});
}
}
}
@Nullable
private TreeNode getChildForSmartExpand(DefaultMutableTreeNode node) {
int realChildCount = 0;
TreeNode nodeToExpand = null;
for (int i = 0; i < node.getChildCount(); i++) {
TreeNode eachChild = node.getChildAt(i);
if (!isLoadingNode(eachChild)) {
realChildCount++;
if (nodeToExpand == null) {
nodeToExpand = eachChild;
}
}
if (realChildCount > 1) {
nodeToExpand = null;
break;
}
}
return nodeToExpand;
}
public boolean isLoadingChildrenFor(final Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return false;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
int loadingNodes = 0;
for (int i = 0; i < Math.min(node.getChildCount(), 2); i++) {
TreeNode child = node.getChildAt(i);
if (isLoadingNode(child)) {
loadingNodes++;
}
}
return loadingNodes > 0 && loadingNodes == node.getChildCount();
}
private boolean isParentLoading(Object nodeObject) {
return getParentLoading(nodeObject) != null;
}
private DefaultMutableTreeNode getParentLoading(Object nodeObject) {
if (!(nodeObject instanceof DefaultMutableTreeNode)) return null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodeObject;
TreeNode eachParent = node.getParent();
while (eachParent != null) {
eachParent = eachParent.getParent();
if (eachParent instanceof DefaultMutableTreeNode) {
final Object eachElement = getElementFor((DefaultMutableTreeNode)eachParent);
if (isLoadedInBackground(eachElement)) return (DefaultMutableTreeNode)eachParent;
}
}
return null;
}
protected String getLoadingNodeText() {
return IdeBundle.message("progress.searching");
}
private ActionCallback processExistingNode(final DefaultMutableTreeNode childNode,
final NodeDescriptor childDescriptor,
final DefaultMutableTreeNode parentNode,
final MutualMap<Object, Integer> elementToIndexMap,
final TreeUpdatePass pass,
final boolean canSmartExpand,
final boolean forceUpdate,
LoadedChildren parentPreloadedChildren) {
final ActionCallback result = new ActionCallback();
if (pass.isExpired()) {
return new ActionCallback.Rejected();
}
final Ref<NodeDescriptor> childDesc = new Ref<NodeDescriptor>(childDescriptor);
if (childDesc.get() == null) {
pass.expire();
return new ActionCallback.Rejected();
}
final Object oldElement = getElementFromDescriptor(childDesc.get());
if (oldElement == null) {
pass.expire();
return new ActionCallback.Rejected();
}
AsyncResult<Boolean> update = new AsyncResult<Boolean>();
if (parentPreloadedChildren != null && parentPreloadedChildren.getDescriptor(oldElement) != null) {
update.setDone(parentPreloadedChildren.isUpdated(oldElement));
}
else {
update = update(childDesc.get(), false);
}
update.doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean isChanged) {
final Ref<Boolean> changes = new Ref<Boolean>(isChanged);
final Ref<Boolean> forceRemapping = new Ref<Boolean>(false);
final Ref<Object> newElement = new Ref<Object>(getElementFromDescriptor(childDesc.get()));
final Integer index = newElement.get() != null ? elementToIndexMap.getValue(getBuilder().getTreeStructureElement(childDesc.get())) : null;
final AsyncResult<Boolean> updateIndexDone = new AsyncResult<Boolean>();
final ActionCallback indexReady = new ActionCallback();
if (index != null) {
final Object elementFromMap = elementToIndexMap.getKey(index);
if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) {
if (isInStructure(elementFromMap) && isInStructure(newElement.get())) {
if (parentNode.getUserObject() instanceof NodeDescriptor) {
final NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor));
childNode.setUserObject(childDesc.get());
newElement.set(elementFromMap);
forceRemapping.set(true);
update(childDesc.get(), false).doWhenDone(new AsyncResult.Handler<Boolean>() {
public void run(Boolean isChanged) {
changes.set(isChanged);
updateIndexDone.setDone(isChanged);
}
});
}
}
else {
updateIndexDone.setDone(changes.get());
}
} else {
updateIndexDone.setDone(changes.get());
}
updateIndexDone.doWhenDone(new Runnable() {
public void run() {
if (childDesc.get().getIndex() != index.intValue()) {
changes.set(true);
}
childDesc.get().setIndex(index.intValue());
indexReady.setDone();
}
});
}
else {
updateIndexDone.setDone();
}
updateIndexDone.doWhenDone(new Runnable() {
public void run() {
if (index != null && changes.get()) {
updateNodeImageAndPosition(childNode, false);
}
if (!oldElement.equals(newElement.get()) | forceRemapping.get()) {
removeMapping(oldElement, childNode, newElement.get());
if (newElement.get() != null) {
createMapping(newElement.get(), childNode);
}
NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode);
if (parentDescriptor != null) {
parentDescriptor.setChildrenSortingStamp(-1);
}
}
if (index == null) {
int selectedIndex = -1;
if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) {
selectedIndex = parentNode.getIndex(childNode);
}
if (childNode.getParent() instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent();
if (myTree.isExpanded(new TreePath(parent.getPath()))) {
if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) {
insertLoadingNode(parent, false);
}
}
}
Object disposedElement = getElementFor(childNode);
removeNodeFromParent(childNode, selectedIndex >= 0);
disposeNode(childNode);
adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement);
}
else {
elementToIndexMap.remove(getBuilder().getTreeStructureElement(childDesc.get()));
updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true);
}
if (parentNode.equals(getRootNode())) {
myTreeModel.nodeChanged(getRootNode());
}
result.setDone();
}
});
}
});
return result;
}
private void adjustSelectionOnChildRemove(DefaultMutableTreeNode parentNode, int selectedIndex, Object disposedElement) {
DefaultMutableTreeNode node = getNodeForElement(disposedElement, false);
if (node != null && isValidForSelectionAdjusting(node)) {
Object newElement = getElementFor(node);
addSelectionPath(getPathFor(node), true, getExpiredElementCondition(newElement), disposedElement);
return;
}
if (selectedIndex >= 0) {
if (parentNode.getChildCount() > 0) {
if (parentNode.getChildCount() > selectedIndex) {
TreeNode newChildNode = parentNode.getChildAt(selectedIndex);
if (isValidForSelectionAdjusting(newChildNode)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChildNode)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
else {
TreeNode newChild = parentNode.getChildAt(parentNode.getChildCount() - 1);
if (isValidForSelectionAdjusting(newChild)) {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(newChild)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
}
else {
addSelectionPath(new TreePath(myTreeModel.getPathToRoot(parentNode)), true, getExpiredElementCondition(disposedElement), disposedElement);
}
}
}
private boolean isValidForSelectionAdjusting(TreeNode node) {
if (!myTree.isRootVisible() && getRootNode() == node) return false;
if (isLoadingNode(node)) return true;
final Object elementInTree = getElementFor(node);
if (elementInTree == null) return false;
final TreeNode parentNode = node.getParent();
final Object parentElementInTree = getElementFor(parentNode);
if (parentElementInTree == null) return false;
final Object parentElement = getTreeStructure().getParentElement(elementInTree);
return parentElementInTree.equals(parentElement);
}
public Condition getExpiredElementCondition(final Object element) {
return new Condition() {
public boolean value(final Object o) {
return isInStructure(element);
}
};
}
private void addSelectionPath(final TreePath path, final boolean isAdjustedSelection, final Condition isExpiredAdjustement, @Nullable final Object adjustmentCause) {
processInnerChange(new Runnable() {
public void run() {
TreePath toSelect = null;
if (isLoadingNode(path.getLastPathComponent())) {
final TreePath parentPath = path.getParentPath();
if (parentPath != null) {
if (isValidForSelectionAdjusting((TreeNode)parentPath.getLastPathComponent())) {
toSelect = parentPath;
}
else {
toSelect = null;
}
}
}
else {
toSelect = path;
}
if (toSelect != null) {
myTree.addSelectionPath(toSelect);
if (isAdjustedSelection && myUpdaterState != null) {
final Object toSelectElement = getElementFor(toSelect.getLastPathComponent());
myUpdaterState.addAdjustedSelection(toSelectElement, isExpiredAdjustement, adjustmentCause);
}
}
}
});
}
private static TreePath getPathFor(TreeNode node) {
if (node instanceof DefaultMutableTreeNode) {
return new TreePath(((DefaultMutableTreeNode)node).getPath());
}
else {
ArrayList nodes = new ArrayList();
TreeNode eachParent = node;
while (eachParent != null) {
nodes.add(eachParent);
eachParent = eachParent.getParent();
}
return new TreePath(ArrayUtil.toObjectArray(nodes));
}
}
private void removeNodeFromParent(final MutableTreeNode node, final boolean willAdjustSelection) {
processInnerChange(new Runnable() {
public void run() {
if (willAdjustSelection) {
final TreePath path = getPathFor(node);
if (myTree.isPathSelected(path)) {
myTree.removeSelectionPath(path);
}
}
if (node.getParent() != null) {
myTreeModel.removeNodeFromParent(node);
}
}
});
}
private void expandPath(final TreePath path, final boolean canSmartExpand) {
processInnerChange(new Runnable() {
public void run() {
if (path.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getChildCount() > 0 && !myTree.isExpanded(path)) {
if (!canSmartExpand) {
myNotForSmartExpand.add(node);
}
try {
myRequestedExpand = path;
myTree.expandPath(path);
processSmartExpand(node, canSmartExpand, false);
}
finally {
myNotForSmartExpand.remove(node);
myRequestedExpand = null;
}
}
else {
processNodeActionsIfReady(node);
}
}
}
});
}
private void processInnerChange(Runnable runnable) {
if (myUpdaterState == null) {
setUpdaterState(new UpdaterTreeState(this));
}
myUpdaterState.process(runnable);
}
private boolean isInnerChange() {
return myUpdaterState != null && myUpdaterState.isProcessingNow();
}
protected boolean doUpdateNodeDescriptor(final NodeDescriptor descriptor) {
return descriptor.update();
}
private void makeLoadingOrLeafIfNoChildren(final DefaultMutableTreeNode node) {
TreePath path = getPathFor(node);
if (path == null) return;
insertLoadingNode(node, true);
final NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
descriptor.setChildrenSortingStamp(-1);
if (getBuilder().isAlwaysShowPlus(descriptor)) return;
TreePath parentPath = path.getParentPath();
if (myTree.isVisible(path) || (parentPath != null && myTree.isExpanded(parentPath))) {
if (myTree.isExpanded(path)) {
addSubtreeToUpdate(node);
}
else {
insertLoadingNode(node, false);
}
}
}
private boolean isValid(DefaultMutableTreeNode node) {
if (node == null) return false;
final Object object = node.getUserObject();
if (object instanceof NodeDescriptor) {
return isValid((NodeDescriptor)object);
}
return false;
}
private boolean isValid(NodeDescriptor descriptor) {
if (descriptor == null) return false;
return isValid(getElementFromDescriptor(descriptor));
}
private boolean isValid(Object element) {
if (element instanceof ValidateableNode) {
if (!((ValidateableNode)element).isValid()) return false;
}
return getBuilder().validateNode(element);
}
private void insertLoadingNode(final DefaultMutableTreeNode node, boolean addToUnbuilt) {
if (!isLoadingChildrenFor(node)) {
myTreeModel.insertNodeInto(new LoadingNode(), node, 0);
}
if (addToUnbuilt) {
addToUnbuilt(node);
}
}
protected ActionCallback queueToBackground(@NotNull final Runnable bgBuildAction,
@Nullable final Runnable edtPostRunnable) {
if (validateReleaseRequested()) return new ActionCallback.Rejected();
final ActionCallback result = new ActionCallback();
final Ref<Boolean> fail = new Ref<Boolean>(false);
final Runnable finalizer = new Runnable() {
public void run() {
if (fail.get()) {
result.setRejected();
} else {
result.setDone();
}
}
};
registerWorkerTask(bgBuildAction);
final Runnable pooledThreadWithProgressRunnable = new Runnable() {
public void run() {
final AbstractTreeBuilder builder = getBuilder();
builder.runBackgroundLoading(new Runnable() {
public void run() {
assertNotDispatchThread();
try {
bgBuildAction.run();
if (edtPostRunnable != null) {
builder.updateAfterLoadedInBackground(new Runnable() {
public void run() {
try {
assertIsDispatchThread();
edtPostRunnable.run();
} catch (ProcessCanceledException e) {
fail.set(true);
}
finally {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
});
}
else {
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
catch (ProcessCanceledException e) {
fail.set(true);
unregisterWorkerTask(bgBuildAction, finalizer);
}
catch (Throwable t) {
unregisterWorkerTask(bgBuildAction, finalizer);
throw new RuntimeException(t);
}
}
});
}
};
Runnable pooledThreadRunnable = new Runnable() {
public void run() {
try {
if (myProgress != null) {
ProgressManager.getInstance().runProcess(pooledThreadWithProgressRunnable, myProgress);
}
else {
pooledThreadWithProgressRunnable.run();
}
}
catch (ProcessCanceledException e) {
fail.set(true);
unregisterWorkerTask(bgBuildAction, finalizer);
}
}
};
if (isPassthroughMode()) {
} else {
if (myWorker == null || myWorker.isDisposed()) {
myWorker = new WorkerThread("AbstractTreeBuilder.Worker", 1);
myWorker.start();
myWorker.addTaskFirst(pooledThreadRunnable);
myWorker.dispose(false);
}
else {
myWorker.addTaskFirst(pooledThreadRunnable);
}
}
return result;
}
private void registerWorkerTask(Runnable runnable) {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.add(runnable);
}
}
private void unregisterWorkerTask(Runnable runnable, @Nullable Runnable finalizeRunnable) {
boolean wasRemoved;
synchronized (myActiveWorkerTasks) {
wasRemoved = myActiveWorkerTasks.remove(runnable);
}
if (wasRemoved && finalizeRunnable != null) {
finalizeRunnable.run();
}
maybeReady();
}
public boolean isWorkerBusy() {
synchronized (myActiveWorkerTasks) {
return myActiveWorkerTasks.size() > 0;
}
}
private void clearWorkerTasks() {
synchronized (myActiveWorkerTasks) {
myActiveWorkerTasks.clear();
}
}
private void updateNodeImageAndPosition(final DefaultMutableTreeNode node, boolean updatePosition) {
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (getElementFromDescriptor(descriptor) == null) return;
boolean notified = false;
if (updatePosition) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)node.getParent();
if (parentNode != null) {
int oldIndex = parentNode.getIndex(node);
int newIndex = oldIndex;
if (isLoadingChildrenFor(node.getParent()) || getBuilder().isChildrenResortingNeeded(descriptor)) {
final ArrayList<TreeNode> children = new ArrayList<TreeNode>(parentNode.getChildCount());
for (int i = 0; i < parentNode.getChildCount(); i++) {
children.add(parentNode.getChildAt(i));
}
sortChildren(node, children, true, false);
newIndex = children.indexOf(node);
}
if (oldIndex != newIndex) {
List<Object> pathsToExpand = new ArrayList<Object>();
List<Object> selectionPaths = new ArrayList<Object>();
TreeBuilderUtil.storePaths(getBuilder(), node, pathsToExpand, selectionPaths, false);
removeNodeFromParent(node, false);
myTreeModel.insertNodeInto(node, parentNode, newIndex);
TreeBuilderUtil.restorePaths(getBuilder(), pathsToExpand, selectionPaths, false);
notified = true;
}
else {
myTreeModel.nodeChanged(node);
notified = true;
}
}
else {
myTreeModel.nodeChanged(node);
notified = true;
}
}
if (!notified) {
myTreeModel.nodeChanged(node);
}
}
public DefaultTreeModel getTreeModel() {
return myTreeModel;
}
private void insertNodesInto(final ArrayList<TreeNode> toInsert, final DefaultMutableTreeNode parentNode) {
sortChildren(parentNode, toInsert, false, true);
final ArrayList<TreeNode> all = new ArrayList<TreeNode>(toInsert.size() + parentNode.getChildCount());
all.addAll(toInsert);
all.addAll(TreeUtil.childrenToArray(parentNode));
if (toInsert.size() > 0) {
sortChildren(parentNode, all, true, true);
int[] newNodeIndices = new int[toInsert.size()];
int eachNewNodeIndex = 0;
TreeMap<Integer, TreeNode> insertSet = new TreeMap<Integer, TreeNode>();
for (int i = 0; i < toInsert.size(); i++) {
TreeNode eachNewNode = toInsert.get(i);
while (all.get(eachNewNodeIndex) != eachNewNode) {
eachNewNodeIndex++;
}
newNodeIndices[i] = eachNewNodeIndex;
insertSet.put(eachNewNodeIndex, eachNewNode);
}
Iterator<Integer> indices = insertSet.keySet().iterator();
while (indices.hasNext()) {
Integer eachIndex = indices.next();
TreeNode eachNode = insertSet.get(eachIndex);
parentNode.insert((MutableTreeNode)eachNode, eachIndex);
}
myTreeModel.nodesWereInserted(parentNode, newNodeIndices);
}
else {
ArrayList<TreeNode> before = new ArrayList<TreeNode>();
before.addAll(all);
sortChildren(parentNode, all, true, false);
if (!before.equals(all)) {
processInnerChange(new Runnable() {
public void run() {
parentNode.removeAllChildren();
for (TreeNode each : all) {
parentNode.add((MutableTreeNode)each);
}
myTreeModel.nodeStructureChanged(parentNode);
}
});
}
}
}
private void sortChildren(DefaultMutableTreeNode node, ArrayList<TreeNode> children, boolean updateStamp, boolean forceSort) {
NodeDescriptor descriptor = getDescriptorFrom(node);
assert descriptor != null;
if (descriptor.getChildrenSortingStamp() >= getComparatorStamp() && !forceSort) return;
if (children.size() > 0) {
getBuilder().sortChildren(myNodeComparator, node, children);
}
if (updateStamp) {
descriptor.setChildrenSortingStamp(getComparatorStamp());
}
}
private void disposeNode(DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
if (parent instanceof DefaultMutableTreeNode) {
addToUnbuilt((DefaultMutableTreeNode)parent);
}
if (node.getChildCount() > 0) {
for (DefaultMutableTreeNode _node = (DefaultMutableTreeNode)node.getFirstChild(); _node != null; _node = _node.getNextSibling()) {
disposeNode(_node);
}
}
removeFromUpdating(node);
removeFromUnbuilt(node);
if (isLoadingNode(node)) return;
NodeDescriptor descriptor = getDescriptorFrom(node);
if (descriptor == null) return;
final Object element = getElementFromDescriptor(descriptor);
removeMapping(element, node, null);
myAutoExpandRoots.remove(element);
node.setUserObject(null);
node.removeAllChildren();
}
public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root) {
return addSubtreeToUpdate(root, null);
}
public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root, Runnable runAfterUpdate) {
Object element = getElementFor(root);
if (getTreeStructure().isAlwaysLeaf(element)) {
removeLoading(root, true);
if (runAfterUpdate != null) {
getReady(this).doWhenDone(runAfterUpdate);
}
return false;
}
if (isReleaseRequested()) {
processNodeActionsIfReady(root);
} else {
getUpdater().runAfterUpdate(runAfterUpdate);
getUpdater().addSubtreeToUpdate(root);
}
return true;
}
public boolean wasRootNodeInitialized() {
return myRootNodeWasInitialized;
}
private boolean isRootNodeBuilt() {
return myRootNodeWasInitialized && isNodeBeingBuilt(myRootNode);
}
public void select(final Object[] elements, @Nullable final Runnable onDone) {
select(elements, onDone, false);
}
public void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection) {
select(elements, onDone, addToSelection, false);
}
public void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection, boolean deferred) {
_select(elements, onDone, addToSelection, true, false, true, deferred, false, false);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure) {
_select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, true, false, false, false);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure,
final boolean scrollToVisible) {
_select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, false, false, false);
}
public void userSelect(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
boolean scroll) {
_select(elements, onDone, addToSelection, true, false, scroll, false, true, true);
}
void _select(final Object[] elements,
final Runnable onDone,
final boolean addToSelection,
final boolean checkCurrentSelection,
final boolean checkIfInStructure,
final boolean scrollToVisible,
final boolean deferred,
final boolean canSmartExpand,
final boolean mayQueue) {
AbstractTreeUpdater updater = getUpdater();
if (mayQueue && updater != null) {
updater.queueSelection(new SelectionRequest(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, deferred, canSmartExpand));
return;
}
boolean willAffectSelection = elements.length > 0 || (elements.length == 0 && addToSelection);
if (!willAffectSelection) {
runDone(onDone);
return;
}
final boolean oldCanProcessDeferredSelection = myCanProcessDeferredSelections;
if (!deferred && wasRootNodeInitialized() && willAffectSelection) {
myCanProcessDeferredSelections = false;
}
if (!checkDeferred(deferred, onDone)) return;
if (!deferred && oldCanProcessDeferredSelection && !myCanProcessDeferredSelections) {
getTree().clearSelection();
}
runDone(new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
final Set<Object> currentElements = getSelectedElements();
if (checkCurrentSelection && currentElements.size() > 0 && elements.length == currentElements.size()) {
boolean runSelection = false;
for (Object eachToSelect : elements) {
if (!currentElements.contains(eachToSelect)) {
runSelection = true;
break;
}
}
if (!runSelection) {
if (elements.length > 0) {
selectVisible(elements[0], onDone, true, true, scrollToVisible);
}
return;
}
}
Set<Object> toSelect = new HashSet<Object>();
myTree.clearSelection();
toSelect.addAll(Arrays.asList(elements));
if (addToSelection) {
toSelect.addAll(currentElements);
}
if (checkIfInStructure) {
final Iterator<Object> allToSelect = toSelect.iterator();
while (allToSelect.hasNext()) {
Object each = allToSelect.next();
if (!isInStructure(each)) {
allToSelect.remove();
}
}
}
final Object[] elementsToSelect = ArrayUtil.toObjectArray(toSelect);
if (wasRootNodeInitialized()) {
final int[] originalRows = myTree.getSelectionRows();
if (!addToSelection) {
myTree.clearSelection();
}
addNext(elementsToSelect, 0, new Runnable() {
public void run() {
if (getTree().isSelectionEmpty()) {
processInnerChange(new Runnable() {
public void run() {
restoreSelection(currentElements);
}
});
}
runDone(onDone);
}
}, originalRows, deferred, scrollToVisible, canSmartExpand);
}
else {
addToDeferred(elementsToSelect, onDone);
}
}
});
}
private void restoreSelection(Set<Object> selection) {
for (Object each : selection) {
DefaultMutableTreeNode node = getNodeForElement(each, false);
if (node != null && isValidForSelectionAdjusting(node)) {
addSelectionPath(getPathFor(node), false, null, null);
}
}
}
private void addToDeferred(final Object[] elementsToSelect, final Runnable onDone) {
myDeferredSelections.clear();
myDeferredSelections.add(new Runnable() {
public void run() {
select(elementsToSelect, onDone, false, true);
}
});
}
private boolean checkDeferred(boolean isDeferred, @Nullable Runnable onDone) {
if (!isDeferred || myCanProcessDeferredSelections || !wasRootNodeInitialized()) {
return true;
}
else {
runDone(onDone);
return false;
}
}
@NotNull
final Set<Object> getSelectedElements() {
final TreePath[] paths = myTree.getSelectionPaths();
Set<Object> result = new HashSet<Object>();
if (paths != null) {
for (TreePath eachPath : paths) {
if (eachPath.getLastPathComponent() instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode eachNode = (DefaultMutableTreeNode)eachPath.getLastPathComponent();
final Object eachElement = getElementFor(eachNode);
if (eachElement != null) {
result.add(eachElement);
}
}
}
}
return result;
}
private void addNext(final Object[] elements,
final int i,
@Nullable final Runnable onDone,
final int[] originalRows,
final boolean deferred,
final boolean scrollToVisible,
final boolean canSmartExpand) {
if (i >= elements.length) {
if (myTree.isSelectionEmpty()) {
myTree.setSelectionRows(originalRows);
}
runDone(onDone);
}
else {
if (!checkDeferred(deferred, onDone)) {
return;
}
doSelect(elements[i], new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
addNext(elements, i + 1, onDone, originalRows, deferred, scrollToVisible, canSmartExpand);
}
}, true, deferred, i == 0, scrollToVisible, canSmartExpand);
}
}
public void select(final Object element, @Nullable final Runnable onDone) {
select(element, onDone, false);
}
public void select(final Object element, @Nullable final Runnable onDone, boolean addToSelection) {
_select(new Object[]{element}, onDone, addToSelection, true, false);
}
private void doSelect(final Object element,
final Runnable onDone,
final boolean addToSelection,
final boolean deferred,
final boolean canBeCentered,
final boolean scrollToVisible,
boolean canSmartExpand) {
final Runnable _onDone = new Runnable() {
public void run() {
if (!checkDeferred(deferred, onDone)) return;
selectVisible(element, onDone, addToSelection, canBeCentered, scrollToVisible);
}
};
_expand(element, _onDone, true, false, canSmartExpand);
}
public void scrollSelectionToVisible(@Nullable Runnable onDone, boolean shouldBeCentered) {
int[] rows = myTree.getSelectionRows();
if (rows == null || rows.length == 0) {
runDone(onDone);
return;
}
Object toSelect = null;
for (int eachRow : rows) {
TreePath path = myTree.getPathForRow(eachRow);
toSelect = getElementFor(path.getLastPathComponent());
if (toSelect != null) break;
}
if (toSelect != null) {
selectVisible(toSelect, onDone, true, shouldBeCentered, true);
}
}
private void selectVisible(Object element, final Runnable onDone, boolean addToSelection, boolean canBeCentered, final boolean scroll) {
final DefaultMutableTreeNode toSelect = getNodeForElement(element, false);
if (toSelect == null) {
runDone(onDone);
return;
}
if (getRootNode() == toSelect && !myTree.isRootVisible()) {
runDone(onDone);
return;
}
final int row = myTree.getRowForPath(new TreePath(toSelect.getPath()));
if (myUpdaterState != null) {
myUpdaterState.addSelection(element);
}
if (Registry.is("ide.tree.autoscrollToVCenter") && canBeCentered) {
runDone(new Runnable() {
public void run() {
TreeUtil.showRowCentered(myTree, row, false, scroll).doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
});
}
});
}
else {
TreeUtil.showAndSelect(myTree, row - 2, row + 2, row, -1, addToSelection, scroll).doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
});
}
}
public void expand(final Object element, @Nullable final Runnable onDone) {
expand(new Object[]{element}, onDone);
}
public void expand(final Object[] element, @Nullable final Runnable onDone) {
expand(element, onDone, false);
}
void expand(final Object element, @Nullable final Runnable onDone, boolean checkIfInStructure) {
_expand(new Object[]{element}, onDone == null ? new EmptyRunnable() : onDone, false, checkIfInStructure, false);
}
void expand(final Object[] element, @Nullable final Runnable onDone, boolean checkIfInStructure) {
_expand(element, onDone == null ? new EmptyRunnable() : onDone, false, checkIfInStructure, false);
}
void _expand(final Object[] element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
final boolean checkIfInStructure,
final boolean canSmartExpand) {
runDone(new Runnable() {
public void run() {
if (element.length == 0) {
runDone(onDone);
return;
}
if (myUpdaterState != null) {
myUpdaterState.clearExpansion();
}
final ActionCallback done = new ActionCallback(element.length);
done.doWhenDone(new Runnable() {
public void run() {
runDone(onDone);
}
}).doWhenRejected(new Runnable() {
public void run() {
runDone(onDone);
}
});
expandNext(element, 0, parentsOnly, checkIfInStructure, canSmartExpand, done);
}
});
}
private void expandNext(final Object[] elements, final int index, final boolean parentsOnly, final boolean checkIfInStricture, final boolean canSmartExpand, final ActionCallback done) {
if (elements.length <= 0) {
done.setDone();
return;
}
if (index >= elements.length) {
return;
}
_expand(elements[index], new Runnable() {
public void run() {
done.setDone();
expandNext(elements, index + 1, parentsOnly, checkIfInStricture, canSmartExpand, done);
}
}, parentsOnly, checkIfInStricture, canSmartExpand);
}
public void collapseChildren(final Object element, @Nullable final Runnable onDone) {
runDone(new Runnable() {
public void run() {
final DefaultMutableTreeNode node = getNodeForElement(element, false);
if (node != null) {
getTree().collapsePath(new TreePath(node.getPath()));
runDone(onDone);
}
}
});
}
private void runDone(@Nullable Runnable done) {
if (done == null) return;
if (isYeildingNow()) {
if (!myYeildingDoneRunnables.contains(done)) {
myYeildingDoneRunnables.add(done);
}
}
else {
done.run();
}
}
private void _expand(final Object element,
@NotNull final Runnable onDone,
final boolean parentsOnly,
boolean checkIfInStructure,
boolean canSmartExpand) {
if (checkIfInStructure && !isInStructure(element)) {
runDone(onDone);
return;
}
if (wasRootNodeInitialized()) {
List<Object> kidsToExpand = new ArrayList<Object>();
Object eachElement = element;
DefaultMutableTreeNode firstVisible = null;
while (true) {
if (!isValid(eachElement)) break;
firstVisible = getNodeForElement(eachElement, true);
if (eachElement != element || !parentsOnly) {
assert !kidsToExpand.contains(eachElement) :
"Not a valid tree structure, walking up the structure gives many entries for element=" +
eachElement +
", root=" +
getTreeStructure().getRootElement();
kidsToExpand.add(eachElement);
}
if (firstVisible != null) break;
eachElement = getTreeStructure().getParentElement(eachElement);
if (eachElement == null) {
firstVisible = null;
break;
}
}
if (firstVisible == null) {
runDone(onDone);
}
else if (kidsToExpand.size() == 0) {
final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)firstVisible.getParent();
if (parentNode != null) {
final TreePath parentPath = new TreePath(parentNode.getPath());
if (!myTree.isExpanded(parentPath)) {
expand(parentPath, canSmartExpand);
}
}
runDone(onDone);
}
else {
processExpand(firstVisible, kidsToExpand, kidsToExpand.size() - 1, onDone, canSmartExpand);
}
}
else {
deferExpansion(element, onDone, parentsOnly, canSmartExpand);
}
}
private void deferExpansion(final Object element, final Runnable onDone, final boolean parentsOnly, final boolean canSmartExpand) {
myDeferredExpansions.add(new Runnable() {
public void run() {
_expand(element, onDone, parentsOnly, false, canSmartExpand);
}
});
}
private void processExpand(final DefaultMutableTreeNode toExpand,
final List kidsToExpand,
final int expandIndex,
@NotNull final Runnable onDone,
final boolean canSmartExpand) {
final Object element = getElementFor(toExpand);
if (element == null) {
runDone(onDone);
return;
}
addNodeAction(element, new NodeAction() {
public void onReady(final DefaultMutableTreeNode node) {
if (node.getChildCount() > 0 && !myTree.isExpanded(new TreePath(node.getPath()))) {
if (!isAutoExpand(node)) {
expand(node, canSmartExpand);
}
}
if (expandIndex <= 0) {
runDone(onDone);
return;
}
final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false);
if (nextNode != null) {
processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand);
}
else {
runDone(onDone);
}
}
}, true);
boolean childrenToUpdate = areChildrenToBeUpdated(toExpand);
boolean expanded = myTree.isExpanded(getPathFor(toExpand));
boolean unbuilt = myUnbuiltNodes.contains(toExpand);
if (expanded) {
if (unbuilt && !childrenToUpdate) {
addSubtreeToUpdate(toExpand);
}
} else {
expand(toExpand, canSmartExpand);
}
if (!unbuilt && !childrenToUpdate) {
processNodeActionsIfReady(toExpand);
}
}
private boolean areChildrenToBeUpdated(DefaultMutableTreeNode node) {
return getUpdater().isEnqueuedToUpdate(node) || isUpdatingParent(node);
}
private String asString(DefaultMutableTreeNode node) {
if (node == null) return null;
StringBuffer children = new StringBuffer(node.toString());
children.append(" [");
for (int i = 0; i < node.getChildCount(); i++) {
children.append(node.getChildAt(i));
if (i < node.getChildCount() - 1) {
children.append(",");
}
}
children.append("]");
return children.toString();
}
@Nullable
public Object getElementFor(Object node) {
if (!(node instanceof DefaultMutableTreeNode)) return null;
return getElementFor((DefaultMutableTreeNode)node);
}
@Nullable
Object getElementFor(DefaultMutableTreeNode node) {
if (node != null) {
final Object o = node.getUserObject();
if (o instanceof NodeDescriptor) {
return getElementFromDescriptor(((NodeDescriptor)o));
}
}
return null;
}
public final boolean isNodeBeingBuilt(final TreePath path) {
return isNodeBeingBuilt(path.getLastPathComponent());
}
public final boolean isNodeBeingBuilt(Object node) {
if (isReleaseRequested()) return false;
return getParentBuiltNode(node) != null;
}
public final DefaultMutableTreeNode getParentBuiltNode(Object node) {
DefaultMutableTreeNode parent = getParentLoading(node);
if (parent != null) return parent;
if (isLoadingParent(node)) return (DefaultMutableTreeNode)node;
final boolean childrenAreNoLoadedYet = myUnbuiltNodes.contains(node);
if (childrenAreNoLoadedYet) {
if (node instanceof DefaultMutableTreeNode) {
final TreePath nodePath = new TreePath(((DefaultMutableTreeNode)node).getPath());
if (!myTree.isExpanded(nodePath)) return null;
}
return (DefaultMutableTreeNode)node;
}
return null;
}
private boolean isLoadingParent(Object node) {
if (!(node instanceof DefaultMutableTreeNode)) return false;
return isLoadedInBackground(getElementFor((DefaultMutableTreeNode)node));
}
public void setTreeStructure(final AbstractTreeStructure treeStructure) {
myTreeStructure = treeStructure;
clearUpdaterState();
}
public AbstractTreeUpdater getUpdater() {
return myUpdater;
}
public void setUpdater(final AbstractTreeUpdater updater) {
myUpdater = updater;
if (updater != null && myUpdateIfInactive) {
updater.showNotify();
}
if (myUpdater != null) {
myUpdater.setPassThroughMode(myPassthroughMode);
}
}
public DefaultMutableTreeNode getRootNode() {
return myRootNode;
}
public void setRootNode(@NotNull final DefaultMutableTreeNode rootNode) {
myRootNode = rootNode;
}
private void dropUpdaterStateIfExternalChange() {
if (!isInnerChange()) {
clearUpdaterState();
myAutoExpandRoots.clear();
}
}
void clearUpdaterState() {
myUpdaterState = null;
}
private void createMapping(Object element, DefaultMutableTreeNode node) {
if (!myElementToNodeMap.containsKey(element)) {
myElementToNodeMap.put(element, node);
}
else {
final Object value = myElementToNodeMap.get(element);
final List<DefaultMutableTreeNode> nodes;
if (value instanceof DefaultMutableTreeNode) {
nodes = new ArrayList<DefaultMutableTreeNode>();
nodes.add((DefaultMutableTreeNode)value);
myElementToNodeMap.put(element, nodes);
}
else {
nodes = (List<DefaultMutableTreeNode>)value;
}
nodes.add(node);
}
}
private void removeMapping(Object element, DefaultMutableTreeNode node, @Nullable Object elementToPutNodeActionsFor) {
final Object value = myElementToNodeMap.get(element);
if (value != null) {
if (value instanceof DefaultMutableTreeNode) {
if (value.equals(node)) {
myElementToNodeMap.remove(element);
}
}
else {
List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
final boolean reallyRemoved = nodes.remove(node);
if (reallyRemoved) {
if (nodes.isEmpty()) {
myElementToNodeMap.remove(element);
}
}
}
}
remapNodeActions(element, elementToPutNodeActionsFor);
}
private void remapNodeActions(Object element, Object elementToPutNodeActionsFor) {
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeActions);
_remapNodeActions(element, elementToPutNodeActionsFor, myNodeChildrenActions);
}
private void _remapNodeActions(Object element, Object elementToPutNodeActionsFor, final Map<Object, List<NodeAction>> nodeActions) {
final List<NodeAction> actions = nodeActions.get(element);
nodeActions.remove(element);
if (elementToPutNodeActionsFor != null && actions != null) {
nodeActions.put(elementToPutNodeActionsFor, actions);
}
}
private DefaultMutableTreeNode getFirstNode(Object element) {
return findNode(element, 0);
}
private DefaultMutableTreeNode findNode(final Object element, int startIndex) {
final Object value = getBuilder().findNodeByElement(element);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
return startIndex == 0 ? (DefaultMutableTreeNode)value : null;
}
final List<DefaultMutableTreeNode> nodes = (List<DefaultMutableTreeNode>)value;
return startIndex < nodes.size() ? nodes.get(startIndex) : null;
}
protected Object findNodeByElement(Object element) {
if (myElementToNodeMap.containsKey(element)) {
return myElementToNodeMap.get(element);
}
try {
TREE_NODE_WRAPPER.setValue(element);
return myElementToNodeMap.get(TREE_NODE_WRAPPER);
}
finally {
TREE_NODE_WRAPPER.setValue(null);
}
}
private DefaultMutableTreeNode findNodeForChildElement(DefaultMutableTreeNode parentNode, Object element) {
final Object value = myElementToNodeMap.get(element);
if (value == null) {
return null;
}
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode elementNode = (DefaultMutableTreeNode)value;
return parentNode.equals(elementNode.getParent()) ? elementNode : null;
}
final List<DefaultMutableTreeNode> allNodesForElement = (List<DefaultMutableTreeNode>)value;
for (final DefaultMutableTreeNode elementNode : allNodesForElement) {
if (parentNode.equals(elementNode.getParent())) {
return elementNode;
}
}
return null;
}
public void cancelBackgroundLoading() {
if (myWorker != null) {
myWorker.cancelTasks();
clearWorkerTasks();
}
clearNodeActions();
}
private void addNodeAction(Object element, NodeAction action, boolean shouldChildrenBeReady) {
_addNodeAction(element, action, myNodeActions);
if (shouldChildrenBeReady) {
_addNodeAction(element, action, myNodeChildrenActions);
}
}
private void _addNodeAction(Object element, NodeAction action, Map<Object, List<NodeAction>> map) {
maybeSetBusyAndScheduleWaiterForReady(true);
List<NodeAction> list = map.get(element);
if (list == null) {
list = new ArrayList<NodeAction>();
map.put(element, list);
}
list.add(action);
}
private void cleanUpNow() {
if (isReleaseRequested()) return;
final UpdaterTreeState state = new UpdaterTreeState(this);
myTree.collapsePath(new TreePath(myTree.getModel().getRoot()));
myTree.clearSelection();
getRootNode().removeAllChildren();
myRootNodeWasInitialized = false;
clearNodeActions();
myElementToNodeMap.clear();
myDeferredSelections.clear();
myDeferredExpansions.clear();
myLoadedInBackground.clear();
myUnbuiltNodes.clear();
myUpdateFromRootRequested = true;
if (myWorker != null) {
Disposer.dispose(myWorker);
myWorker = null;
}
myTree.invalidate();
state.restore(null);
}
public AbstractTreeUi setClearOnHideDelay(final long clearOnHideDelay) {
myClearOnHideDelay = clearOnHideDelay;
return this;
}
public void setJantorPollPeriod(final long time) {
myJanitorPollPeriod = time;
}
public void setCheckStructure(final boolean checkStructure) {
myCheckStructure = checkStructure;
}
private class MySelectionListener implements TreeSelectionListener {
public void valueChanged(final TreeSelectionEvent e) {
dropUpdaterStateIfExternalChange();
}
}
private class MyExpansionListener implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent event) {
dropUpdaterStateIfExternalChange();
TreePath path = event.getPath();
if (myRequestedExpand != null && !myRequestedExpand.equals(path)) return;
//myRequestedExpand = null;
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (!myUnbuiltNodes.contains(node)) {
removeLoading(node, false);
Set<DefaultMutableTreeNode> childrenToUpdate = new HashSet<DefaultMutableTreeNode>();
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode each = (DefaultMutableTreeNode)node.getChildAt(i);
if (myUnbuiltNodes.contains(each)) {
makeLoadingOrLeafIfNoChildren(each);
childrenToUpdate.add(each);
}
}
if (childrenToUpdate.size() > 0) {
for (DefaultMutableTreeNode each : childrenToUpdate) {
maybeUpdateSubtreeToUpdate(each);
}
}
}
else {
getBuilder().expandNodeChildren(node);
}
processSmartExpand(node, canSmartExpand(node, true), false);
processNodeActionsIfReady(node);
}
public void treeCollapsed(TreeExpansionEvent e) {
dropUpdaterStateIfExternalChange();
final TreePath path = e.getPath();
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (!(node.getUserObject() instanceof NodeDescriptor)) return;
TreePath pathToSelect = null;
if (isSelectionInside(node)) {
pathToSelect = new TreePath(node.getPath());
}
NodeDescriptor descriptor = getDescriptorFrom(node);
if (getBuilder().isDisposeOnCollapsing(descriptor)) {
runDone(new Runnable() {
public void run() {
if (isDisposed(node)) return;
TreePath nodePath = new TreePath(node.getPath());
if (myTree.isExpanded(nodePath)) return;
removeChildren(node);
makeLoadingOrLeafIfNoChildren(node);
}
});
if (node.equals(getRootNode())) {
if (myTree.isRootVisible()) {
//todo kirillk to investigate -- should be done by standard selction move
//addSelectionPath(new TreePath(getRootNode().getPath()), true, Condition.FALSE);
}
}
else {
myTreeModel.reload(node);
}
}
if (pathToSelect != null && myTree.isSelectionEmpty()) {
addSelectionPath(pathToSelect, true, Condition.FALSE, null);
}
}
private void removeChildren(DefaultMutableTreeNode node) {
EnumerationCopy copy = new EnumerationCopy(node.children());
while (copy.hasMoreElements()) {
disposeNode((DefaultMutableTreeNode)copy.nextElement());
}
node.removeAllChildren();
myTreeModel.nodeStructureChanged(node);
}
}
private void maybeUpdateSubtreeToUpdate(final DefaultMutableTreeNode subtreeRoot) {
if (!myUnbuiltNodes.contains(subtreeRoot)) return;
TreePath path = getPathFor(subtreeRoot);
if (myTree.getRowForPath(path) == -1) return;
DefaultMutableTreeNode parent = getParentBuiltNode(subtreeRoot);
if (parent == null) {
addSubtreeToUpdate(subtreeRoot);
} else if (parent != subtreeRoot) {
addNodeAction(getElementFor(subtreeRoot), new NodeAction() {
public void onReady(DefaultMutableTreeNode parent) {
maybeUpdateSubtreeToUpdate(subtreeRoot);
}
}, true);
}
}
private boolean isSelectionInside(DefaultMutableTreeNode parent) {
TreePath path = new TreePath(myTreeModel.getPathToRoot(parent));
TreePath[] paths = myTree.getSelectionPaths();
if (paths == null) return false;
for (TreePath path1 : paths) {
if (path.isDescendant(path1)) return true;
}
return false;
}
public boolean isInStructure(@Nullable Object element) {
Object eachParent = element;
while (eachParent != null) {
if (getTreeStructure().getRootElement().equals(eachParent)) return true;
eachParent = getTreeStructure().getParentElement(eachParent);
}
return false;
}
interface NodeAction {
void onReady(DefaultMutableTreeNode node);
}
public void setCanYield(final boolean canYield) {
myCanYield = canYield;
}
public Collection<TreeUpdatePass> getYeildingPasses() {
return myYeildingPasses;
}
public boolean isBuilt(Object element) {
if (!myElementToNodeMap.containsKey(element)) return false;
final Object node = myElementToNodeMap.get(element);
return !myUnbuiltNodes.contains(node);
}
static class LoadedChildren {
private List myElements;
private Map<Object, NodeDescriptor> myDescriptors = new HashMap<Object, NodeDescriptor>();
private Map<NodeDescriptor, Boolean> myChanges = new HashMap<NodeDescriptor, Boolean>();
LoadedChildren(Object[] elements) {
myElements = Arrays.asList(elements != null ? elements : ArrayUtil.EMPTY_OBJECT_ARRAY);
}
void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) {
assert myElements.contains(element);
myDescriptors.put(element, descriptor);
myChanges.put(descriptor, isChanged);
}
List getElements() {
return myElements;
}
NodeDescriptor getDescriptor(Object element) {
return myDescriptors.get(element);
}
@Override
public String toString() {
return Arrays.asList(myElements) + "->" + myChanges;
}
public boolean isUpdated(Object element) {
NodeDescriptor desc = getDescriptor(element);
return myChanges.get(desc);
}
}
UpdaterTreeState getUpdaterState() {
return myUpdaterState;
}
private ActionCallback addReadyCallback(Object requestor) {
synchronized (myReadyCallbacks) {
ActionCallback cb = myReadyCallbacks.get(requestor);
if (cb == null) {
cb = new ActionCallback();
myReadyCallbacks.put(requestor, cb);
}
return cb;
}
}
private ActionCallback[] getReadyCallbacks(boolean clear) {
synchronized (myReadyCallbacks) {
ActionCallback[] result = myReadyCallbacks.values().toArray(new ActionCallback[myReadyCallbacks.size()]);
if (clear) {
myReadyCallbacks.clear();
}
return result;
}
}
private long getComparatorStamp() {
if (myNodeDescriptorComparator instanceof NodeDescriptor.NodeComparator) {
long currentComparatorStamp = ((NodeDescriptor.NodeComparator)myNodeDescriptorComparator).getStamp();
if (currentComparatorStamp > myLastComparatorStamp) {
myOwnComparatorStamp = Math.max(myOwnComparatorStamp, currentComparatorStamp) + 1;
}
myLastComparatorStamp = currentComparatorStamp;
return Math.max(currentComparatorStamp, myOwnComparatorStamp);
}
else {
return myOwnComparatorStamp;
}
}
public void incComparatorStamp() {
myOwnComparatorStamp = getComparatorStamp() + 1;
}
public static class UpdateInfo {
NodeDescriptor myDescriptor;
TreeUpdatePass myPass;
boolean myCanSmartExpand;
boolean myWasExpanded;
boolean myForceUpdate;
boolean myDescriptorIsUpToDate;
public UpdateInfo(NodeDescriptor descriptor,
TreeUpdatePass pass,
boolean canSmartExpand,
boolean wasExpanded,
boolean forceUpdate,
boolean descriptorIsUpToDate) {
myDescriptor = descriptor;
myPass = pass;
myCanSmartExpand = canSmartExpand;
myWasExpanded = wasExpanded;
myForceUpdate = forceUpdate;
myDescriptorIsUpToDate = descriptorIsUpToDate;
}
synchronized NodeDescriptor getDescriptor() {
return myDescriptor;
}
synchronized TreeUpdatePass getPass() {
return myPass;
}
synchronized boolean isCanSmartExpand() {
return myCanSmartExpand;
}
synchronized boolean isWasExpanded() {
return myWasExpanded;
}
synchronized boolean isForceUpdate() {
return myForceUpdate;
}
synchronized boolean isDescriptorIsUpToDate() {
return myDescriptorIsUpToDate;
}
public synchronized void apply(UpdateInfo updateInfo) {
myDescriptor = updateInfo.myDescriptor;
myPass = updateInfo.myPass;
myCanSmartExpand = updateInfo.myCanSmartExpand;
myWasExpanded = updateInfo.myWasExpanded;
myForceUpdate = updateInfo.myForceUpdate;
myDescriptorIsUpToDate = updateInfo.myDescriptorIsUpToDate;
}
public String toString() {
return "UpdateInfo: desc=" + myDescriptor + " pass=" + myPass + " canSmartExpand=" + myCanSmartExpand + " wasExpanded=" + myWasExpanded + " forceUpdate=" + myForceUpdate + " descriptorUpToDate=" + myDescriptorIsUpToDate;
}
}
public void setPassthroughMode(boolean passthrough) {
myPassthroughMode = passthrough;
AbstractTreeUpdater updater = getUpdater();
if (updater != null) {
updater.setPassThroughMode(myPassthroughMode);
}
if (!isUnitTestingMode() && passthrough) {
// TODO: this assertion should be restored back as soon as possible [JamTreeTableView should be rewritten, etc]
//LOG.error("Pass-through mode for TreeUi is allowed only for unit test mode");
}
}
public boolean isPassthroughMode() {
return myPassthroughMode;
}
private boolean isUnitTestingMode() {
Application app = ApplicationManager.getApplication();
return app != null && app.isUnitTestMode();
}
private void addModelListenerToDianoseAccessOutsideEdt() {
myTreeModel.addTreeModelListener(new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeNodesInserted(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeNodesRemoved(TreeModelEvent e) {
assertIsDispatchThread();
}
public void treeStructureChanged(TreeModelEvent e) {
assertIsDispatchThread();
}
});
}
}
| TreeUi: tolarance against null element to select
| platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java | TreeUi: tolarance against null element to select |
|
Java | apache-2.0 | 2d7eabb7aadaa2cae49635c86ba3f193a28ca90b | 0 | FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,semonte/intellij-community,semonte/intellij-community,semonte/intellij-community,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,signed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,allotria/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.run;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Output;
import com.intellij.execution.OutputListener;
import com.intellij.execution.RunContentExecutor;
import com.intellij.execution.configurations.EncodingEnvironmentUtil;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.ParamsGroup;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.NotNullFunction;
import com.jetbrains.python.HelperPackage;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.buildout.BuildoutFacet;
import com.jetbrains.python.console.PydevConsoleRunner;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* TODO: Use {@link com.jetbrains.python.run.PythonRunner} instead of this class? At already supports rerun and other things
* Base class for tasks which are run from PyCharm with results displayed in a toolwindow (manage.py, setup.py, Sphinx etc).
*
* @author yole
*/
public class PythonTask {
/**
* Mils we wait to process to be stopped when "rerun" called
*/
private static final long TIME_TO_WAIT_PROCESS_STOP = 2000L;
private static final int TIMEOUT_TO_WAIT_FOR_TASK = 30000;
protected final Module myModule;
private final Sdk mySdk;
private String myWorkingDirectory;
private String myRunnerScript;
private HelperPackage myHelper = null;
private List<String> myParameters = new ArrayList<>();
private final String myRunTabTitle;
private String myHelpId;
private Runnable myAfterCompletion;
public PythonTask(Module module, String runTabTitle) throws ExecutionException {
this(module, runTabTitle, PythonSdkType.findPythonSdk(module));
}
@NotNull
public static PythonTask create(@NotNull final Module module,
@NotNull final String runTabTitle,
@NotNull final Sdk sdk) {
// Ctor throws checked exception which is not good, so this wrapper saves user from dumb code
try {
return new PythonTask(module, runTabTitle, sdk);
}
catch (final ExecutionException ignored) {
throw new AssertionError("Exception thrown file should not be");
}
}
public PythonTask(final Module module, final String runTabTitle, @Nullable final Sdk sdk) throws ExecutionException {
myModule = module;
myRunTabTitle = runTabTitle;
mySdk = sdk;
if (mySdk == null) { // TODO: Get rid of such a weird contract
throw new ExecutionException("Cannot find Python interpreter for selected module");
}
}
public String getWorkingDirectory() {
return myWorkingDirectory;
}
public void setWorkingDirectory(String workingDirectory) {
myWorkingDirectory = workingDirectory;
}
public void setRunnerScript(String script) {
myRunnerScript = script;
}
public void setHelper(HelperPackage helper) {
myHelper = helper;
}
public void setParameters(List<String> parameters) {
myParameters = parameters;
}
public void setHelpId(String helpId) {
myHelpId = helpId;
}
public void setAfterCompletion(Runnable afterCompletion) {
myAfterCompletion = afterCompletion;
}
/**
* @param env environment variables to be passed to process or null if nothing should be passed
*/
public ProcessHandler createProcess(@Nullable final Map<String, String> env) throws ExecutionException {
final GeneralCommandLine commandLine = createCommandLine();
if (env != null) {
commandLine.getEnvironment().putAll(env);
}
PydevConsoleRunner.setCorrectStdOutEncoding(commandLine, myModule.getProject()); // To support UTF-8 output
ProcessHandler handler;
if (PySdkUtil.isRemote(mySdk)) {
assert mySdk != null;
handler = new PyRemoteProcessStarter().startRemoteProcess(mySdk, commandLine, myModule.getProject(), null);
}
else {
EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(commandLine);
handler = PythonProcessRunner.createProcessHandlingCtrlC(commandLine);
ProcessTerminatedListener.attach(handler);
}
return handler;
}
/**
* Runs command using env vars from facet
* @param consoleView console view to be used for command or null to create new
* @throws ExecutionException failed to execute command
*/
public void run(@Nullable final ConsoleView consoleView) throws ExecutionException {
run(createCommandLine().getEnvironment(), consoleView);
}
public GeneralCommandLine createCommandLine() {
GeneralCommandLine cmd = new GeneralCommandLine();
if (myWorkingDirectory != null) {
cmd.setWorkDirectory(myWorkingDirectory);
}
String homePath = mySdk.getHomePath();
if (homePath != null) {
homePath = FileUtil.toSystemDependentName(homePath);
}
PythonCommandLineState.createStandardGroups(cmd);
ParamsGroup scriptParams = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
assert scriptParams != null;
Map<String, String> env = cmd.getEnvironment();
if (!SystemInfo.isWindows && !PySdkUtil.isRemote(mySdk)) {
cmd.setExePath("bash");
ParamsGroup bashParams = cmd.getParametersList().addParamsGroupAt(0, "Bash");
bashParams.addParameter("-cl");
NotNullFunction<String, String> escaperFunction = StringUtil.escaper(false, "|>$\"'& ");
StringBuilder paramString;
if (myHelper != null) {
paramString = new StringBuilder(escaperFunction.fun(homePath) + " " + escaperFunction.fun(myHelper.asParamString()));
myHelper.addToPythonPath(cmd.getEnvironment());
}
else {
paramString = new StringBuilder(escaperFunction.fun(homePath) + " " + escaperFunction.fun(myRunnerScript));
}
for (String p : myParameters) {
paramString.append(" ").append(p);
}
bashParams.addParameter(paramString.toString());
}
else {
cmd.setExePath(homePath);
if (myHelper != null) {
myHelper.addToGroup(scriptParams, cmd);
}
else {
scriptParams.addParameter(myRunnerScript);
}
scriptParams.addParameters(myParameters.stream().filter( o -> o != null).collect(Collectors.toList()));
}
PythonEnvUtil.setPythonUnbuffered(env);
if (homePath != null) {
PythonEnvUtil.resetHomePathChanges(homePath, env);
}
List<String> pythonPath = setupPythonPath();
PythonCommandLineState.initPythonPath(cmd, true, pythonPath, homePath);
BuildoutFacet facet = BuildoutFacet.getInstance(myModule);
if (facet != null) {
facet.patchCommandLineForBuildout(cmd);
}
return cmd;
}
protected List<String> setupPythonPath() {
return setupPythonPath(true, true);
}
protected List<String> setupPythonPath(final boolean addContent, final boolean addSource) {
final List<String> pythonPath = Lists.newArrayList(PythonCommandLineState.getAddedPaths(mySdk));
pythonPath.addAll(PythonCommandLineState.collectPythonPath(myModule, addContent, addSource));
return pythonPath;
}
/**
* @param env environment variables to be passed to process or null if nothing should be passed
* @param consoleView console to run this task on. New console will be used if no console provided.
*/
public void run(@Nullable final Map<String, String> env, @Nullable final ConsoleView consoleView) throws ExecutionException {
final ProcessHandler process = createProcess(env);
final Project project = myModule.getProject();
new RunContentExecutor(project, process)
.withFilter(new PythonTracebackFilter(project))
.withConsole(consoleView)
.withTitle(myRunTabTitle)
.withRerun(() -> {
try {
process.destroyProcess(); // Stop process before rerunning it
if (process.waitFor(TIME_TO_WAIT_PROCESS_STOP)) {
this.run(env, consoleView);
}
else {
Messages.showErrorDialog(PyBundle.message("unable.to.stop"), myRunTabTitle);
}
}
catch (ExecutionException e) {
Messages.showErrorDialog(e.getMessage(), myRunTabTitle);
}
})
.withStop(() -> process.destroyProcess(), () -> !process.isProcessTerminated()
)
.withAfterCompletion(myAfterCompletion)
.withHelpId(myHelpId)
.run();
}
/**
* Runs task with out console
* @return stdout
* @throws ExecutionException in case of error. Consider using {@link com.intellij.execution.util.ExecutionErrorDialog}
*/
@NotNull
public final String runNoConsole() throws ExecutionException {
final ProcessHandler process = createProcess(new HashMap<>());
final OutputListener listener = new OutputListener();
process.addProcessListener(listener);
process.startNotify();
process.waitFor(TIMEOUT_TO_WAIT_FOR_TASK);
final Output output = listener.getOutput();
final int exitCode = output.getExitCode();
if (exitCode == 0) {
return output.getStdout();
}
throw new ExecutionException(String.format("Error on python side. " +
"Exit code: %s, err: %s out: %s", exitCode, output.getStderr(), output.getStdout()));
}
}
| python/src/com/jetbrains/python/run/PythonTask.java | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.run;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Output;
import com.intellij.execution.OutputListener;
import com.intellij.execution.RunContentExecutor;
import com.intellij.execution.configurations.EncodingEnvironmentUtil;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.ParamsGroup;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.NotNullFunction;
import com.jetbrains.python.HelperPackage;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.buildout.BuildoutFacet;
import com.jetbrains.python.console.PydevConsoleRunner;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* TODO: Use {@link com.jetbrains.python.run.PythonRunner} instead of this class? At already supports rerun and other things
* Base class for tasks which are run from PyCharm with results displayed in a toolwindow (manage.py, setup.py, Sphinx etc).
*
* @author yole
*/
public class PythonTask {
/**
* Mils we wait to process to be stopped when "rerun" called
*/
private static final long TIME_TO_WAIT_PROCESS_STOP = 2000L;
private static final int TIMEOUT_TO_WAIT_FOR_TASK = 30000;
protected final Module myModule;
private final Sdk mySdk;
private String myWorkingDirectory;
private String myRunnerScript;
private HelperPackage myHelper = null;
private List<String> myParameters = new ArrayList<>();
private final String myRunTabTitle;
private String myHelpId;
private Runnable myAfterCompletion;
public PythonTask(Module module, String runTabTitle) throws ExecutionException {
this(module, runTabTitle, PythonSdkType.findPythonSdk(module));
}
@NotNull
public static PythonTask create(@NotNull final Module module,
@NotNull final String runTabTitle,
@NotNull final Sdk sdk) {
// Ctor throws checked exception which is not good, so this wrapper saves user from dumb code
try {
return new PythonTask(module, runTabTitle, sdk);
}
catch (final ExecutionException ignored) {
throw new AssertionError("Exception thrown file should not be");
}
}
public PythonTask(final Module module, final String runTabTitle, @Nullable final Sdk sdk) throws ExecutionException {
myModule = module;
myRunTabTitle = runTabTitle;
mySdk = sdk;
if (mySdk == null) { // TODO: Get rid of such a weird contract
throw new ExecutionException("Cannot find Python interpreter for selected module");
}
}
public String getWorkingDirectory() {
return myWorkingDirectory;
}
public void setWorkingDirectory(String workingDirectory) {
myWorkingDirectory = workingDirectory;
}
public void setRunnerScript(String script) {
myRunnerScript = script;
}
public void setHelper(HelperPackage helper) {
myHelper = helper;
}
public void setParameters(List<String> parameters) {
myParameters = parameters;
}
public void setHelpId(String helpId) {
myHelpId = helpId;
}
public void setAfterCompletion(Runnable afterCompletion) {
myAfterCompletion = afterCompletion;
}
/**
* @param env environment variables to be passed to process or null if nothing should be passed
*/
public ProcessHandler createProcess(@Nullable final Map<String, String> env) throws ExecutionException {
final GeneralCommandLine commandLine = createCommandLine();
if (env != null) {
commandLine.getEnvironment().putAll(env);
}
PydevConsoleRunner.setCorrectStdOutEncoding(commandLine, myModule.getProject()); // To support UTF-8 output
ProcessHandler handler;
if (PySdkUtil.isRemote(mySdk)) {
assert mySdk != null;
handler = new PyRemoteProcessStarter().startRemoteProcess(mySdk, commandLine, myModule.getProject(), null);
}
else {
EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(commandLine);
handler = PythonProcessRunner.createProcessHandlingCtrlC(commandLine);
ProcessTerminatedListener.attach(handler);
}
return handler;
}
/**
* Runs command using env vars from facet
* @param consoleView console view to be used for command or null to create new
* @throws ExecutionException failed to execute command
*/
public void run(@Nullable final ConsoleView consoleView) throws ExecutionException {
run(createCommandLine().getEnvironment(), consoleView);
}
public GeneralCommandLine createCommandLine() {
GeneralCommandLine cmd = new GeneralCommandLine();
if (myWorkingDirectory != null) {
cmd.setWorkDirectory(myWorkingDirectory);
}
String homePath = mySdk.getHomePath();
if (homePath != null) {
homePath = FileUtil.toSystemDependentName(homePath);
}
PythonCommandLineState.createStandardGroups(cmd);
ParamsGroup scriptParams = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
assert scriptParams != null;
Map<String, String> env = cmd.getEnvironment();
if (!SystemInfo.isWindows && !PySdkUtil.isRemote(mySdk)) {
cmd.setExePath("bash");
ParamsGroup bashParams = cmd.getParametersList().addParamsGroupAt(0, "Bash");
bashParams.addParameter("-cl");
NotNullFunction<String, String> escaperFunction = StringUtil.escaper(false, "|>$\"'& ");
StringBuilder paramString;
if (myHelper != null) {
paramString = new StringBuilder(escaperFunction.fun(homePath) + " " + escaperFunction.fun(myHelper.asParamString()));
myHelper.addToPythonPath(cmd.getEnvironment());
}
else {
paramString = new StringBuilder(escaperFunction.fun(homePath) + " " + escaperFunction.fun(myRunnerScript));
}
for (String p : myParameters) {
paramString.append(" ").append(p);
}
bashParams.addParameter(paramString.toString());
}
else {
cmd.setExePath(homePath);
if (myHelper != null) {
myHelper.addToGroup(scriptParams, cmd);
}
else {
scriptParams.addParameter(myRunnerScript);
}
scriptParams.addParameters(myParameters);
}
PythonEnvUtil.setPythonUnbuffered(env);
if (homePath != null) {
PythonEnvUtil.resetHomePathChanges(homePath, env);
}
List<String> pythonPath = setupPythonPath();
PythonCommandLineState.initPythonPath(cmd, true, pythonPath, homePath);
BuildoutFacet facet = BuildoutFacet.getInstance(myModule);
if (facet != null) {
facet.patchCommandLineForBuildout(cmd);
}
return cmd;
}
protected List<String> setupPythonPath() {
return setupPythonPath(true, true);
}
protected List<String> setupPythonPath(final boolean addContent, final boolean addSource) {
final List<String> pythonPath = Lists.newArrayList(PythonCommandLineState.getAddedPaths(mySdk));
pythonPath.addAll(PythonCommandLineState.collectPythonPath(myModule, addContent, addSource));
return pythonPath;
}
/**
* @param env environment variables to be passed to process or null if nothing should be passed
* @param consoleView console to run this task on. New console will be used if no console provided.
*/
public void run(@Nullable final Map<String, String> env, @Nullable final ConsoleView consoleView) throws ExecutionException {
final ProcessHandler process = createProcess(env);
final Project project = myModule.getProject();
new RunContentExecutor(project, process)
.withFilter(new PythonTracebackFilter(project))
.withConsole(consoleView)
.withTitle(myRunTabTitle)
.withRerun(() -> {
try {
process.destroyProcess(); // Stop process before rerunning it
if (process.waitFor(TIME_TO_WAIT_PROCESS_STOP)) {
this.run(env, consoleView);
}
else {
Messages.showErrorDialog(PyBundle.message("unable.to.stop"), myRunTabTitle);
}
}
catch (ExecutionException e) {
Messages.showErrorDialog(e.getMessage(), myRunTabTitle);
}
})
.withStop(() -> process.destroyProcess(), () -> !process.isProcessTerminated()
)
.withAfterCompletion(myAfterCompletion)
.withHelpId(myHelpId)
.run();
}
/**
* Runs task with out console
* @return stdout
* @throws ExecutionException in case of error. Consider using {@link com.intellij.execution.util.ExecutionErrorDialog}
*/
@NotNull
public final String runNoConsole() throws ExecutionException {
final ProcessHandler process = createProcess(new HashMap<>());
final OutputListener listener = new OutputListener();
process.addProcessListener(listener);
process.startNotify();
process.waitFor(TIMEOUT_TO_WAIT_FOR_TASK);
final Output output = listener.getOutput();
final int exitCode = output.getExitCode();
if (exitCode == 0) {
return output.getStdout();
}
throw new ExecutionException(String.format("Error on python side. " +
"Exit code: %s, err: %s out: %s", exitCode, output.getStderr(), output.getStdout()));
}
}
| PY-21617, PY-21614: Project name not passed to Django in plugin leading to bugs
* Plugin uses different GUI, so project name lost and project generation failed
* We know check all params are not null when passing to project generation task
| python/src/com/jetbrains/python/run/PythonTask.java | PY-21617, PY-21614: Project name not passed to Django in plugin leading to bugs |
|
Java | apache-2.0 | 115f4c84d92535a4232e4e50cb4d386731678853 | 0 | mglukhikh/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,caot/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,izonder/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,holmes/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,caot/intellij-community,asedunov/intellij-community,slisson/intellij-community,vladmm/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,vladmm/intellij-community,kool79/intellij-community,asedunov/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,holmes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,Distrotech/intellij-community,kool79/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,robovm/robovm-studio,dslomov/intellij-community,kdwink/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,holmes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,izonder/intellij-community,clumsy/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,petteyg/intellij-community,jagguli/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,signed/intellij-community,retomerz/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,holmes/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,caot/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,clumsy/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,allotria/intellij-community,kool79/intellij-community,supersven/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,fnouama/intellij-community,holmes/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,petteyg/intellij-community,da1z/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,signed/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,jagguli/intellij-community,signed/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,FHannes/intellij-community,semonte/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,petteyg/intellij-community,kool79/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,FHannes/intellij-community,apixandru/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,allotria/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,signed/intellij-community,Lekanich/intellij-community,da1z/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,dslomov/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,supersven/intellij-community,supersven/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,signed/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,allotria/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,caot/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,retomerz/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,vvv1559/intellij-community,slisson/intellij-community,samthor/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kool79/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,holmes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,allotria/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,semonte/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,amith01994/intellij-community,blademainer/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,izonder/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,samthor/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,xfournet/intellij-community,caot/intellij-community,robovm/robovm-studio,jagguli/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,dslomov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,da1z/intellij-community,amith01994/intellij-community,xfournet/intellij-community,da1z/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,holmes/intellij-community,wreckJ/intellij-community,signed/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,diorcety/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,da1z/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,kool79/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,supersven/intellij-community,signed/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,semonte/intellij-community,slisson/intellij-community,fitermay/intellij-community,caot/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,kdwink/intellij-community,izonder/intellij-community,allotria/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,holmes/intellij-community,asedunov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,caot/intellij-community,signed/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,supersven/intellij-community,asedunov/intellij-community,fnouama/intellij-community,signed/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,diorcety/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,petteyg/intellij-community,signed/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,apixandru/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,apixandru/intellij-community,robovm/robovm-studio,petteyg/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,robovm/robovm-studio,FHannes/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,kdwink/intellij-community,adedayo/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,da1z/intellij-community,suncycheng/intellij-community,da1z/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,signed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,caot/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,da1z/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,vladmm/intellij-community,signed/intellij-community,izonder/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,diorcety/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,hurricup/intellij-community,apixandru/intellij-community,slisson/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,xfournet/intellij-community,dslomov/intellij-community,caot/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,supersven/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,allotria/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,xfournet/intellij-community,adedayo/intellij-community,amith01994/intellij-community,izonder/intellij-community,vladmm/intellij-community,vladmm/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.actions;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.execution.Executor;
import com.intellij.execution.ExecutorRegistry;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ChooseRunConfigurationPopup;
import com.intellij.execution.actions.ExecutorProvider;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.impl.RunDialog;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.ide.SearchTopHitProvider;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.laf.darcula.ui.DarculaTextBorder;
import com.intellij.ide.ui.laf.darcula.ui.DarculaTextFieldUI;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.ide.util.DefaultPsiElementCellRenderer;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.gotoByName.*;
import com.intellij.lang.Language;
import com.intellij.lang.LanguagePsiElementExternalizer;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actions.TextComponentEditorAction;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.MacKeymapUtil;
import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ComponentPopupBuilder;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFilePathWrapper;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.OnOffButton;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.PopupPositionManager;
import com.intellij.util.*;
import com.intellij.util.text.Matcher;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware, DataProvider, RightAlignedToolbarAction {
public static final String SE_HISTORY_KEY = "SearchEverywhereHistoryKey";
public static final int SEARCH_FIELD_COLUMNS = 25;
private static final int MAX_CLASSES = 6;
private static final int MAX_FILES = 6;
private static final int MAX_RUN_CONFIGURATION = 6;
private static final int MAX_TOOL_WINDOWS = 4;
private static final int MAX_SYMBOLS = 6;
private static final int MAX_SETTINGS = 5;
private static final int MAX_ACTIONS = 5;
private static final int MAX_RECENT_FILES = 10;
private static final int DEFAULT_MORE_STEP_COUNT = 15;
public static final int MAX_SEARCH_EVERYWHERE_HISTORY = 50;
private static final int POPUP_MAX_WIDTH = 600;
private static final Logger LOG = Logger.getInstance("#" + SearchEverywhereAction.class.getName());
private SearchEverywhereAction.MyListRenderer myRenderer;
MySearchTextField myPopupField;
private volatile GotoClassModel2 myClassModel;
private volatile GotoFileModel myFileModel;
private volatile GotoActionItemProvider myActionProvider;
private volatile GotoSymbolModel2 mySymbolsModel;
private Component myFocusComponent;
private JBPopup myPopup;
private Map<String, String> myConfigurables = new HashMap<String, String>();
private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, ApplicationManager.getApplication());
private Alarm myUpdateAlarm = new Alarm(ApplicationManager.getApplication());
private JBList myList;
private JCheckBox myNonProjectCheckBox;
private AnActionEvent myActionEvent;
private Component myContextComponent;
private CalcThread myCalcThread;
private static AtomicBoolean ourShiftIsPressed = new AtomicBoolean(false);
private static AtomicBoolean showAll = new AtomicBoolean(false);
private volatile ActionCallback myCurrentWorker = ActionCallback.DONE;
private int myHistoryIndex = 0;
boolean mySkipFocusGain = false;
static {
ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_SEARCH_EVERYWHERE, KeyEvent.VK_SHIFT, -1);
IdeEventQueue.getInstance().addPostprocessor(new IdeEventQueue.EventDispatcher() {
@Override
public boolean dispatch(AWTEvent event) {
if (event instanceof KeyEvent) {
final int keyCode = ((KeyEvent)event).getKeyCode();
if (keyCode == KeyEvent.VK_SHIFT) {
ourShiftIsPressed.set(event.getID() == KeyEvent.KEY_PRESSED);
}
}
return false;
}
}, null);
}
private volatile JBPopup myBalloon;
private int myPopupActualWidth;
private Component myFocusOwner;
private ChooseByNamePopup myFileChooseByName;
private ChooseByNamePopup myClassChooseByName;
private ChooseByNamePopup mySymbolsChooseByName;
private Editor myEditor;
private PsiFile myFile;
private HistoryItem myHistoryItem;
@Override
public JComponent createCustomComponent(Presentation presentation) {
JPanel panel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
if (myBalloon != null && !myBalloon.isDisposed() && myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
final Gradient gradient = getGradientColors();
((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
g.fillRect(0,0,getWidth(), getHeight());
} else {
super.paintComponent(g);
}
}
};
panel.setOpaque(false);
final JLabel label = new JBLabel(AllIcons.Actions.FindPlain) {
{
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
};
panel.add(label, BorderLayout.CENTER);
initTooltip(label);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (myBalloon != null) {
myBalloon.cancel();
}
myFocusOwner = IdeFocusManager.findInstance().getFocusOwner();
label.setToolTipText(null);
IdeTooltipManager.getInstance().hideCurrentNow(false);
label.setIcon(AllIcons.Actions.FindWhite);
actionPerformed(null, e);
}
@Override
public void mouseEntered(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(AllIcons.Actions.Find);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(AllIcons.Actions.FindPlain);
}
}
});
return panel;
}
private static Gradient getGradientColors() {
return new Gradient(
new JBColor(new Color(101, 147, 242), new Color(64, 80, 94)),
new JBColor(new Color(46, 111, 205), new Color(53, 65, 87)));
}
public SearchEverywhereAction() {
updateComponents();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
onFocusLost();
}
});
}
private void updateComponents() {
myRenderer = new MyListRenderer();
myList = new JBList() {
@Override
public Dimension getPreferredSize() {
final Dimension size = super.getPreferredSize();
return new Dimension(Math.min(size.width - 2, POPUP_MAX_WIDTH), size.height);
}
@Override
public void clearSelection() {
//avoid blinking
}
@Override
public Object getSelectedValue() {
try {
return super.getSelectedValue();
} catch (Exception e) {
return null;
}
}
};
myList.setCellRenderer(myRenderer);
myList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.consume();
final int i = myList.locationToIndex(e.getPoint());
if (i != -1) {
mySkipFocusGain = true;
getField().requestFocus();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myList.setSelectedIndex(i);
doNavigate(i);
}
});
}
}
});
myNonProjectCheckBox = new JCheckBox();
myNonProjectCheckBox.setOpaque(false);
myNonProjectCheckBox.setAlignmentX(1.0f);
myNonProjectCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (showAll.get() != myNonProjectCheckBox.isSelected()) {
showAll.set(!showAll.get());
final JTextField editor = UIUtil.findComponentOfType(myBalloon.getContent(), JTextField.class);
if (editor != null) {
final String pattern = editor.getText();
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
@Override
public void run() {
if (editor.hasFocus()) {
rebuildList(pattern);
}
}
}, 30);
}
}
}
});
}
private static void initTooltip(JLabel label) {
final String shortcutText;
shortcutText = getShortcut();
label.setToolTipText("<html><body>Search Everywhere<br/>Press <b>"
+ shortcutText
+ "</b> to access<br/> - Classes<br/> - Files<br/> - Tool Windows<br/> - Actions<br/> - Settings</body></html>");
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
return null;
}
private static String getShortcut() {
String shortcutText;
final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_SEARCH_EVERYWHERE);
if (shortcuts.length == 0) {
shortcutText = "Double " + (SystemInfo.isMac ? MacKeymapUtil.SHIFT : "Shift");
} else {
shortcutText = KeymapUtil.getShortcutsText(shortcuts);
}
return shortcutText;
}
private void initSearchField(final MySearchTextField search) {
final JTextField editor = search.getTextEditor();
// onFocusLost();
editor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
final String pattern = editor.getText();
if (editor.hasFocus()) {
rebuildList(pattern);
}
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if (mySkipFocusGain) {
mySkipFocusGain = false;
return;
}
search.setText("");
search.getTextEditor().setForeground(UIUtil.getLabelForeground());
//titleIndex = new TitleIndexes();
editor.setColumns(SEARCH_FIELD_COLUMNS);
myFocusComponent = e.getOppositeComponent();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JComponent parent = (JComponent)editor.getParent();
parent.revalidate();
parent.repaint();
}
});
//if (myPopup != null && myPopup.isVisible()) {
// myPopup.cancel();
// myPopup = null;
//}
rebuildList("");
}
@Override
public void focusLost(FocusEvent e) {
if ( myPopup instanceof AbstractPopup && myPopup.isVisible()
&& ((myList == e.getOppositeComponent()) || ((AbstractPopup)myPopup).getPopupWindow() == e.getOppositeComponent())) {
return;
}
if (myNonProjectCheckBox == e.getOppositeComponent()) {
mySkipFocusGain = true;
editor.requestFocus();
return;
}
onFocusLost();
}
});
}
private void jumpNextGroup(boolean forward) {
final int index = myList.getSelectedIndex();
final SearchListModel model = getModel();
if (index >= 0) {
final int newIndex = forward ? model.next(index) : model.prev(index);
myList.setSelectedIndex(newIndex);
int more = model.next(newIndex) - 1;
if (more < newIndex) {
more = myList.getItemsCount() - 1;
}
ListScrollingUtil.ensureIndexIsVisible(myList, more, forward ? 1 : -1);
ListScrollingUtil.ensureIndexIsVisible(myList, newIndex, forward ? 1 : -1);
}
}
private SearchListModel getModel() {
return (SearchListModel)myList.getModel();
}
private ActionCallback onFocusLost() {
final ActionCallback result = new ActionCallback();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (myCalcThread != null) {
myCalcThread.cancel();
//myCalcThread = null;
}
myAlarm.cancelAllRequests();
if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) {
myBalloon.cancel();
myPopup.cancel();
}
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ActionToolbarImpl.updateAllToolbarsImmediately();
}
});
} finally {
result.setDone();
}
}
});
return result;
}
private SearchTextField getField() {
return myPopupField;
}
private void doNavigate(final int index) {
final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
final Executor executor = ourShiftIsPressed.get()
? DefaultRunExecutor.getRunExecutorInstance()
: ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
assert project != null;
final SearchListModel model = getModel();
if (isMoreItem(index)) {
final String pattern = myPopupField.getText();
WidgetID wid = null;
if (index == model.moreIndex.classes) wid = WidgetID.CLASSES;
else if (index == model.moreIndex.files) wid = WidgetID.FILES;
else if (index == model.moreIndex.settings) wid = WidgetID.SETTINGS;
else if (index == model.moreIndex.actions) wid = WidgetID.ACTIONS;
else if (index == model.moreIndex.symbols) wid = WidgetID.SYMBOLS;
else if (index == model.moreIndex.runConfigurations) wid = WidgetID.RUN_CONFIGURATIONS;
if (wid != null) {
final WidgetID widgetID = wid;
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myCalcThread = new CalcThread(project, pattern, true);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.insert(index, widgetID);
}
});
return;
}
}
final String pattern = getField().getText();
final Object value = myList.getSelectedValue();
saveHistory(project, pattern, value);
IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(getField().getTextEditor());
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
if (value instanceof BooleanOptionDescription) {
final BooleanOptionDescription option = (BooleanOptionDescription)value;
option.setOptionState(!option.isOptionEnabled());
myList.revalidate();
myList.repaint();
return;
}
Runnable onDone = null;
AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (value instanceof PsiElement) {
onDone = new Runnable() {
public void run() {
NavigationUtil.activateFileWithPsiElement((PsiElement)value, true);
}
};
return;
}
else if (isVirtualFile(value)) {
onDone = new Runnable() {
public void run() {
OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile)value));
}
};
return;
}
else if (isActionValue(value) || isSetting(value) || isRunConfiguration(value)) {
focusManager.requestDefaultFocus(true);
final Component comp = myContextComponent;
final AnActionEvent event = myActionEvent;
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
Component c = comp;
if (c == null) {
c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
}
if (isRunConfiguration(value)) {
((ChooseRunConfigurationPopup.ItemWrapper)value).perform(project, executor, DataManager.getInstance().getDataContext(c));
} else {
GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event);
if (isToolWindowAction(value)) return;
}
}
});
return;
}
else if (value instanceof Navigatable) {
onDone = new Runnable() {
@Override
public void run() {
OpenSourceUtil.navigate(true, (Navigatable)value);
}
};
return;
}
}
finally {
token.finish();
final ActionCallback callback = onFocusLost();
if (onDone != null) {
callback.doWhenDone(onDone);
}
}
focusManager.requestDefaultFocus(true);
}
private boolean isMoreItem(int index) {
final SearchListModel model = getModel();
return index == model.moreIndex.classes ||
index == model.moreIndex.files ||
index == model.moreIndex.settings ||
index == model.moreIndex.actions ||
index == model.moreIndex.symbols ||
index == model.moreIndex.runConfigurations;
}
private void rebuildList(final String pattern) {
assert EventQueue.isDispatchThread() : "Must be EDT";
if (myCalcThread != null && !myCurrentWorker.isProcessed()) {
myCurrentWorker = myCalcThread.cancel();
}
if (myCalcThread != null && !myCalcThread.isCanceled()) {
myCalcThread.cancel();
}
final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
assert project != null;
myRenderer.myProject = project;
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myCalcThread = new CalcThread(project, pattern, false);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.start();
}
});
}
@Override
public void actionPerformed(AnActionEvent e) {
actionPerformed(e, null);
}
public void actionPerformed(AnActionEvent e, MouseEvent me) {
if (myBalloon != null && myBalloon.isVisible()) {
showAll.set(!showAll.get());
myNonProjectCheckBox.setSelected(showAll.get());
// myPopupField.getTextEditor().setBackground(showAll.get() ? new JBColor(new Color(0xffffe4), new Color(0x494539)) : UIUtil.getTextFieldBackground());
rebuildList(myPopupField.getText());
return;
}
myCurrentWorker = ActionCallback.DONE;
if (e != null) {
myEditor = e.getData(CommonDataKeys.EDITOR);
myFile = e.getData(CommonDataKeys.PSI_FILE);
}
if (e == null && myFocusOwner != null) {
e = new AnActionEvent(me, DataManager.getInstance().getDataContext(myFocusOwner), ActionPlaces.UNKNOWN, getTemplatePresentation(), ActionManager.getInstance(), 0);
}
if (e == null) return;
updateComponents();
myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext());
Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent)
: KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
if (wnd == null && myContextComponent instanceof Window) {
wnd = (Window)myContextComponent;
}
if (wnd == null || wnd.getParent() != null) return;
myActionEvent = e;
if (myPopupField != null) {
Disposer.dispose(myPopupField);
}
myPopupField = new MySearchTextField();
myPopupField.getTextEditor().addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
myHistoryIndex = 0;
myHistoryItem = null;
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
myList.repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
myList.repaint();
}
}
});
initSearchField(myPopupField);
myPopupField.setOpaque(false);
final JTextField editor = myPopupField.getTextEditor();
editor.setColumns(SEARCH_FIELD_COLUMNS);
final JPanel panel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
final Gradient gradient = getGradientColors();
((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
g.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(410, super.getPreferredSize().height);
}
};
final JLabel title = new JLabel(" Search Everywhere: ");
final JPanel topPanel = new NonOpaquePanel(new BorderLayout());
title.setForeground(new JBColor(Gray._240, Gray._200));
if (SystemInfo.isMac) {
title.setFont(title.getFont().deriveFont(Font.BOLD, title.getFont().getSize() - 1f));
} else {
title.setFont(title.getFont().deriveFont(Font.BOLD));
}
topPanel.add(title, BorderLayout.WEST);
myNonProjectCheckBox.setForeground(new JBColor(Gray._240, Gray._200));
myNonProjectCheckBox.setText("Include non-project items (" + getShortcut() + ")");
if (!NonProjectScopeDisablerEP.isSearchInNonProjectDisabled()) {
topPanel.add(myNonProjectCheckBox, BorderLayout.EAST);
}
panel.add(myPopupField, BorderLayout.CENTER);
panel.add(topPanel, BorderLayout.NORTH);
panel.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 4, 5));
DataManager.registerDataProvider(panel, this);
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor);
myBalloon = builder
.setCancelOnClickOutside(true)
.setModalContext(false)
.setRequestFocus(true)
.createPopup();
myBalloon.getContent().setBorder(new EmptyBorder(0,0,0,0));
final Window window = WindowManager.getInstance().suggestParentWindow(e.getProject());
//noinspection ConstantConditions
e.getProject().getMessageBus().connect(myBalloon).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
@Override
public void enteredDumbMode() {
}
@Override
public void exitDumbMode() {
rebuildList(myPopupField.getText());
}
});
Component parent = UIUtil.findUltimateParent(window);
registerDataProvider(panel, e.getProject());
final RelativePoint showPoint;
if (me != null) {
final Component label = me.getComponent();
final Component button = label.getParent();
assert button != null;
showPoint = new RelativePoint(button, new Point(button.getWidth() - panel.getPreferredSize().width, button.getHeight()));
} else {
if (parent != null) {
int height = UISettings.getInstance().SHOW_MAIN_TOOLBAR ? 135 : 115;
if (parent instanceof IdeFrameImpl && ((IdeFrameImpl)parent).isInFullScreen()) {
height -= 20;
}
showPoint = new RelativePoint(parent, new Point((parent.getSize().width - panel.getPreferredSize().width)/ 2, height));
} else {
showPoint = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext());
}
}
myList.setFont(UIUtil.getListFont());
myBalloon.show(showPoint);
initSearchActions(myBalloon, myPopupField);
IdeFocusManager focusManager = IdeFocusManager.getInstance(e.getProject());
focusManager.requestFocus(editor, true);
FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE);
}
private static void saveHistory(Project project, String text, Object value) {
if (project == null || project.isDisposed() || !project.isInitialized()) {
return;
}
HistoryType type = null;
String fqn = null;
if (isActionValue(value)) {
type = HistoryType.ACTION;
AnAction action = (AnAction)(value instanceof GotoActionModel.ActionWrapper ? ((GotoActionModel.ActionWrapper)value).getAction() : value);
fqn = ActionManager.getInstance().getId(action);
} else if (value instanceof VirtualFile) {
type = HistoryType.FILE;
fqn = ((VirtualFile)value).getUrl();
} else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
type = HistoryType.RUN_CONFIGURATION;
fqn = ((ChooseRunConfigurationPopup.ItemWrapper)value).getText();
} else if (value instanceof PsiElement) {
final PsiElement psiElement = (PsiElement)value;
final Language language = psiElement.getLanguage();
final String name = LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).getQualifiedName(psiElement);
if (name != null) {
type = HistoryType.PSI;
fqn = language.getID() + "://" + name;
}
}
final PropertiesComponent storage = PropertiesComponent.getInstance(project);
final String[] values = storage.getValues(SE_HISTORY_KEY);
List<HistoryItem> history = new ArrayList<HistoryItem>();
if (values != null) {
for (String s : values) {
final String[] split = s.split("\t");
if (split.length != 3 || text.equals(split[0])) {
continue;
}
if (!StringUtil.isEmpty(split[0])) {
history.add(new HistoryItem(split[0], split[1], split[2]));
}
}
}
history.add(0, new HistoryItem(text, type == null ? null : type.name(), fqn));
if (history.size() > MAX_SEARCH_EVERYWHERE_HISTORY) {
history = history.subList(0, MAX_SEARCH_EVERYWHERE_HISTORY);
}
final String[] newValues = new String[history.size()];
for (int i = 0; i < newValues.length; i++) {
newValues[i] = history.get(i).toString();
}
storage.setValues(SE_HISTORY_KEY, newValues);
}
public Executor getExecutor() {
return ourShiftIsPressed.get() ? DefaultRunExecutor.getRunExecutorInstance()
: ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
private void registerDataProvider(JPanel panel, final Project project) {
DataManager.registerDataProvider(panel, new DataProvider() {
@Nullable
@Override
public Object getData(@NonNls String dataId) {
final Object value = myList.getSelectedValue();
if (CommonDataKeys.PSI_ELEMENT.is(dataId) && value instanceof PsiElement) {
return value;
} else if (CommonDataKeys.VIRTUAL_FILE.is(dataId) && value instanceof VirtualFile) {
return value;
} else if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
if (value instanceof Navigatable) return value;
if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
final Object config = ((ChooseRunConfigurationPopup.ItemWrapper)value).getValue();
if (config instanceof RunnerAndConfigurationSettings) {
return new Navigatable() {
@Override
public void navigate(boolean requestFocus) {
RunDialog.editConfiguration(project, (RunnerAndConfigurationSettings)config, "Edit Configuration", getExecutor());
}
@Override
public boolean canNavigate() {
return true;
}
@Override
public boolean canNavigateToSource() {
return true;
}
};
}
}
}
return null;
}
});
}
private void initSearchActions(JBPopup balloon, MySearchTextField searchTextField) {
final JTextField editor = searchTextField.getTextEditor();
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
jumpNextGroup(true);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
jumpNextGroup(false);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
if (myBalloon != null && myBalloon.isVisible()) {
myBalloon.cancel();
}
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
final int index = myList.getSelectedIndex();
if (index != -1) {
doNavigate(index);
}
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER", "shift ENTER"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject());
final String[] values = storage.getValues(SE_HISTORY_KEY);
if (values != null) {
if (values.length > myHistoryIndex) {
final List<String> data = StringUtil.split(values[myHistoryIndex], "\t");
myHistoryItem = new HistoryItem(data.get(0), data.get(1), data.get(2));
myHistoryIndex++;
editor.setText(myHistoryItem.pattern);
editor.setCaretPosition(myHistoryItem.pattern.length());
editor.moveCaretPosition(0);
}
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(editor.getCaretPosition() == 0);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon);
}
private static class MySearchTextField extends SearchTextField implements DataProvider, Disposable {
public MySearchTextField() {
super(false);
getTextEditor().setOpaque(false);
getTextEditor().setUI((DarculaTextFieldUI)DarculaTextFieldUI.createUI(getTextEditor()));
getTextEditor().setBorder(new DarculaTextBorder());
getTextEditor().putClientProperty("JTextField.Search.noBorderRing", Boolean.TRUE);
if (UIUtil.isUnderDarcula()) {
getTextEditor().setBackground(Gray._45);
getTextEditor().setForeground(Gray._240);
}
}
@Override
protected boolean isSearchControlUISupported() {
return true;
}
@Override
protected boolean hasIconsOutsideOfTextField() {
return false;
}
@Override
protected void showPopup() {
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) {
return getTextEditor().getText();
}
return null;
}
@Override
public void dispose() {
}
}
private class MyListRenderer extends ColoredListCellRenderer {
ColoredListCellRenderer myLocation = new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
setPaintFocusBorder(false);
append(myLocationString, SimpleTextAttributes.GRAYED_ATTRIBUTES);
setIcon(myLocationIcon);
}
};
GotoFileCellRenderer myFileRenderer = new GotoFileCellRenderer(400);
private String myLocationString;
private DefaultPsiElementCellRenderer myPsiRenderer = new DefaultPsiElementCellRenderer() {
{setFocusBorderEnabled(false);}
};
private Icon myLocationIcon;
private Project myProject;
private JPanel myMainPanel = new JPanel(new BorderLayout());
private JLabel myTitle = new JLabel();
@Override
public void clear() {
super.clear();
myLocation.clear();
myLocationString = null;
myLocationIcon = null;
}
public void setLocationString(String locationString) {
myLocationString = locationString;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component cmp;
PsiElement file = null;
myLocationString = null;
String pattern = "*" + myPopupField.getText();
Matcher matcher = NameUtil.buildMatcher(pattern, 0, true, true, pattern.toLowerCase().equals(pattern));
if (isMoreItem(index)) {
cmp = More.get(isSelected);
} else if (value instanceof VirtualFile
&& myProject != null
&& ((((VirtualFile)value).isDirectory() && (file = PsiManager.getInstance(myProject).findDirectory((VirtualFile)value)) != null )
|| (file = PsiManager.getInstance(myProject).findFile((VirtualFile)value)) != null)) {
myFileRenderer.setPatternMatcher(matcher);
cmp = myFileRenderer.getListCellRendererComponent(list, file, index, isSelected, cellHasFocus);
} else if (value instanceof PsiElement) {
myPsiRenderer.setPatternMatcher(matcher);
cmp = myPsiRenderer.getListCellRendererComponent(list, value, index, isSelected, isSelected);
} else {
cmp = super.getListCellRendererComponent(list, value, index, isSelected, isSelected);
final JPanel p = new JPanel(new BorderLayout());
p.setBackground(UIUtil.getListBackground(isSelected));
p.add(cmp, BorderLayout.CENTER);
cmp = p;
}
if (myLocationString != null || value instanceof BooleanOptionDescription) {
final JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(UIUtil.getListBackground(isSelected));
panel.add(cmp, BorderLayout.CENTER);
final Component rightComponent;
if (value instanceof BooleanOptionDescription) {
final OnOffButton button = new OnOffButton();
button.setSelected(((BooleanOptionDescription)value).isOptionEnabled());
rightComponent = button;
}
else {
rightComponent = myLocation.getListCellRendererComponent(list, value, index, isSelected, isSelected);
}
panel.add(rightComponent, BorderLayout.EAST);
cmp = panel;
}
Color bg = cmp.getBackground();
if (bg == null) {
cmp.setBackground(UIUtil.getListBackground(isSelected));
bg = cmp.getBackground();
}
myMainPanel.setBorder(new CustomLineBorder(bg, 0, 0, 2, 0));
String title = getModel().titleIndex.getTitle(index);
myMainPanel.removeAll();
if (title != null) {
myTitle.setText(title);
myMainPanel.add(createTitle(" " + title), BorderLayout.NORTH);
}
myMainPanel.add(cmp, BorderLayout.CENTER);
final int width = myMainPanel.getPreferredSize().width;
if (width > myPopupActualWidth) {
myPopupActualWidth = width;
//schedulePopupUpdate();
}
return myMainPanel;
}
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
setPaintFocusBorder(false);
setIcon(EmptyIcon.ICON_16);
AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (value instanceof PsiElement) {
String name = myClassModel.getElementName(value);
assert name != null;
append(name);
} else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
final ChooseRunConfigurationPopup.ItemWrapper wrapper = (ChooseRunConfigurationPopup.ItemWrapper)value;
append(wrapper.getText());
setIcon(wrapper.getIcon());
setLocationString(ourShiftIsPressed.get() ? "Run" : "Debug");
myLocationIcon = ourShiftIsPressed.get() ? AllIcons.Toolwindows.ToolWindowRun : AllIcons.Toolwindows.ToolWindowDebugger;
} else if (isVirtualFile(value)) {
final VirtualFile file = (VirtualFile)value;
if (file instanceof VirtualFilePathWrapper) {
append(((VirtualFilePathWrapper)file).getPresentablePath());
} else {
append(file.getName());
}
setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject));
}
else if (isActionValue(value)) {
final GotoActionModel.ActionWrapper actionWithParentGroup = value instanceof GotoActionModel.ActionWrapper ? (GotoActionModel.ActionWrapper)value : null;
final AnAction anAction = actionWithParentGroup == null ? (AnAction)value : actionWithParentGroup.getAction();
final Presentation templatePresentation = anAction.getTemplatePresentation();
Icon icon = templatePresentation.getIcon();
if (anAction instanceof ActivateToolWindowAction) {
final String id = ((ActivateToolWindowAction)anAction).getToolWindowId();
ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(id);
if (toolWindow != null) {
icon = toolWindow.getIcon();
}
}
append(templatePresentation.getText());
if (actionWithParentGroup != null) {
final String groupName = actionWithParentGroup.getGroupName();
if (!StringUtil.isEmpty(groupName)) {
setLocationString(groupName);
}
}
final String groupName = actionWithParentGroup == null ? null : actionWithParentGroup.getGroupName();
if (!StringUtil.isEmpty(groupName)) {
setLocationString(groupName);
}
if (icon != null && icon.getIconWidth() <= 16 && icon.getIconHeight() <= 16) {
setIcon(IconUtil.toSize(icon, 16, 16));
}
}
else if (isSetting(value)) {
String text = getSettingText((OptionDescription)value);
append(text);
final String id = ((OptionDescription)value).getConfigurableId();
final String name = myConfigurables.get(id);
if (name != null) {
setLocationString(name);
}
}
else {
ItemPresentation presentation = null;
if (value instanceof ItemPresentation) {
presentation = (ItemPresentation)value;
}
else if (value instanceof NavigationItem) {
presentation = ((NavigationItem)value).getPresentation();
}
if (presentation != null) {
final String text = presentation.getPresentableText();
append(text == null ? value.toString() : text);
final String location = presentation.getLocationString();
if (!StringUtil.isEmpty(location)) {
setLocationString(location);
}
Icon icon = presentation.getIcon(false);
if (icon != null) setIcon(icon);
}
}
}
finally {
token.finish();
}
}
public void recalculateWidth() {
ListModel model = myList.getModel();
myTitle.setIcon(EmptyIcon.ICON_16);
myTitle.setFont(getTitleFont());
int index = 0;
while (index < model.getSize()) {
String title = getModel().titleIndex.getTitle(index);
if (title != null) {
myTitle.setText(title);
}
index++;
}
myTitle.setForeground(Gray._122);
myTitle.setAlignmentY(BOTTOM_ALIGNMENT);
}
}
private static String getSettingText(OptionDescription value) {
String hit = value.getHit();
if (hit == null) {
hit = value.getOption();
}
hit = StringUtil.unescapeXml(hit);
if (hit.length() > 60) {
hit = hit.substring(0, 60) + "...";
}
hit = hit.replace(" ", " "); //avoid extra spaces from mnemonics and xml conversion
String text = hit.trim();
if (text.endsWith(":")) {
text = text.substring(0, text.length() - 1);
}
return text;
}
private static boolean isActionValue(Object o) {
return o instanceof GotoActionModel.ActionWrapper || o instanceof AnAction;
}
private static boolean isSetting(Object o) {
return o instanceof OptionDescription;
}
private static boolean isRunConfiguration(Object o) {
return o instanceof ChooseRunConfigurationPopup.ItemWrapper;
}
private static boolean isVirtualFile(Object o) {
return o instanceof VirtualFile;
}
private static Font getTitleFont() {
return UIUtil.getLabelFont().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.SMALL));
}
enum WidgetID {CLASSES, FILES, ACTIONS, SETTINGS, SYMBOLS, RUN_CONFIGURATIONS}
@SuppressWarnings("SSBasedInspection")
private class CalcThread implements Runnable {
private final Project project;
private final String pattern;
private final ProgressIndicator myProgressIndicator = new ProgressIndicatorBase();
private final ActionCallback myDone = new ActionCallback();
private final SearchListModel myListModel;
private final ArrayList<VirtualFile> myAlreadyAddedFiles = new ArrayList<VirtualFile>();
private final ArrayList<AnAction> myAlreadyAddedActions = new ArrayList<AnAction>();
public CalcThread(Project project, String pattern, boolean reuseModel) {
this.project = project;
this.pattern = pattern;
myListModel = reuseModel ? (SearchListModel)myList.getModel() : new SearchListModel();
}
@Override
public void run() {
try {
check();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb]
myList.getEmptyText().setText("Searching...");
myAlarm.cancelAllRequests();
if (myList.getModel() instanceof SearchListModel) {
//noinspection unchecked
myAlarm.addRequest(new Runnable() {
@Override
public void run() {
if (!myDone.isRejected()) {
myList.setModel(myListModel);
}
}
}, 100);
} else {
myList.setModel(myListModel);
}
}
});
if (pattern.trim().length() == 0) {
buildModelFromRecentFiles();
updatePopup();
return;
}
checkModelsUpToDate(); check();
buildTopHit(pattern); check();
buildRecentFiles(pattern); check();
updatePopup(); check();
buildToolWindows(pattern); check();
updatePopup(); check();
runReadAction(new Runnable() {
public void run() {
buildRunConfigurations(pattern);
}
}, true);
runReadAction(new Runnable() {
public void run() {
buildClasses(pattern);
}
}, true);
runReadAction(new Runnable() {
public void run() {
buildFiles(pattern);
}
}, false);
buildActionsAndSettings(pattern);
updatePopup();
runReadAction(new Runnable() {
public void run() {
buildSymbols(pattern);
}
}, true);
}
catch (ProcessCanceledException ignore) {
myDone.setRejected();
}
catch (Exception e) {
LOG.error(e);
myDone.setRejected();
}
finally {
if (!isCanceled()) {
myList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT);
updatePopup();
}
if (!myDone.isProcessed()) {
myDone.setDone();
}
}
}
private void runReadAction(Runnable action, boolean checkDumb) {
if (!checkDumb || !DumbService.getInstance(project).isDumb()) {
ApplicationManager.getApplication().runReadAction(action);
updatePopup();
}
}
protected void check() {
myProgressIndicator.checkCanceled();
if (myDone.isRejected()) throw new ProcessCanceledException();
if (myBalloon == null || myBalloon.isDisposed()) throw new ProcessCanceledException();
}
private synchronized void buildToolWindows(String pattern) {
final List<ActivateToolWindowAction> actions = new ArrayList<ActivateToolWindowAction>();
for (ActivateToolWindowAction action : ToolWindowsGroup.getToolWindowActions(project)) {
String text = action.getTemplatePresentation().getText();
if (text != null && StringUtil.startsWithIgnoreCase(text, pattern)) {
actions.add(action);
if (actions.size() == MAX_TOOL_WINDOWS) {
break;
}
}
}
check();
if (actions.isEmpty()) {
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myListModel.titleIndex.toolWindows = myListModel.size();
for (Object toolWindow : actions) {
myListModel.addElement(toolWindow);
}
}
});
}
private SearchResult getActionsOrSettings(final String pattern, final int max, final boolean actions) {
final SearchResult result = new SearchResult();
final MinusculeMatcher matcher = new MinusculeMatcher("*" +pattern, NameUtil.MatchingCaseSensitivity.NONE);
if (myActionProvider == null) {
myActionProvider = createActionProvider();
}
myActionProvider.filterElements(pattern, true, new Processor<GotoActionModel.MatchedValue>() {
@Override
public boolean process(GotoActionModel.MatchedValue matched) {
check();
Object object = matched.value;
if (myListModel.contains(object)) return true;
if (!actions && isSetting(object)) {
if (matcher.matches(getSettingText((OptionDescription)object))) {
result.add(object);
}
} else if (actions && !isToolWindowAction(object) && isActionValue(object)) {
result.add(object);
}
return result.size() <= max;
}
});
return result;
}
private synchronized void buildActionsAndSettings(String pattern) {
final SearchResult actions = getActionsOrSettings(pattern, MAX_ACTIONS, true);
final SearchResult settings = getActionsOrSettings(pattern, MAX_SETTINGS, false);
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
if (actions.size() > 0) {
myListModel.titleIndex.actions = myListModel.size();
for (Object action : actions) {
myListModel.addElement(action);
}
}
myListModel.moreIndex.actions = actions.size() >= MAX_ACTIONS ? myListModel.size() - 1 : -1;
if (settings.size() > 0) {
myListModel.titleIndex.settings = myListModel.size();
for (Object setting : settings) {
myListModel.addElement(setting);
}
}
myListModel.moreIndex.settings = settings.size() >= MAX_SETTINGS ? myListModel.size() - 1 : -1;
}
});
}
private synchronized void buildFiles(final String pattern) {
final SearchResult files = getFiles(pattern, MAX_FILES, myFileChooseByName);
check();
if (files.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.files = myListModel.size();
for (Object file : files) {
myListModel.addElement(file);
}
myListModel.moreIndex.files = files.needMore ? myListModel.size() - 1 : -1;
}
});
}
}
private synchronized void buildSymbols(final String pattern) {
final SearchResult symbols = getSymbols(pattern, MAX_SYMBOLS, mySymbolsChooseByName);
check();
if (symbols.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.symbols = myListModel.size();
for (Object file : symbols) {
myListModel.addElement(file);
}
myListModel.moreIndex.symbols = symbols.needMore ? myListModel.size() - 1 : -1;
}
});
}
}
@Nullable
private ChooseRunConfigurationPopup.ItemWrapper getRunConfigurationByName(String name) {
final ChooseRunConfigurationPopup.ItemWrapper[] wrappers =
ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() {
@Override
public Executor getExecutor() {
return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
}, false);
for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) {
if (wrapper.getText().equals(name)) {
return wrapper;
}
}
return null;
}
private synchronized void buildRunConfigurations(String pattern) {
final SearchResult runConfigurations = getConfigurations(pattern, MAX_RUN_CONFIGURATION);
if (runConfigurations.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.runConfigurations = myListModel.size();
for (Object runConfiguration : runConfigurations) {
myListModel.addElement(runConfiguration);
}
myListModel.moreIndex.runConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1;
}
});
}
}
private SearchResult getConfigurations(String pattern, int max) {
SearchResult configurations = new SearchResult();
MinusculeMatcher matcher = new MinusculeMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE);
final ChooseRunConfigurationPopup.ItemWrapper[] wrappers =
ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() {
@Override
public Executor getExecutor() {
return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
}, false);
check();
for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) {
if (matcher.matches(wrapper.getText()) && !myListModel.contains(wrapper)) {
if (configurations.size() == max) {
configurations.needMore = true;
break;
}
configurations.add(wrapper);
}
check();
}
return configurations;
}
private synchronized void buildClasses(final String pattern) {
if (pattern.indexOf('.') != -1) {
//todo[kb] it's not a mistake. If we search for "*.png" or "index.xml" in SearchEverywhere
//todo[kb] we don't want to see Java classes started with Png or Xml. This approach should be reworked someday.
return;
}
check();
final SearchResult classes = getClasses(pattern, showAll.get(), MAX_CLASSES, myClassChooseByName);
check();
if (classes.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.classes = myListModel.size();
for (Object file : classes) {
myListModel.addElement(file);
}
myListModel.moreIndex.classes = -1;
if (classes.needMore) {
myListModel.moreIndex.classes = myListModel.size() - 1;
}
}
});
}
}
private SearchResult getSymbols(String pattern, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult symbols = new SearchResult();
final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, false,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
if (o instanceof PsiElement) {
final PsiElement element = (PsiElement)o;
final PsiFile file = element.getContainingFile();
if (!myListModel.contains(o) &&
//some elements are non-physical like DB columns
(file == null || (file.getVirtualFile() != null && scope.accept(file.getVirtualFile())))) {
symbols.add(o);
}
}
symbols.needMore = symbols.size() == max;
return !symbols.needMore;
}
});
return symbols;
}
private SearchResult getClasses(String pattern, boolean includeLibs, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult classes = new SearchResult();
if (chooseByNamePopup == null) {
return classes;
}
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, includeLibs,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
if (o instanceof PsiElement && !myListModel.contains(o) && !classes.contains(o)) {
if (classes.size() == max) {
classes.needMore = true;
return false;
}
classes.add(o);
}
return true;
}
});
if (!includeLibs && classes.isEmpty()) {
return getClasses(pattern, true, max, chooseByNamePopup);
}
return classes;
}
private SearchResult getFiles(final String pattern, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult files = new SearchResult();
if (chooseByNamePopup == null) {
return files;
}
final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, true,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
VirtualFile file = null;
if (o instanceof VirtualFile) {
file = (VirtualFile)o;
} else if (o instanceof PsiFile) {
file = ((PsiFile)o).getVirtualFile();
} else if (o instanceof PsiDirectory) {
file = ((PsiDirectory)o).getVirtualFile();
}
if (file != null
&& !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1)
&& (showAll.get() || scope.accept(file)
&& !myListModel.contains(file)
&& !myAlreadyAddedFiles.contains(file))
&& !files.contains(file)) {
if (files.size() == max) {
files.needMore = true;
return false;
}
files.add(file);
}
return true;
}
});
return files;
}
private synchronized void buildRecentFiles(String pattern) {
final MinusculeMatcher matcher = new MinusculeMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE);
final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>();
final List<VirtualFile> selected = Arrays.asList(FileEditorManager.getInstance(project).getSelectedFiles());
for (VirtualFile file : ArrayUtil.reverseArray(EditorHistoryManager.getInstance(project).getFiles())) {
if (StringUtil.isEmptyOrSpaces(pattern) || matcher.matches(file.getName())) {
if (!files.contains(file) && !selected.contains(file)) {
files.add(file);
}
}
if (files.size() > MAX_RECENT_FILES) break;
}
if (files.size() > 0) {
myAlreadyAddedFiles.addAll(files);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.recentFiles = myListModel.size();
for (Object file : files) {
myListModel.addElement(file);
}
}
});
}
}
private boolean isCanceled() {
return myProgressIndicator.isCanceled() || myDone.isRejected();
}
private synchronized void buildTopHit(String pattern) {
final List<Object> elements = new ArrayList<Object>();
final HistoryItem history = myHistoryItem;
if (history != null) {
final HistoryType type = parseHistoryType(history.type);
if (type != null) {
switch (type){
case PSI:
if (!DumbService.isDumb(project)) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final int i = history.fqn.indexOf("://");
if (i != -1) {
final String langId = history.fqn.substring(0, i);
final Language language = Language.findLanguageByID(langId);
final String psiFqn = history.fqn.substring(i + 3);
if (language != null) {
final PsiElement psi =
LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).findByQualifiedName(project, psiFqn);
if (psi != null) {
elements.add(psi);
final PsiFile psiFile = psi.getContainingFile();
if (psiFile != null) {
final VirtualFile file = psiFile.getVirtualFile();
if (file != null) {
myAlreadyAddedFiles.add(file);
}
}
}
}
}
}
});
}
break;
case FILE:
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(history.fqn);
if (file != null) {
elements.add(file);
}
break;
case SETTING:
break;
case ACTION:
final AnAction action = ActionManager.getInstance().getAction(history.fqn);
if (action != null) {
elements.add(action);
myAlreadyAddedActions.add(action);
}
break;
case RUN_CONFIGURATION:
if (!DumbService.isDumb(project)) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final ChooseRunConfigurationPopup.ItemWrapper runConfiguration = getRunConfigurationByName(history.fqn);
if (runConfiguration != null) {
elements.add(runConfiguration);
}
}
});
}
break;
}
}
}
final Consumer<Object> consumer = new Consumer<Object>() {
@Override
public void consume(Object o) {
if (isSetting(o) || isVirtualFile(o) || isActionValue(o) || o instanceof PsiElement) {
if (o instanceof AnAction && myAlreadyAddedActions.contains(o)) {
return;
}
elements.add(o);
}
}
};
final ActionManager actionManager = ActionManager.getInstance();
final List<String> actions = AbbreviationManager.getInstance().findActions(pattern);
for (String actionId : actions) {
consumer.consume(actionManager.getAction(actionId));
}
for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) {
check();
provider.consumeTopHits(pattern, consumer);
}
if (elements.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
for (Object element : elements.toArray()) {
if (element instanceof AnAction) {
final AnAction action = (AnAction)element;
final AnActionEvent e = new AnActionEvent(myActionEvent.getInputEvent(),
myActionEvent.getDataContext(),
myActionEvent.getPlace(),
action.getTemplatePresentation(),
myActionEvent.getActionManager(),
myActionEvent.getModifiers());
ActionUtil.performDumbAwareUpdate(action, e, false);
final Presentation presentation = e.getPresentation();
if (!presentation.isEnabled() || !presentation.isVisible() || StringUtil.isEmpty(presentation.getText())) {
elements.remove(element);
}
if (isCanceled()) return;
}
}
if (isCanceled() || elements.isEmpty()) return;
myListModel.titleIndex.topHit = myListModel.size();
for (Object element : elements) {
myListModel.addElement(element);
}
}
});
}
}
private synchronized void checkModelsUpToDate() {
if (myClassModel == null) {
myClassModel = new GotoClassModel2(project);
myFileModel = new GotoFileModel(project);
mySymbolsModel = new GotoSymbolModel2(project);
myFileChooseByName = ChooseByNamePopup.createPopup(project, myFileModel, (PsiElement)null);
myClassChooseByName = ChooseByNamePopup.createPopup(project, myClassModel, (PsiElement)null);
mySymbolsChooseByName = ChooseByNamePopup.createPopup(project, mySymbolsModel, (PsiElement)null);
project.putUserData(ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, null);
myActionProvider = createActionProvider();
myConfigurables.clear();
fillConfigurablesIds(null, ShowSettingsUtilImpl.getConfigurables(project, true));
}
}
private void buildModelFromRecentFiles() {
buildRecentFiles("");
}
private GotoActionItemProvider createActionProvider() {
GotoActionModel model = new GotoActionModel(project, myFocusComponent, myEditor, myFile) {
@Override
protected MatchMode actionMatches(String pattern, @NotNull AnAction anAction) {
String text = anAction.getTemplatePresentation().getText();
return text != null && NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE)
.matches(text) ? MatchMode.NAME : MatchMode.NONE;
}
};
return new GotoActionItemProvider(model);
}
@SuppressWarnings("SSBasedInspection")
private void updatePopup() {
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myListModel.update();
myList.revalidate();
myList.repaint();
myRenderer.recalculateWidth();
if (myBalloon == null || myBalloon.isDisposed()) {
return;
}
if (myPopup == null || !myPopup.isVisible()) {
final ActionCallback callback = ListDelegationUtil.installKeyboardDelegation(getField().getTextEditor(), myList);
final ComponentPopupBuilder builder = JBPopupFactory.getInstance()
.createComponentPopupBuilder(new JBScrollPane(myList), null);
myPopup = builder
.setRequestFocus(false)
.setCancelKeyEnabled(false)
.setCancelCallback(new Computable<Boolean>() {
@Override
public Boolean compute() {
return myBalloon == null || myBalloon.isDisposed() || !getField().getTextEditor().hasFocus();
}
})
.createPopup();
myPopup.getContent().setBorder(new EmptyBorder(0, 0, 0, 0));
Disposer.register(myPopup, new Disposable() {
@Override
public void dispose() {
callback.setDone();
resetFields();
myNonProjectCheckBox.setSelected(false);
ActionToolbarImpl.updateAllToolbarsImmediately();
if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
final Component component = myActionEvent.getInputEvent().getComponent();
if (component != null) {
final JLabel label = UIUtil.getParentOfType(JLabel.class, component);
if (label != null) {
label.setIcon(AllIcons.Actions.FindPlain);
}
}
}
myActionEvent = null;
}
});
myPopup.show(new RelativePoint(getField().getParent(), new Point(0, getField().getParent().getHeight())));
updatePopupBounds();
ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() {
@Override
public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (action instanceof TextComponentEditorAction) {
return;
}
myPopup.cancel();
}
}, myPopup);
}
else {
myList.revalidate();
myList.repaint();
}
ListScrollingUtil.ensureSelectionExists(myList);
if (myList.getModel().getSize() > 0) {
updatePopupBounds();
}
}
});
}
public ActionCallback cancel() {
myProgressIndicator.cancel();
myDone.setRejected();
return myDone;
}
public ActionCallback insert(final int index, final WidgetID id) {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
runReadAction(new Runnable() {
@Override
public void run() {
try {
final SearchResult result
= id == WidgetID.CLASSES ? getClasses(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myClassChooseByName)
: id == WidgetID.FILES ? getFiles(pattern, DEFAULT_MORE_STEP_COUNT, myFileChooseByName)
: id == WidgetID.RUN_CONFIGURATIONS ? getConfigurations(pattern, DEFAULT_MORE_STEP_COUNT)
: id == WidgetID.SYMBOLS ? getSymbols(pattern, DEFAULT_MORE_STEP_COUNT, mySymbolsChooseByName)
: id == WidgetID.ACTIONS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, true)
: id == WidgetID.SETTINGS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, false)
: new SearchResult();
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
int shift = 0;
int i = index+1;
for (Object o : result) {
//noinspection unchecked
myListModel.insertElementAt(o, i);
shift++;
i++;
}
MoreIndex moreIndex = myListModel.moreIndex;
myListModel.titleIndex.shift(index, shift);
moreIndex.shift(index, shift);
if (!result.needMore) {
switch (id) {
case CLASSES: moreIndex.classes = -1; break;
case FILES: moreIndex.files = -1; break;
case ACTIONS: moreIndex.actions = -1; break;
case SETTINGS: moreIndex.settings = -1; break;
case SYMBOLS: moreIndex.symbols = -1; break;
case RUN_CONFIGURATIONS: moreIndex.runConfigurations = -1; break;
}
}
ListScrollingUtil.selectItem(myList, index);
myDone.setDone();
}
catch (Exception e) {
myDone.setRejected();
}
}
});
}
catch (Exception e) {
myDone.setRejected();
}
}
}, true);
}
});
return myDone;
}
public ActionCallback start() {
ApplicationManager.getApplication().executeOnPooledThread(this);
return myDone;
}
}
protected void resetFields() {
if (myBalloon!= null) {
myBalloon.cancel();
myBalloon = null;
}
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myFileModel = null;
if (myFileChooseByName != null) {
myFileChooseByName.close(false);
myFileChooseByName = null;
}
if (myClassChooseByName != null) {
myClassChooseByName.close(false);
myClassChooseByName = null;
}
if (mySymbolsChooseByName != null) {
mySymbolsChooseByName.close(false);
mySymbolsChooseByName = null;
}
final Object lock = myCalcThread;
if (lock != null) {
synchronized (lock) {
myClassModel = null;
myActionProvider = null;
mySymbolsModel = null;
myConfigurables.clear();
myFocusComponent = null;
myContextComponent = null;
myFocusOwner = null;
myRenderer.myProject = null;
myPopup = null;
myHistoryIndex = 0;
myPopupActualWidth = 0;
myCurrentWorker = ActionCallback.DONE;
showAll.set(false);
myCalcThread = null;
}
}
}
});
mySkipFocusGain = false;
}
private void updatePopupBounds() {
if (myPopup == null || !myPopup.isVisible()) {
return;
}
final Container parent = getField().getParent();
final Dimension size = myList.getParent().getParent().getPreferredSize();
size.width = myPopupActualWidth - 2;
if (size.width + 2 < parent.getWidth()) {
size.width = parent.getWidth();
}
if (myList.getItemsCount() == 0) {
size.height = 70;
}
Dimension sz = new Dimension(size.width, myList.getPreferredSize().height);
if (sz.width > POPUP_MAX_WIDTH || sz.height > POPUP_MAX_WIDTH) {
final JBScrollPane pane = new JBScrollPane();
final int extraWidth = pane.getVerticalScrollBar().getWidth() + 1;
final int extraHeight = pane.getHorizontalScrollBar().getHeight() + 1;
sz = new Dimension(Math.min(POPUP_MAX_WIDTH, Math.max(getField().getWidth(), sz.width + extraWidth)), Math.min(POPUP_MAX_WIDTH, sz.height + extraHeight));
sz.width += 20;
sz.height+=2;
} else {
sz.width+=2;
sz.height+=2;
}
sz.width = Math.max(sz.width, myPopup.getSize().width);
myPopup.setSize(sz);
if (myActionEvent != null && myActionEvent.getInputEvent() == null) {
final Point p = parent.getLocationOnScreen();
p.y += parent.getHeight();
if (parent.getWidth() < sz.width) {
p.x -= sz.width - parent.getWidth();
}
myPopup.setLocation(p);
} else {
try {
adjustPopup();
}
catch (Exception ignore) {}
}
}
private void adjustPopup() {
// new PopupPositionManager.PositionAdjuster(getField().getParent(), 0).adjust(myPopup, PopupPositionManager.Position.BOTTOM);
final Dimension d = PopupPositionManager.PositionAdjuster.getPopupSize(myPopup);
final JComponent myRelativeTo = myBalloon.getContent();
Point myRelativeOnScreen = myRelativeTo.getLocationOnScreen();
Rectangle screen = ScreenUtil.getScreenRectangle(myRelativeOnScreen);
Rectangle popupRect = null;
Rectangle r = new Rectangle(myRelativeOnScreen.x, myRelativeOnScreen.y + myRelativeTo.getHeight(), d.width, d.height);
if (screen.contains(r)) {
popupRect = r;
}
if (popupRect != null) {
myPopup.setLocation(new Point(r.x, r.y));
}
else {
if (r.y + d.height > screen.y + screen.height) {
r.height = screen.y + screen.height - r.y - 2;
}
if (r.width > screen.width) {
r.width = screen.width - 50;
}
if (r.x + r.width > screen.x + screen.width) {
r.x = screen.x + screen.width - r.width - 2;
}
myPopup.setSize(r.getSize());
myPopup.setLocation(r.getLocation());
}
}
private static boolean isToolWindowAction(Object o) {
return isActionValue(o)
&& o instanceof GotoActionModel.ActionWrapper
&& ((GotoActionModel.ActionWrapper)o).getAction() instanceof ActivateToolWindowAction;
}
private void fillConfigurablesIds(String pathToParent, Configurable[] configurables) {
for (Configurable configurable : configurables) {
if (configurable instanceof SearchableConfigurable) {
final String id = ((SearchableConfigurable)configurable).getId();
String name = configurable.getDisplayName();
if (pathToParent != null) {
name = pathToParent + " -> " + name;
}
myConfigurables.put(id, name);
if (configurable instanceof SearchableConfigurable.Parent) {
fillConfigurablesIds(name, ((SearchableConfigurable.Parent)configurable).getConfigurables());
}
}
}
}
static class MoreIndex {
volatile int classes = -1;
volatile int files = -1;
volatile int actions = -1;
volatile int settings = -1;
volatile int symbols = -1;
volatile int runConfigurations = -1;
public void shift(int index, int shift) {
if (runConfigurations >= index) runConfigurations += shift;
if (classes >= index) classes += shift;
if (files >= index) files += shift;
if (actions >= index) actions += shift;
if (settings >= index) settings += shift;
if (symbols >= index) symbols += shift;
}
}
static class TitleIndex {
volatile int topHit = -1;
volatile int recentFiles = -1;
volatile int runConfigurations = -1;
volatile int classes = -1;
volatile int files = -1;
volatile int actions = -1;
volatile int settings = -1;
volatile int toolWindows = -1;
volatile int symbols = -1;
final String gotoClassTitle;
final String gotoFileTitle;
final String gotoActionTitle;
final String gotoSettingsTitle;
final String gotoRecentFilesTitle;
final String gotoRunConfigurationsTitle;
final String gotoSymbolTitle;
static final String toolWindowsTitle = "Tool Windows";
TitleIndex() {
String gotoClass = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoClass"));
gotoClassTitle = StringUtil.isEmpty(gotoClass) ? "Classes" : "Classes (" + gotoClass + ")";
String gotoFile = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoFile"));
gotoFileTitle = StringUtil.isEmpty(gotoFile) ? "Files" : "Files (" + gotoFile + ")";
String gotoAction = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoAction"));
gotoActionTitle = StringUtil.isEmpty(gotoAction) ? "Actions" : "Actions (" + gotoAction + ")";
String gotoSettings = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ShowSettings"));
gotoSettingsTitle = StringUtil.isEmpty(gotoAction) ? "Preferences" : "Preferences (" + gotoSettings + ")";
String gotoRecentFiles = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("RecentFiles"));
gotoRecentFilesTitle = StringUtil.isEmpty(gotoRecentFiles) ? "Recent Files" : "Recent Files (" + gotoRecentFiles + ")";
String gotoSymbol = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoSymbol"));
gotoSymbolTitle = StringUtil.isEmpty(gotoSymbol) ? "Symbols" : "Symbols (" + gotoSymbol + ")";
String gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseDebugConfiguration"));
if (StringUtil.isEmpty(gotoRunConfiguration)) {
gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseRunConfiguration"));
}
gotoRunConfigurationsTitle = StringUtil.isEmpty(gotoRunConfiguration) ? "Run Configurations" : "Run Configurations (" + gotoRunConfiguration + ")";
}
String getTitle(int index) {
if (index == topHit) return index == 0 ? "Top Hit" : "Top Hits";
if (index == recentFiles) return gotoRecentFilesTitle;
if (index == runConfigurations) return gotoRunConfigurationsTitle;
if (index == classes) return gotoClassTitle;
if (index == files) return gotoFileTitle;
if (index == toolWindows) return toolWindowsTitle;
if (index == actions) return gotoActionTitle;
if (index == settings) return gotoSettingsTitle;
if (index == symbols) return gotoSymbolTitle;
return null;
}
public void clear() {
topHit = -1;
runConfigurations = -1;
recentFiles = -1;
classes = -1;
files = -1;
actions = -1;
settings = -1;
toolWindows = -1;
}
public void shift(int index, int shift) {
if (toolWindows != - 1 && toolWindows > index) toolWindows += shift;
if (settings != - 1 && settings > index) settings += shift;
if (actions != - 1 && actions > index) actions += shift;
if (files != - 1 && files > index) files += shift;
if (classes != - 1 && classes > index) classes += shift;
if (runConfigurations != - 1 && runConfigurations > index) runConfigurations += shift;
if (symbols != - 1 && symbols > index) symbols += shift;
}
}
static class SearchResult extends ArrayList<Object> {
boolean needMore;
}
@SuppressWarnings("unchecked")
private static class SearchListModel extends DefaultListModel {
@SuppressWarnings("UseOfObsoleteCollectionType")
Vector myDelegate;
volatile TitleIndex titleIndex = new TitleIndex();
volatile MoreIndex moreIndex = new MoreIndex();
private SearchListModel() {
super();
myDelegate = ReflectionUtil.getField(DefaultListModel.class, this, Vector.class, "delegate");
}
int next(int index) {
int[] all = getAll();
Arrays.sort(all);
for (int next : all) {
if (next > index) return next;
}
return 0;
}
int[] getAll() {
return new int[]{
titleIndex.topHit,
titleIndex.recentFiles,
titleIndex.runConfigurations,
titleIndex.classes,
titleIndex.files,
titleIndex.actions,
titleIndex.settings,
titleIndex.toolWindows,
titleIndex.symbols,
moreIndex.classes,
moreIndex.actions,
moreIndex.files,
moreIndex.settings,
moreIndex.symbols,
moreIndex.runConfigurations
};
}
int prev(int index) {
int[] all = getAll();
Arrays.sort(all);
for (int i = all.length-1; i >= 0; i--) {
if (all[i] != -1 && all[i] < index) return all[i];
}
return all[all.length - 1];
}
@Override
public void addElement(Object obj) {
myDelegate.add(obj);
}
public void update() {
fireContentsChanged(this, 0, getSize() - 1);
}
}
static class More extends JPanel {
static final More instance = new More();
final JLabel label = new JLabel(" ... more ");
private More() {
super(new BorderLayout());
add(label, BorderLayout.CENTER);
}
static More get(boolean isSelected) {
instance.setBackground(UIUtil.getListBackground(isSelected));
instance.label.setForeground(UIUtil.getLabelDisabledForeground());
instance.label.setFont(getTitleFont());
instance.label.setBackground(UIUtil.getListBackground(isSelected));
return instance;
}
}
private static JComponent createTitle(String titleText) {
JLabel titleLabel = new JLabel(titleText);
titleLabel.setFont(getTitleFont());
titleLabel.setForeground(UIUtil.getLabelDisabledForeground());
final Color bg = UIUtil.getListBackground();
SeparatorComponent separatorComponent =
new SeparatorComponent(titleLabel.getPreferredSize().height / 2, new JBColor(Gray._220, Gray._80), null);
JPanel result = new JPanel(new BorderLayout(5, 10));
result.add(titleLabel, BorderLayout.WEST);
result.add(separatorComponent, BorderLayout.CENTER);
result.setBackground(bg);
return result;
}
private enum HistoryType {PSI, FILE, SETTING, ACTION, RUN_CONFIGURATION}
@Nullable
private static HistoryType parseHistoryType(@Nullable String name) {
try {
return HistoryType.valueOf(name);
} catch (Exception e) {
return null;
}
}
private static class HistoryItem {
final String pattern, type, fqn;
private HistoryItem(String pattern, String type, String fqn) {
this.pattern = pattern;
this.type = type;
this.fqn = fqn;
}
public String toString() {
return pattern + "\t" + type + "\t" + fqn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HistoryItem item = (HistoryItem)o;
if (!pattern.equals(item.pattern)) return false;
return true;
}
@Override
public int hashCode() {
return pattern.hashCode();
}
}
}
| platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.actions;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.execution.Executor;
import com.intellij.execution.ExecutorRegistry;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ChooseRunConfigurationPopup;
import com.intellij.execution.actions.ExecutorProvider;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.impl.RunDialog;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.ide.SearchTopHitProvider;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.laf.darcula.ui.DarculaTextBorder;
import com.intellij.ide.ui.laf.darcula.ui.DarculaTextFieldUI;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.ide.util.DefaultPsiElementCellRenderer;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.gotoByName.*;
import com.intellij.lang.Language;
import com.intellij.lang.LanguagePsiElementExternalizer;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actions.TextComponentEditorAction;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.MacKeymapUtil;
import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ComponentPopupBuilder;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFilePathWrapper;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.OnOffButton;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.PopupPositionManager;
import com.intellij.util.*;
import com.intellij.util.text.Matcher;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware, DataProvider, RightAlignedToolbarAction {
public static final String SE_HISTORY_KEY = "SearchEverywhereHistoryKey";
public static final int SEARCH_FIELD_COLUMNS = 25;
private static final int MAX_CLASSES = 6;
private static final int MAX_FILES = 6;
private static final int MAX_RUN_CONFIGURATION = 6;
private static final int MAX_TOOL_WINDOWS = 4;
private static final int MAX_SYMBOLS = 6;
private static final int MAX_SETTINGS = 5;
private static final int MAX_ACTIONS = 5;
private static final int MAX_RECENT_FILES = 10;
private static final int DEFAULT_MORE_STEP_COUNT = 15;
public static final int MAX_SEARCH_EVERYWHERE_HISTORY = 50;
private static final int POPUP_MAX_WIDTH = 600;
private static final Logger LOG = Logger.getInstance("#" + SearchEverywhereAction.class.getName());
private SearchEverywhereAction.MyListRenderer myRenderer;
MySearchTextField myPopupField;
private volatile GotoClassModel2 myClassModel;
private volatile GotoFileModel myFileModel;
private volatile GotoActionItemProvider myActionProvider;
private volatile GotoSymbolModel2 mySymbolsModel;
private Component myFocusComponent;
private JBPopup myPopup;
private Map<String, String> myConfigurables = new HashMap<String, String>();
private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, ApplicationManager.getApplication());
private Alarm myUpdateAlarm = new Alarm(ApplicationManager.getApplication());
private JBList myList;
private JCheckBox myNonProjectCheckBox;
private AnActionEvent myActionEvent;
private Component myContextComponent;
private CalcThread myCalcThread;
private static AtomicBoolean ourShiftIsPressed = new AtomicBoolean(false);
private static AtomicBoolean showAll = new AtomicBoolean(false);
private volatile ActionCallback myCurrentWorker = ActionCallback.DONE;
private int myHistoryIndex = 0;
boolean mySkipFocusGain = false;
static {
ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_SEARCH_EVERYWHERE, KeyEvent.VK_SHIFT, -1);
IdeEventQueue.getInstance().addPostprocessor(new IdeEventQueue.EventDispatcher() {
@Override
public boolean dispatch(AWTEvent event) {
if (event instanceof KeyEvent) {
final int keyCode = ((KeyEvent)event).getKeyCode();
if (keyCode == KeyEvent.VK_SHIFT) {
ourShiftIsPressed.set(event.getID() == KeyEvent.KEY_PRESSED);
}
}
return false;
}
}, null);
}
private volatile JBPopup myBalloon;
private int myPopupActualWidth;
private Component myFocusOwner;
private ChooseByNamePopup myFileChooseByName;
private ChooseByNamePopup myClassChooseByName;
private ChooseByNamePopup mySymbolsChooseByName;
private Editor myEditor;
private PsiFile myFile;
private HistoryItem myHistoryItem;
@Override
public JComponent createCustomComponent(Presentation presentation) {
JPanel panel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
if (myBalloon != null && !myBalloon.isDisposed() && myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
final Gradient gradient = getGradientColors();
((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
g.fillRect(0,0,getWidth(), getHeight());
} else {
super.paintComponent(g);
}
}
};
panel.setOpaque(false);
final JLabel label = new JBLabel(AllIcons.Actions.FindPlain) {
{
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
};
panel.add(label, BorderLayout.CENTER);
initTooltip(label);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (myBalloon != null) {
myBalloon.cancel();
}
myFocusOwner = IdeFocusManager.findInstance().getFocusOwner();
label.setToolTipText(null);
IdeTooltipManager.getInstance().hideCurrentNow(false);
label.setIcon(AllIcons.Actions.FindWhite);
actionPerformed(null, e);
}
@Override
public void mouseEntered(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(AllIcons.Actions.Find);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(AllIcons.Actions.FindPlain);
}
}
});
return panel;
}
private static Gradient getGradientColors() {
return new Gradient(
new JBColor(new Color(101, 147, 242), new Color(64, 80, 94)),
new JBColor(new Color(46, 111, 205), new Color(53, 65, 87)));
}
public SearchEverywhereAction() {
updateComponents();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
onFocusLost();
}
});
}
private void updateComponents() {
myRenderer = new MyListRenderer();
myList = new JBList() {
@Override
public Dimension getPreferredSize() {
final Dimension size = super.getPreferredSize();
return new Dimension(Math.min(size.width - 2, POPUP_MAX_WIDTH), size.height);
}
};
myList.setCellRenderer(myRenderer);
myList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.consume();
final int i = myList.locationToIndex(e.getPoint());
if (i != -1) {
mySkipFocusGain = true;
getField().requestFocus();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myList.setSelectedIndex(i);
doNavigate(i);
}
});
}
}
});
myNonProjectCheckBox = new JCheckBox();
myNonProjectCheckBox.setOpaque(false);
myNonProjectCheckBox.setAlignmentX(1.0f);
myNonProjectCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (showAll.get() != myNonProjectCheckBox.isSelected()) {
showAll.set(!showAll.get());
final JTextField editor = UIUtil.findComponentOfType(myBalloon.getContent(), JTextField.class);
if (editor != null) {
final String pattern = editor.getText();
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
@Override
public void run() {
if (editor.hasFocus()) {
rebuildList(pattern);
}
}
}, 30);
}
}
}
});
}
private static void initTooltip(JLabel label) {
final String shortcutText;
shortcutText = getShortcut();
label.setToolTipText("<html><body>Search Everywhere<br/>Press <b>"
+ shortcutText
+ "</b> to access<br/> - Classes<br/> - Files<br/> - Tool Windows<br/> - Actions<br/> - Settings</body></html>");
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
return null;
}
private static String getShortcut() {
String shortcutText;
final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_SEARCH_EVERYWHERE);
if (shortcuts.length == 0) {
shortcutText = "Double " + (SystemInfo.isMac ? MacKeymapUtil.SHIFT : "Shift");
} else {
shortcutText = KeymapUtil.getShortcutsText(shortcuts);
}
return shortcutText;
}
private void initSearchField(final MySearchTextField search) {
final JTextField editor = search.getTextEditor();
// onFocusLost();
editor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
final String pattern = editor.getText();
if (editor.hasFocus()) {
rebuildList(pattern);
}
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if (mySkipFocusGain) {
mySkipFocusGain = false;
return;
}
search.setText("");
search.getTextEditor().setForeground(UIUtil.getLabelForeground());
//titleIndex = new TitleIndexes();
editor.setColumns(SEARCH_FIELD_COLUMNS);
myFocusComponent = e.getOppositeComponent();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JComponent parent = (JComponent)editor.getParent();
parent.revalidate();
parent.repaint();
}
});
//if (myPopup != null && myPopup.isVisible()) {
// myPopup.cancel();
// myPopup = null;
//}
rebuildList("");
}
@Override
public void focusLost(FocusEvent e) {
if ( myPopup instanceof AbstractPopup && myPopup.isVisible()
&& ((myList == e.getOppositeComponent()) || ((AbstractPopup)myPopup).getPopupWindow() == e.getOppositeComponent())) {
return;
}
if (myNonProjectCheckBox == e.getOppositeComponent()) {
mySkipFocusGain = true;
editor.requestFocus();
return;
}
onFocusLost();
}
});
}
private void jumpNextGroup(boolean forward) {
final int index = myList.getSelectedIndex();
final SearchListModel model = getModel();
if (index >= 0) {
final int newIndex = forward ? model.next(index) : model.prev(index);
myList.setSelectedIndex(newIndex);
int more = model.next(newIndex) - 1;
if (more < newIndex) {
more = myList.getItemsCount() - 1;
}
ListScrollingUtil.ensureIndexIsVisible(myList, more, forward ? 1 : -1);
ListScrollingUtil.ensureIndexIsVisible(myList, newIndex, forward ? 1 : -1);
}
}
private SearchListModel getModel() {
return (SearchListModel)myList.getModel();
}
private ActionCallback onFocusLost() {
final ActionCallback result = new ActionCallback();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (myCalcThread != null) {
myCalcThread.cancel();
//myCalcThread = null;
}
myAlarm.cancelAllRequests();
if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) {
myBalloon.cancel();
myPopup.cancel();
}
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ActionToolbarImpl.updateAllToolbarsImmediately();
}
});
} finally {
result.setDone();
}
}
});
return result;
}
private SearchTextField getField() {
return myPopupField;
}
private void doNavigate(final int index) {
final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
final Executor executor = ourShiftIsPressed.get()
? DefaultRunExecutor.getRunExecutorInstance()
: ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
assert project != null;
final SearchListModel model = getModel();
if (isMoreItem(index)) {
final String pattern = myPopupField.getText();
WidgetID wid = null;
if (index == model.moreIndex.classes) wid = WidgetID.CLASSES;
else if (index == model.moreIndex.files) wid = WidgetID.FILES;
else if (index == model.moreIndex.settings) wid = WidgetID.SETTINGS;
else if (index == model.moreIndex.actions) wid = WidgetID.ACTIONS;
else if (index == model.moreIndex.symbols) wid = WidgetID.SYMBOLS;
else if (index == model.moreIndex.runConfigurations) wid = WidgetID.RUN_CONFIGURATIONS;
if (wid != null) {
final WidgetID widgetID = wid;
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myCalcThread = new CalcThread(project, pattern, true);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.insert(index, widgetID);
}
});
return;
}
}
final String pattern = getField().getText();
final Object value = myList.getSelectedValue();
saveHistory(project, pattern, value);
IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(getField().getTextEditor());
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
if (value instanceof BooleanOptionDescription) {
final BooleanOptionDescription option = (BooleanOptionDescription)value;
option.setOptionState(!option.isOptionEnabled());
myList.revalidate();
myList.repaint();
return;
}
Runnable onDone = null;
AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (value instanceof PsiElement) {
onDone = new Runnable() {
public void run() {
NavigationUtil.activateFileWithPsiElement((PsiElement)value, true);
}
};
return;
}
else if (isVirtualFile(value)) {
onDone = new Runnable() {
public void run() {
OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile)value));
}
};
return;
}
else if (isActionValue(value) || isSetting(value) || isRunConfiguration(value)) {
focusManager.requestDefaultFocus(true);
final Component comp = myContextComponent;
final AnActionEvent event = myActionEvent;
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
Component c = comp;
if (c == null) {
c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
}
if (isRunConfiguration(value)) {
((ChooseRunConfigurationPopup.ItemWrapper)value).perform(project, executor, DataManager.getInstance().getDataContext(c));
} else {
GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event);
if (isToolWindowAction(value)) return;
}
}
});
return;
}
else if (value instanceof Navigatable) {
onDone = new Runnable() {
@Override
public void run() {
OpenSourceUtil.navigate(true, (Navigatable)value);
}
};
return;
}
}
finally {
token.finish();
final ActionCallback callback = onFocusLost();
if (onDone != null) {
callback.doWhenDone(onDone);
}
}
focusManager.requestDefaultFocus(true);
}
private boolean isMoreItem(int index) {
final SearchListModel model = getModel();
return index == model.moreIndex.classes ||
index == model.moreIndex.files ||
index == model.moreIndex.settings ||
index == model.moreIndex.actions ||
index == model.moreIndex.symbols ||
index == model.moreIndex.runConfigurations;
}
private void rebuildList(final String pattern) {
assert EventQueue.isDispatchThread() : "Must be EDT";
if (myCalcThread != null && !myCurrentWorker.isProcessed()) {
myCurrentWorker = myCalcThread.cancel();
}
if (myCalcThread != null && !myCalcThread.isCanceled()) {
myCalcThread.cancel();
}
final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
assert project != null;
myRenderer.myProject = project;
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myCalcThread = new CalcThread(project, pattern, false);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.start();
}
});
}
@Override
public void actionPerformed(AnActionEvent e) {
actionPerformed(e, null);
}
public void actionPerformed(AnActionEvent e, MouseEvent me) {
if (myBalloon != null && myBalloon.isVisible()) {
showAll.set(!showAll.get());
myNonProjectCheckBox.setSelected(showAll.get());
// myPopupField.getTextEditor().setBackground(showAll.get() ? new JBColor(new Color(0xffffe4), new Color(0x494539)) : UIUtil.getTextFieldBackground());
rebuildList(myPopupField.getText());
return;
}
myCurrentWorker = ActionCallback.DONE;
if (e != null) {
myEditor = e.getData(CommonDataKeys.EDITOR);
myFile = e.getData(CommonDataKeys.PSI_FILE);
}
if (e == null && myFocusOwner != null) {
e = new AnActionEvent(me, DataManager.getInstance().getDataContext(myFocusOwner), ActionPlaces.UNKNOWN, getTemplatePresentation(), ActionManager.getInstance(), 0);
}
if (e == null) return;
updateComponents();
myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext());
Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent)
: KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
if (wnd == null && myContextComponent instanceof Window) {
wnd = (Window)myContextComponent;
}
if (wnd == null || wnd.getParent() != null) return;
myActionEvent = e;
if (myPopupField != null) {
Disposer.dispose(myPopupField);
}
myPopupField = new MySearchTextField();
myPopupField.getTextEditor().addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
myHistoryIndex = 0;
myHistoryItem = null;
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
myList.repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
myList.repaint();
}
}
});
initSearchField(myPopupField);
myPopupField.setOpaque(false);
final JTextField editor = myPopupField.getTextEditor();
editor.setColumns(SEARCH_FIELD_COLUMNS);
final JPanel panel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
final Gradient gradient = getGradientColors();
((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
g.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(410, super.getPreferredSize().height);
}
};
final JLabel title = new JLabel(" Search Everywhere: ");
final JPanel topPanel = new NonOpaquePanel(new BorderLayout());
title.setForeground(new JBColor(Gray._240, Gray._200));
if (SystemInfo.isMac) {
title.setFont(title.getFont().deriveFont(Font.BOLD, title.getFont().getSize() - 1f));
} else {
title.setFont(title.getFont().deriveFont(Font.BOLD));
}
topPanel.add(title, BorderLayout.WEST);
myNonProjectCheckBox.setForeground(new JBColor(Gray._240, Gray._200));
myNonProjectCheckBox.setText("Include non-project items (" + getShortcut() + ")");
if (!NonProjectScopeDisablerEP.isSearchInNonProjectDisabled()) {
topPanel.add(myNonProjectCheckBox, BorderLayout.EAST);
}
panel.add(myPopupField, BorderLayout.CENTER);
panel.add(topPanel, BorderLayout.NORTH);
panel.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 4, 5));
DataManager.registerDataProvider(panel, this);
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor);
myBalloon = builder
.setCancelOnClickOutside(true)
.setModalContext(false)
.setRequestFocus(true)
.createPopup();
myBalloon.getContent().setBorder(new EmptyBorder(0,0,0,0));
final Window window = WindowManager.getInstance().suggestParentWindow(e.getProject());
//noinspection ConstantConditions
e.getProject().getMessageBus().connect(myBalloon).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
@Override
public void enteredDumbMode() {
}
@Override
public void exitDumbMode() {
rebuildList(myPopupField.getText());
}
});
Component parent = UIUtil.findUltimateParent(window);
registerDataProvider(panel, e.getProject());
final RelativePoint showPoint;
if (me != null) {
final Component label = me.getComponent();
final Component button = label.getParent();
assert button != null;
showPoint = new RelativePoint(button, new Point(button.getWidth() - panel.getPreferredSize().width, button.getHeight()));
} else {
if (parent != null) {
int height = UISettings.getInstance().SHOW_MAIN_TOOLBAR ? 135 : 115;
if (parent instanceof IdeFrameImpl && ((IdeFrameImpl)parent).isInFullScreen()) {
height -= 20;
}
showPoint = new RelativePoint(parent, new Point((parent.getSize().width - panel.getPreferredSize().width)/ 2, height));
} else {
showPoint = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext());
}
}
myList.setFont(UIUtil.getListFont());
myBalloon.show(showPoint);
initSearchActions(myBalloon, myPopupField);
IdeFocusManager focusManager = IdeFocusManager.getInstance(e.getProject());
focusManager.requestFocus(editor, true);
FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE);
}
private static void saveHistory(Project project, String text, Object value) {
if (project == null || project.isDisposed() || !project.isInitialized()) {
return;
}
HistoryType type = null;
String fqn = null;
if (isActionValue(value)) {
type = HistoryType.ACTION;
AnAction action = (AnAction)(value instanceof GotoActionModel.ActionWrapper ? ((GotoActionModel.ActionWrapper)value).getAction() : value);
fqn = ActionManager.getInstance().getId(action);
} else if (value instanceof VirtualFile) {
type = HistoryType.FILE;
fqn = ((VirtualFile)value).getUrl();
} else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
type = HistoryType.RUN_CONFIGURATION;
fqn = ((ChooseRunConfigurationPopup.ItemWrapper)value).getText();
} else if (value instanceof PsiElement) {
final PsiElement psiElement = (PsiElement)value;
final Language language = psiElement.getLanguage();
final String name = LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).getQualifiedName(psiElement);
if (name != null) {
type = HistoryType.PSI;
fqn = language.getID() + "://" + name;
}
}
final PropertiesComponent storage = PropertiesComponent.getInstance(project);
final String[] values = storage.getValues(SE_HISTORY_KEY);
List<HistoryItem> history = new ArrayList<HistoryItem>();
if (values != null) {
for (String s : values) {
final String[] split = s.split("\t");
if (split.length != 3 || text.equals(split[0])) {
continue;
}
if (!StringUtil.isEmpty(split[0])) {
history.add(new HistoryItem(split[0], split[1], split[2]));
}
}
}
history.add(0, new HistoryItem(text, type == null ? null : type.name(), fqn));
if (history.size() > MAX_SEARCH_EVERYWHERE_HISTORY) {
history = history.subList(0, MAX_SEARCH_EVERYWHERE_HISTORY);
}
final String[] newValues = new String[history.size()];
for (int i = 0; i < newValues.length; i++) {
newValues[i] = history.get(i).toString();
}
storage.setValues(SE_HISTORY_KEY, newValues);
}
public Executor getExecutor() {
return ourShiftIsPressed.get() ? DefaultRunExecutor.getRunExecutorInstance()
: ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
private void registerDataProvider(JPanel panel, final Project project) {
DataManager.registerDataProvider(panel, new DataProvider() {
@Nullable
@Override
public Object getData(@NonNls String dataId) {
final Object value = myList.getSelectedValue();
if (CommonDataKeys.PSI_ELEMENT.is(dataId) && value instanceof PsiElement) {
return value;
} else if (CommonDataKeys.VIRTUAL_FILE.is(dataId) && value instanceof VirtualFile) {
return value;
} else if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
if (value instanceof Navigatable) return value;
if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
final Object config = ((ChooseRunConfigurationPopup.ItemWrapper)value).getValue();
if (config instanceof RunnerAndConfigurationSettings) {
return new Navigatable() {
@Override
public void navigate(boolean requestFocus) {
RunDialog.editConfiguration(project, (RunnerAndConfigurationSettings)config, "Edit Configuration", getExecutor());
}
@Override
public boolean canNavigate() {
return true;
}
@Override
public boolean canNavigateToSource() {
return true;
}
};
}
}
}
return null;
}
});
}
private void initSearchActions(JBPopup balloon, MySearchTextField searchTextField) {
final JTextField editor = searchTextField.getTextEditor();
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
jumpNextGroup(true);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
jumpNextGroup(false);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
if (myBalloon != null && myBalloon.isVisible()) {
myBalloon.cancel();
}
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
final int index = myList.getSelectedIndex();
if (index != -1) {
doNavigate(index);
}
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER", "shift ENTER"), editor, balloon);
new DumbAwareAction(){
@Override
public void actionPerformed(AnActionEvent e) {
final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject());
final String[] values = storage.getValues(SE_HISTORY_KEY);
if (values != null) {
if (values.length > myHistoryIndex) {
final List<String> data = StringUtil.split(values[myHistoryIndex], "\t");
myHistoryItem = new HistoryItem(data.get(0), data.get(1), data.get(2));
myHistoryIndex++;
editor.setText(myHistoryItem.pattern);
editor.setCaretPosition(myHistoryItem.pattern.length());
editor.moveCaretPosition(0);
}
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(editor.getCaretPosition() == 0);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon);
}
private static class MySearchTextField extends SearchTextField implements DataProvider, Disposable {
public MySearchTextField() {
super(false);
getTextEditor().setOpaque(false);
getTextEditor().setUI((DarculaTextFieldUI)DarculaTextFieldUI.createUI(getTextEditor()));
getTextEditor().setBorder(new DarculaTextBorder());
getTextEditor().putClientProperty("JTextField.Search.noBorderRing", Boolean.TRUE);
if (UIUtil.isUnderDarcula()) {
getTextEditor().setBackground(Gray._45);
getTextEditor().setForeground(Gray._240);
}
}
@Override
protected boolean isSearchControlUISupported() {
return true;
}
@Override
protected boolean hasIconsOutsideOfTextField() {
return false;
}
@Override
protected void showPopup() {
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) {
return getTextEditor().getText();
}
return null;
}
@Override
public void dispose() {
}
}
private class MyListRenderer extends ColoredListCellRenderer {
ColoredListCellRenderer myLocation = new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
setPaintFocusBorder(false);
append(myLocationString, SimpleTextAttributes.GRAYED_ATTRIBUTES);
setIcon(myLocationIcon);
}
};
GotoFileCellRenderer myFileRenderer = new GotoFileCellRenderer(400);
private String myLocationString;
private DefaultPsiElementCellRenderer myPsiRenderer = new DefaultPsiElementCellRenderer() {
{setFocusBorderEnabled(false);}
};
private Icon myLocationIcon;
private Project myProject;
private JPanel myMainPanel = new JPanel(new BorderLayout());
private JLabel myTitle = new JLabel();
@Override
public void clear() {
super.clear();
myLocation.clear();
myLocationString = null;
myLocationIcon = null;
}
public void setLocationString(String locationString) {
myLocationString = locationString;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component cmp;
PsiElement file = null;
myLocationString = null;
String pattern = "*" + myPopupField.getText();
Matcher matcher = NameUtil.buildMatcher(pattern, 0, true, true, pattern.toLowerCase().equals(pattern));
if (isMoreItem(index)) {
cmp = More.get(isSelected);
} else if (value instanceof VirtualFile
&& myProject != null
&& ((((VirtualFile)value).isDirectory() && (file = PsiManager.getInstance(myProject).findDirectory((VirtualFile)value)) != null )
|| (file = PsiManager.getInstance(myProject).findFile((VirtualFile)value)) != null)) {
myFileRenderer.setPatternMatcher(matcher);
cmp = myFileRenderer.getListCellRendererComponent(list, file, index, isSelected, cellHasFocus);
} else if (value instanceof PsiElement) {
myPsiRenderer.setPatternMatcher(matcher);
cmp = myPsiRenderer.getListCellRendererComponent(list, value, index, isSelected, isSelected);
} else {
cmp = super.getListCellRendererComponent(list, value, index, isSelected, isSelected);
final JPanel p = new JPanel(new BorderLayout());
p.setBackground(UIUtil.getListBackground(isSelected));
p.add(cmp, BorderLayout.CENTER);
cmp = p;
}
if (myLocationString != null || value instanceof BooleanOptionDescription) {
final JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(UIUtil.getListBackground(isSelected));
panel.add(cmp, BorderLayout.CENTER);
final Component rightComponent;
if (value instanceof BooleanOptionDescription) {
final OnOffButton button = new OnOffButton();
button.setSelected(((BooleanOptionDescription)value).isOptionEnabled());
rightComponent = button;
}
else {
rightComponent = myLocation.getListCellRendererComponent(list, value, index, isSelected, isSelected);
}
panel.add(rightComponent, BorderLayout.EAST);
cmp = panel;
}
Color bg = cmp.getBackground();
if (bg == null) {
cmp.setBackground(UIUtil.getListBackground(isSelected));
bg = cmp.getBackground();
}
myMainPanel.setBorder(new CustomLineBorder(bg, 0, 0, 2, 0));
String title = getModel().titleIndex.getTitle(index);
myMainPanel.removeAll();
if (title != null) {
myTitle.setText(title);
myMainPanel.add(createTitle(" " + title), BorderLayout.NORTH);
}
myMainPanel.add(cmp, BorderLayout.CENTER);
final int width = myMainPanel.getPreferredSize().width;
if (width > myPopupActualWidth) {
myPopupActualWidth = width;
//schedulePopupUpdate();
}
return myMainPanel;
}
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
setPaintFocusBorder(false);
setIcon(EmptyIcon.ICON_16);
AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (value instanceof PsiElement) {
String name = myClassModel.getElementName(value);
assert name != null;
append(name);
} else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) {
final ChooseRunConfigurationPopup.ItemWrapper wrapper = (ChooseRunConfigurationPopup.ItemWrapper)value;
append(wrapper.getText());
setIcon(wrapper.getIcon());
setLocationString(ourShiftIsPressed.get() ? "Run" : "Debug");
myLocationIcon = ourShiftIsPressed.get() ? AllIcons.Toolwindows.ToolWindowRun : AllIcons.Toolwindows.ToolWindowDebugger;
} else if (isVirtualFile(value)) {
final VirtualFile file = (VirtualFile)value;
if (file instanceof VirtualFilePathWrapper) {
append(((VirtualFilePathWrapper)file).getPresentablePath());
} else {
append(file.getName());
}
setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject));
}
else if (isActionValue(value)) {
final GotoActionModel.ActionWrapper actionWithParentGroup = value instanceof GotoActionModel.ActionWrapper ? (GotoActionModel.ActionWrapper)value : null;
final AnAction anAction = actionWithParentGroup == null ? (AnAction)value : actionWithParentGroup.getAction();
final Presentation templatePresentation = anAction.getTemplatePresentation();
Icon icon = templatePresentation.getIcon();
if (anAction instanceof ActivateToolWindowAction) {
final String id = ((ActivateToolWindowAction)anAction).getToolWindowId();
ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(id);
if (toolWindow != null) {
icon = toolWindow.getIcon();
}
}
append(templatePresentation.getText());
if (actionWithParentGroup != null) {
final String groupName = actionWithParentGroup.getGroupName();
if (!StringUtil.isEmpty(groupName)) {
setLocationString(groupName);
}
}
final String groupName = actionWithParentGroup == null ? null : actionWithParentGroup.getGroupName();
if (!StringUtil.isEmpty(groupName)) {
setLocationString(groupName);
}
if (icon != null && icon.getIconWidth() <= 16 && icon.getIconHeight() <= 16) {
setIcon(IconUtil.toSize(icon, 16, 16));
}
}
else if (isSetting(value)) {
String text = getSettingText((OptionDescription)value);
append(text);
final String id = ((OptionDescription)value).getConfigurableId();
final String name = myConfigurables.get(id);
if (name != null) {
setLocationString(name);
}
}
else {
ItemPresentation presentation = null;
if (value instanceof ItemPresentation) {
presentation = (ItemPresentation)value;
}
else if (value instanceof NavigationItem) {
presentation = ((NavigationItem)value).getPresentation();
}
if (presentation != null) {
final String text = presentation.getPresentableText();
append(text == null ? value.toString() : text);
final String location = presentation.getLocationString();
if (!StringUtil.isEmpty(location)) {
setLocationString(location);
}
Icon icon = presentation.getIcon(false);
if (icon != null) setIcon(icon);
}
}
}
finally {
token.finish();
}
}
public void recalculateWidth() {
ListModel model = myList.getModel();
myTitle.setIcon(EmptyIcon.ICON_16);
myTitle.setFont(getTitleFont());
int index = 0;
while (index < model.getSize()) {
String title = getModel().titleIndex.getTitle(index);
if (title != null) {
myTitle.setText(title);
}
index++;
}
myTitle.setForeground(Gray._122);
myTitle.setAlignmentY(BOTTOM_ALIGNMENT);
}
}
private static String getSettingText(OptionDescription value) {
String hit = value.getHit();
if (hit == null) {
hit = value.getOption();
}
hit = StringUtil.unescapeXml(hit);
if (hit.length() > 60) {
hit = hit.substring(0, 60) + "...";
}
hit = hit.replace(" ", " "); //avoid extra spaces from mnemonics and xml conversion
String text = hit.trim();
if (text.endsWith(":")) {
text = text.substring(0, text.length() - 1);
}
return text;
}
private static boolean isActionValue(Object o) {
return o instanceof GotoActionModel.ActionWrapper || o instanceof AnAction;
}
private static boolean isSetting(Object o) {
return o instanceof OptionDescription;
}
private static boolean isRunConfiguration(Object o) {
return o instanceof ChooseRunConfigurationPopup.ItemWrapper;
}
private static boolean isVirtualFile(Object o) {
return o instanceof VirtualFile;
}
private static Font getTitleFont() {
return UIUtil.getLabelFont().deriveFont(UIUtil.getFontSize(UIUtil.FontSize.SMALL));
}
enum WidgetID {CLASSES, FILES, ACTIONS, SETTINGS, SYMBOLS, RUN_CONFIGURATIONS}
@SuppressWarnings("SSBasedInspection")
private class CalcThread implements Runnable {
private final Project project;
private final String pattern;
private final ProgressIndicator myProgressIndicator = new ProgressIndicatorBase();
private final ActionCallback myDone = new ActionCallback();
private final SearchListModel myListModel;
private final ArrayList<VirtualFile> myAlreadyAddedFiles = new ArrayList<VirtualFile>();
private final ArrayList<AnAction> myAlreadyAddedActions = new ArrayList<AnAction>();
public CalcThread(Project project, String pattern, boolean reuseModel) {
this.project = project;
this.pattern = pattern;
myListModel = reuseModel ? (SearchListModel)myList.getModel() : new SearchListModel();
}
@Override
public void run() {
try {
check();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb]
myList.getEmptyText().setText("Searching...");
//noinspection unchecked
myList.setModel(myListModel);
}
});
if (pattern.trim().length() == 0) {
buildModelFromRecentFiles();
updatePopup();
return;
}
checkModelsUpToDate(); check();
buildTopHit(pattern); check();
buildRecentFiles(pattern); check();
updatePopup(); check();
buildToolWindows(pattern); check();
updatePopup(); check();
runReadAction(new Runnable() {
public void run() {
buildRunConfigurations(pattern);
}
}, true);
runReadAction(new Runnable() {
public void run() {
buildClasses(pattern);
}
}, true);
runReadAction(new Runnable() {
public void run() {
buildFiles(pattern);
}
}, false);
buildActionsAndSettings(pattern);
updatePopup();
runReadAction(new Runnable() {
public void run() {
buildSymbols(pattern);
}
}, true);
}
catch (ProcessCanceledException ignore) {
myDone.setRejected();
}
catch (Exception e) {
LOG.error(e);
myDone.setRejected();
}
finally {
if (!isCanceled()) {
myList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT);
updatePopup();
}
if (!myDone.isProcessed()) {
myDone.setDone();
}
}
}
private void runReadAction(Runnable action, boolean checkDumb) {
if (!checkDumb || !DumbService.getInstance(project).isDumb()) {
ApplicationManager.getApplication().runReadAction(action);
updatePopup();
}
}
protected void check() {
myProgressIndicator.checkCanceled();
if (myDone.isRejected()) throw new ProcessCanceledException();
if (myBalloon == null || myBalloon.isDisposed()) throw new ProcessCanceledException();
}
private synchronized void buildToolWindows(String pattern) {
final List<ActivateToolWindowAction> actions = new ArrayList<ActivateToolWindowAction>();
for (ActivateToolWindowAction action : ToolWindowsGroup.getToolWindowActions(project)) {
String text = action.getTemplatePresentation().getText();
if (text != null && StringUtil.startsWithIgnoreCase(text, pattern)) {
actions.add(action);
if (actions.size() == MAX_TOOL_WINDOWS) {
break;
}
}
}
check();
if (actions.isEmpty()) {
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myListModel.titleIndex.toolWindows = myListModel.size();
for (Object toolWindow : actions) {
myListModel.addElement(toolWindow);
}
}
});
}
private SearchResult getActionsOrSettings(final String pattern, final int max, final boolean actions) {
final SearchResult result = new SearchResult();
final MinusculeMatcher matcher = new MinusculeMatcher("*" +pattern, NameUtil.MatchingCaseSensitivity.NONE);
if (myActionProvider == null) {
myActionProvider = createActionProvider();
}
myActionProvider.filterElements(pattern, true, new Processor<GotoActionModel.MatchedValue>() {
@Override
public boolean process(GotoActionModel.MatchedValue matched) {
check();
Object object = matched.value;
if (myListModel.contains(object)) return true;
if (!actions && isSetting(object)) {
if (matcher.matches(getSettingText((OptionDescription)object))) {
result.add(object);
}
} else if (actions && !isToolWindowAction(object) && isActionValue(object)) {
result.add(object);
}
return result.size() <= max;
}
});
return result;
}
private synchronized void buildActionsAndSettings(String pattern) {
final SearchResult actions = getActionsOrSettings(pattern, MAX_ACTIONS, true);
final SearchResult settings = getActionsOrSettings(pattern, MAX_SETTINGS, false);
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
if (actions.size() > 0) {
myListModel.titleIndex.actions = myListModel.size();
for (Object action : actions) {
myListModel.addElement(action);
}
}
myListModel.moreIndex.actions = actions.size() >= MAX_ACTIONS ? myListModel.size() - 1 : -1;
if (settings.size() > 0) {
myListModel.titleIndex.settings = myListModel.size();
for (Object setting : settings) {
myListModel.addElement(setting);
}
}
myListModel.moreIndex.settings = settings.size() >= MAX_SETTINGS ? myListModel.size() - 1 : -1;
}
});
}
private synchronized void buildFiles(final String pattern) {
final SearchResult files = getFiles(pattern, MAX_FILES, myFileChooseByName);
check();
if (files.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.files = myListModel.size();
for (Object file : files) {
myListModel.addElement(file);
}
myListModel.moreIndex.files = files.needMore ? myListModel.size() - 1 : -1;
}
});
}
}
private synchronized void buildSymbols(final String pattern) {
final SearchResult symbols = getSymbols(pattern, MAX_SYMBOLS, mySymbolsChooseByName);
check();
if (symbols.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.symbols = myListModel.size();
for (Object file : symbols) {
myListModel.addElement(file);
}
myListModel.moreIndex.symbols = symbols.needMore ? myListModel.size() - 1 : -1;
}
});
}
}
@Nullable
private ChooseRunConfigurationPopup.ItemWrapper getRunConfigurationByName(String name) {
final ChooseRunConfigurationPopup.ItemWrapper[] wrappers =
ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() {
@Override
public Executor getExecutor() {
return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
}, false);
for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) {
if (wrapper.getText().equals(name)) {
return wrapper;
}
}
return null;
}
private synchronized void buildRunConfigurations(String pattern) {
final SearchResult runConfigurations = getConfigurations(pattern, MAX_RUN_CONFIGURATION);
if (runConfigurations.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.runConfigurations = myListModel.size();
for (Object runConfiguration : runConfigurations) {
myListModel.addElement(runConfiguration);
}
myListModel.moreIndex.runConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1;
}
});
}
}
private SearchResult getConfigurations(String pattern, int max) {
SearchResult configurations = new SearchResult();
MinusculeMatcher matcher = new MinusculeMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE);
final ChooseRunConfigurationPopup.ItemWrapper[] wrappers =
ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() {
@Override
public Executor getExecutor() {
return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
}
}, false);
check();
for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) {
if (matcher.matches(wrapper.getText()) && !myListModel.contains(wrapper)) {
if (configurations.size() == max) {
configurations.needMore = true;
break;
}
configurations.add(wrapper);
}
check();
}
return configurations;
}
private synchronized void buildClasses(final String pattern) {
if (pattern.indexOf('.') != -1) {
//todo[kb] it's not a mistake. If we search for "*.png" or "index.xml" in SearchEverywhere
//todo[kb] we don't want to see Java classes started with Png or Xml. This approach should be reworked someday.
return;
}
check();
final SearchResult classes = getClasses(pattern, showAll.get(), MAX_CLASSES, myClassChooseByName);
check();
if (classes.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.classes = myListModel.size();
for (Object file : classes) {
myListModel.addElement(file);
}
myListModel.moreIndex.classes = -1;
if (classes.needMore) {
myListModel.moreIndex.classes = myListModel.size() - 1;
}
}
});
}
}
private SearchResult getSymbols(String pattern, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult symbols = new SearchResult();
final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, false,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
if (o instanceof PsiElement) {
final PsiElement element = (PsiElement)o;
final PsiFile file = element.getContainingFile();
if (!myListModel.contains(o) &&
//some elements are non-physical like DB columns
(file == null || (file.getVirtualFile() != null && scope.accept(file.getVirtualFile())))) {
symbols.add(o);
}
}
symbols.needMore = symbols.size() == max;
return !symbols.needMore;
}
});
return symbols;
}
private SearchResult getClasses(String pattern, boolean includeLibs, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult classes = new SearchResult();
if (chooseByNamePopup == null) {
return classes;
}
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, includeLibs,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
if (o instanceof PsiElement && !myListModel.contains(o) && !classes.contains(o)) {
if (classes.size() == max) {
classes.needMore = true;
return false;
}
classes.add(o);
}
return true;
}
});
if (!includeLibs && classes.isEmpty()) {
return getClasses(pattern, true, max, chooseByNamePopup);
}
return classes;
}
private SearchResult getFiles(final String pattern, final int max, ChooseByNamePopup chooseByNamePopup) {
final SearchResult files = new SearchResult();
if (chooseByNamePopup == null) {
return files;
}
final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, true,
myProgressIndicator, new Processor<Object>() {
@Override
public boolean process(Object o) {
VirtualFile file = null;
if (o instanceof VirtualFile) {
file = (VirtualFile)o;
} else if (o instanceof PsiFile) {
file = ((PsiFile)o).getVirtualFile();
} else if (o instanceof PsiDirectory) {
file = ((PsiDirectory)o).getVirtualFile();
}
if (file != null
&& !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1)
&& (showAll.get() || scope.accept(file)
&& !myListModel.contains(file)
&& !myAlreadyAddedFiles.contains(file))
&& !files.contains(file)) {
if (files.size() == max) {
files.needMore = true;
return false;
}
files.add(file);
}
return true;
}
});
return files;
}
private synchronized void buildRecentFiles(String pattern) {
final MinusculeMatcher matcher = new MinusculeMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE);
final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>();
final List<VirtualFile> selected = Arrays.asList(FileEditorManager.getInstance(project).getSelectedFiles());
for (VirtualFile file : ArrayUtil.reverseArray(EditorHistoryManager.getInstance(project).getFiles())) {
if (StringUtil.isEmptyOrSpaces(pattern) || matcher.matches(file.getName())) {
if (!files.contains(file) && !selected.contains(file)) {
files.add(file);
}
}
if (files.size() > MAX_RECENT_FILES) break;
}
if (files.size() > 0) {
myAlreadyAddedFiles.addAll(files);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
myListModel.titleIndex.recentFiles = myListModel.size();
for (Object file : files) {
myListModel.addElement(file);
}
}
});
}
}
private boolean isCanceled() {
return myProgressIndicator.isCanceled() || myDone.isRejected();
}
private synchronized void buildTopHit(String pattern) {
final List<Object> elements = new ArrayList<Object>();
final HistoryItem history = myHistoryItem;
if (history != null) {
final HistoryType type = parseHistoryType(history.type);
if (type != null) {
switch (type){
case PSI:
if (!DumbService.isDumb(project)) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final int i = history.fqn.indexOf("://");
if (i != -1) {
final String langId = history.fqn.substring(0, i);
final Language language = Language.findLanguageByID(langId);
final String psiFqn = history.fqn.substring(i + 3);
if (language != null) {
final PsiElement psi =
LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).findByQualifiedName(project, psiFqn);
if (psi != null) {
elements.add(psi);
final PsiFile psiFile = psi.getContainingFile();
if (psiFile != null) {
final VirtualFile file = psiFile.getVirtualFile();
if (file != null) {
myAlreadyAddedFiles.add(file);
}
}
}
}
}
}
});
}
break;
case FILE:
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(history.fqn);
if (file != null) {
elements.add(file);
}
break;
case SETTING:
break;
case ACTION:
final AnAction action = ActionManager.getInstance().getAction(history.fqn);
if (action != null) {
elements.add(action);
myAlreadyAddedActions.add(action);
}
break;
case RUN_CONFIGURATION:
if (!DumbService.isDumb(project)) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final ChooseRunConfigurationPopup.ItemWrapper runConfiguration = getRunConfigurationByName(history.fqn);
if (runConfiguration != null) {
elements.add(runConfiguration);
}
}
});
}
break;
}
}
}
final Consumer<Object> consumer = new Consumer<Object>() {
@Override
public void consume(Object o) {
if (isSetting(o) || isVirtualFile(o) || isActionValue(o) || o instanceof PsiElement) {
if (o instanceof AnAction && myAlreadyAddedActions.contains(o)) {
return;
}
elements.add(o);
}
}
};
final ActionManager actionManager = ActionManager.getInstance();
final List<String> actions = AbbreviationManager.getInstance().findActions(pattern);
for (String actionId : actions) {
consumer.consume(actionManager.getAction(actionId));
}
for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) {
check();
provider.consumeTopHits(pattern, consumer);
}
if (elements.size() > 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isCanceled()) return;
for (Object element : elements.toArray()) {
if (element instanceof AnAction) {
final AnAction action = (AnAction)element;
final AnActionEvent e = new AnActionEvent(myActionEvent.getInputEvent(),
myActionEvent.getDataContext(),
myActionEvent.getPlace(),
action.getTemplatePresentation(),
myActionEvent.getActionManager(),
myActionEvent.getModifiers());
ActionUtil.performDumbAwareUpdate(action, e, false);
final Presentation presentation = e.getPresentation();
if (!presentation.isEnabled() || !presentation.isVisible() || StringUtil.isEmpty(presentation.getText())) {
elements.remove(element);
}
if (isCanceled()) return;
}
}
if (isCanceled() || elements.isEmpty()) return;
myListModel.titleIndex.topHit = myListModel.size();
for (Object element : elements) {
myListModel.addElement(element);
}
}
});
}
}
private synchronized void checkModelsUpToDate() {
if (myClassModel == null) {
myClassModel = new GotoClassModel2(project);
myFileModel = new GotoFileModel(project);
mySymbolsModel = new GotoSymbolModel2(project);
myFileChooseByName = ChooseByNamePopup.createPopup(project, myFileModel, (PsiElement)null);
myClassChooseByName = ChooseByNamePopup.createPopup(project, myClassModel, (PsiElement)null);
mySymbolsChooseByName = ChooseByNamePopup.createPopup(project, mySymbolsModel, (PsiElement)null);
project.putUserData(ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, null);
myActionProvider = createActionProvider();
myConfigurables.clear();
fillConfigurablesIds(null, ShowSettingsUtilImpl.getConfigurables(project, true));
}
}
private void buildModelFromRecentFiles() {
buildRecentFiles("");
}
private GotoActionItemProvider createActionProvider() {
GotoActionModel model = new GotoActionModel(project, myFocusComponent, myEditor, myFile) {
@Override
protected MatchMode actionMatches(String pattern, @NotNull AnAction anAction) {
String text = anAction.getTemplatePresentation().getText();
return text != null && NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE)
.matches(text) ? MatchMode.NAME : MatchMode.NONE;
}
};
return new GotoActionItemProvider(model);
}
@SuppressWarnings("SSBasedInspection")
private void updatePopup() {
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myListModel.update();
myList.revalidate();
myList.repaint();
myRenderer.recalculateWidth();
if (myBalloon == null || myBalloon.isDisposed()) {
return;
}
if (myPopup == null || !myPopup.isVisible()) {
final ActionCallback callback = ListDelegationUtil.installKeyboardDelegation(getField().getTextEditor(), myList);
final ComponentPopupBuilder builder = JBPopupFactory.getInstance()
.createComponentPopupBuilder(new JBScrollPane(myList), null);
myPopup = builder
.setRequestFocus(false)
.setCancelKeyEnabled(false)
.setCancelCallback(new Computable<Boolean>() {
@Override
public Boolean compute() {
return myBalloon == null || myBalloon.isDisposed() || !getField().getTextEditor().hasFocus();
}
})
.createPopup();
myPopup.getContent().setBorder(new EmptyBorder(0, 0, 0, 0));
Disposer.register(myPopup, new Disposable() {
@Override
public void dispose() {
callback.setDone();
resetFields();
myNonProjectCheckBox.setSelected(false);
ActionToolbarImpl.updateAllToolbarsImmediately();
if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
final Component component = myActionEvent.getInputEvent().getComponent();
if (component != null) {
final JLabel label = UIUtil.getParentOfType(JLabel.class, component);
if (label != null) {
label.setIcon(AllIcons.Actions.FindPlain);
}
}
}
myActionEvent = null;
}
});
myPopup.show(new RelativePoint(getField().getParent(), new Point(0, getField().getParent().getHeight())));
updatePopupBounds();
ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() {
@Override
public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (action instanceof TextComponentEditorAction) {
return;
}
myPopup.cancel();
}
}, myPopup);
}
else {
myList.revalidate();
myList.repaint();
}
ListScrollingUtil.ensureSelectionExists(myList);
if (myList.getModel().getSize() > 0) {
updatePopupBounds();
}
}
});
}
public ActionCallback cancel() {
myProgressIndicator.cancel();
myDone.setRejected();
return myDone;
}
public ActionCallback insert(final int index, final WidgetID id) {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
runReadAction(new Runnable() {
@Override
public void run() {
try {
final SearchResult result
= id == WidgetID.CLASSES ? getClasses(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myClassChooseByName)
: id == WidgetID.FILES ? getFiles(pattern, DEFAULT_MORE_STEP_COUNT, myFileChooseByName)
: id == WidgetID.RUN_CONFIGURATIONS ? getConfigurations(pattern, DEFAULT_MORE_STEP_COUNT)
: id == WidgetID.SYMBOLS ? getSymbols(pattern, DEFAULT_MORE_STEP_COUNT, mySymbolsChooseByName)
: id == WidgetID.ACTIONS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, true)
: id == WidgetID.SETTINGS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, false)
: new SearchResult();
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
int shift = 0;
int i = index+1;
for (Object o : result) {
//noinspection unchecked
myListModel.insertElementAt(o, i);
shift++;
i++;
}
MoreIndex moreIndex = myListModel.moreIndex;
myListModel.titleIndex.shift(index, shift);
moreIndex.shift(index, shift);
if (!result.needMore) {
switch (id) {
case CLASSES: moreIndex.classes = -1; break;
case FILES: moreIndex.files = -1; break;
case ACTIONS: moreIndex.actions = -1; break;
case SETTINGS: moreIndex.settings = -1; break;
case SYMBOLS: moreIndex.symbols = -1; break;
case RUN_CONFIGURATIONS: moreIndex.runConfigurations = -1; break;
}
}
ListScrollingUtil.selectItem(myList, index);
myDone.setDone();
}
catch (Exception e) {
myDone.setRejected();
}
}
});
}
catch (Exception e) {
myDone.setRejected();
}
}
}, true);
}
});
return myDone;
}
public ActionCallback start() {
ApplicationManager.getApplication().executeOnPooledThread(this);
return myDone;
}
}
protected void resetFields() {
if (myBalloon!= null) {
myBalloon.cancel();
myBalloon = null;
}
myCurrentWorker.doWhenProcessed(new Runnable() {
@Override
public void run() {
myFileModel = null;
if (myFileChooseByName != null) {
myFileChooseByName.close(false);
myFileChooseByName = null;
}
if (myClassChooseByName != null) {
myClassChooseByName.close(false);
myClassChooseByName = null;
}
if (mySymbolsChooseByName != null) {
mySymbolsChooseByName.close(false);
mySymbolsChooseByName = null;
}
final Object lock = myCalcThread;
if (lock != null) {
synchronized (lock) {
myClassModel = null;
myActionProvider = null;
mySymbolsModel = null;
myConfigurables.clear();
myFocusComponent = null;
myContextComponent = null;
myFocusOwner = null;
myRenderer.myProject = null;
myPopup = null;
myHistoryIndex = 0;
myPopupActualWidth = 0;
myCurrentWorker = ActionCallback.DONE;
showAll.set(false);
myCalcThread = null;
}
}
}
});
mySkipFocusGain = false;
}
private void updatePopupBounds() {
if (myPopup == null || !myPopup.isVisible()) {
return;
}
final Container parent = getField().getParent();
final Dimension size = myList.getParent().getParent().getPreferredSize();
size.width = myPopupActualWidth - 2;
if (size.width + 2 < parent.getWidth()) {
size.width = parent.getWidth();
}
if (myList.getItemsCount() == 0) {
size.height = 70;
}
Dimension sz = new Dimension(size.width, myList.getPreferredSize().height);
if (sz.width > POPUP_MAX_WIDTH || sz.height > POPUP_MAX_WIDTH) {
final JBScrollPane pane = new JBScrollPane();
final int extraWidth = pane.getVerticalScrollBar().getWidth() + 1;
final int extraHeight = pane.getHorizontalScrollBar().getHeight() + 1;
sz = new Dimension(Math.min(POPUP_MAX_WIDTH, Math.max(getField().getWidth(), sz.width + extraWidth)), Math.min(POPUP_MAX_WIDTH, sz.height + extraHeight));
sz.width += 20;
sz.height+=2;
} else {
sz.width+=2;
sz.height+=2;
}
sz.width = Math.max(sz.width, myPopup.getSize().width);
myPopup.setSize(sz);
if (myActionEvent != null && myActionEvent.getInputEvent() == null) {
final Point p = parent.getLocationOnScreen();
p.y += parent.getHeight();
if (parent.getWidth() < sz.width) {
p.x -= sz.width - parent.getWidth();
}
myPopup.setLocation(p);
} else {
try {
adjustPopup();
}
catch (Exception ignore) {}
}
}
private void adjustPopup() {
// new PopupPositionManager.PositionAdjuster(getField().getParent(), 0).adjust(myPopup, PopupPositionManager.Position.BOTTOM);
final Dimension d = PopupPositionManager.PositionAdjuster.getPopupSize(myPopup);
final JComponent myRelativeTo = myBalloon.getContent();
Point myRelativeOnScreen = myRelativeTo.getLocationOnScreen();
Rectangle screen = ScreenUtil.getScreenRectangle(myRelativeOnScreen);
Rectangle popupRect = null;
Rectangle r = new Rectangle(myRelativeOnScreen.x, myRelativeOnScreen.y + myRelativeTo.getHeight(), d.width, d.height);
if (screen.contains(r)) {
popupRect = r;
}
if (popupRect != null) {
myPopup.setLocation(new Point(r.x, r.y));
}
else {
if (r.y + d.height > screen.y + screen.height) {
r.height = screen.y + screen.height - r.y - 2;
}
if (r.width > screen.width) {
r.width = screen.width - 50;
}
if (r.x + r.width > screen.x + screen.width) {
r.x = screen.x + screen.width - r.width - 2;
}
myPopup.setSize(r.getSize());
myPopup.setLocation(r.getLocation());
}
}
private static boolean isToolWindowAction(Object o) {
return isActionValue(o)
&& o instanceof GotoActionModel.ActionWrapper
&& ((GotoActionModel.ActionWrapper)o).getAction() instanceof ActivateToolWindowAction;
}
private void fillConfigurablesIds(String pathToParent, Configurable[] configurables) {
for (Configurable configurable : configurables) {
if (configurable instanceof SearchableConfigurable) {
final String id = ((SearchableConfigurable)configurable).getId();
String name = configurable.getDisplayName();
if (pathToParent != null) {
name = pathToParent + " -> " + name;
}
myConfigurables.put(id, name);
if (configurable instanceof SearchableConfigurable.Parent) {
fillConfigurablesIds(name, ((SearchableConfigurable.Parent)configurable).getConfigurables());
}
}
}
}
static class MoreIndex {
volatile int classes = -1;
volatile int files = -1;
volatile int actions = -1;
volatile int settings = -1;
volatile int symbols = -1;
volatile int runConfigurations = -1;
public void shift(int index, int shift) {
if (runConfigurations >= index) runConfigurations += shift;
if (classes >= index) classes += shift;
if (files >= index) files += shift;
if (actions >= index) actions += shift;
if (settings >= index) settings += shift;
if (symbols >= index) symbols += shift;
}
}
static class TitleIndex {
volatile int topHit = -1;
volatile int recentFiles = -1;
volatile int runConfigurations = -1;
volatile int classes = -1;
volatile int files = -1;
volatile int actions = -1;
volatile int settings = -1;
volatile int toolWindows = -1;
volatile int symbols = -1;
final String gotoClassTitle;
final String gotoFileTitle;
final String gotoActionTitle;
final String gotoSettingsTitle;
final String gotoRecentFilesTitle;
final String gotoRunConfigurationsTitle;
final String gotoSymbolTitle;
static final String toolWindowsTitle = "Tool Windows";
TitleIndex() {
String gotoClass = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoClass"));
gotoClassTitle = StringUtil.isEmpty(gotoClass) ? "Classes" : "Classes (" + gotoClass + ")";
String gotoFile = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoFile"));
gotoFileTitle = StringUtil.isEmpty(gotoFile) ? "Files" : "Files (" + gotoFile + ")";
String gotoAction = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoAction"));
gotoActionTitle = StringUtil.isEmpty(gotoAction) ? "Actions" : "Actions (" + gotoAction + ")";
String gotoSettings = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ShowSettings"));
gotoSettingsTitle = StringUtil.isEmpty(gotoAction) ? "Preferences" : "Preferences (" + gotoSettings + ")";
String gotoRecentFiles = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("RecentFiles"));
gotoRecentFilesTitle = StringUtil.isEmpty(gotoRecentFiles) ? "Recent Files" : "Recent Files (" + gotoRecentFiles + ")";
String gotoSymbol = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("GotoSymbol"));
gotoSymbolTitle = StringUtil.isEmpty(gotoSymbol) ? "Symbols" : "Symbols (" + gotoSymbol + ")";
String gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseDebugConfiguration"));
if (StringUtil.isEmpty(gotoRunConfiguration)) {
gotoRunConfiguration = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("ChooseRunConfiguration"));
}
gotoRunConfigurationsTitle = StringUtil.isEmpty(gotoRunConfiguration) ? "Run Configurations" : "Run Configurations (" + gotoRunConfiguration + ")";
}
String getTitle(int index) {
if (index == topHit) return index == 0 ? "Top Hit" : "Top Hits";
if (index == recentFiles) return gotoRecentFilesTitle;
if (index == runConfigurations) return gotoRunConfigurationsTitle;
if (index == classes) return gotoClassTitle;
if (index == files) return gotoFileTitle;
if (index == toolWindows) return toolWindowsTitle;
if (index == actions) return gotoActionTitle;
if (index == settings) return gotoSettingsTitle;
if (index == symbols) return gotoSymbolTitle;
return null;
}
public void clear() {
topHit = -1;
runConfigurations = -1;
recentFiles = -1;
classes = -1;
files = -1;
actions = -1;
settings = -1;
toolWindows = -1;
}
public void shift(int index, int shift) {
if (toolWindows != - 1 && toolWindows > index) toolWindows += shift;
if (settings != - 1 && settings > index) settings += shift;
if (actions != - 1 && actions > index) actions += shift;
if (files != - 1 && files > index) files += shift;
if (classes != - 1 && classes > index) classes += shift;
if (runConfigurations != - 1 && runConfigurations > index) runConfigurations += shift;
if (symbols != - 1 && symbols > index) symbols += shift;
}
}
static class SearchResult extends ArrayList<Object> {
boolean needMore;
}
@SuppressWarnings("unchecked")
private static class SearchListModel extends DefaultListModel {
@SuppressWarnings("UseOfObsoleteCollectionType")
Vector myDelegate;
volatile TitleIndex titleIndex = new TitleIndex();
volatile MoreIndex moreIndex = new MoreIndex();
private SearchListModel() {
super();
myDelegate = ReflectionUtil.getField(DefaultListModel.class, this, Vector.class, "delegate");
}
int next(int index) {
int[] all = getAll();
Arrays.sort(all);
for (int next : all) {
if (next > index) return next;
}
return 0;
}
int[] getAll() {
return new int[]{
titleIndex.topHit,
titleIndex.recentFiles,
titleIndex.runConfigurations,
titleIndex.classes,
titleIndex.files,
titleIndex.actions,
titleIndex.settings,
titleIndex.toolWindows,
titleIndex.symbols,
moreIndex.classes,
moreIndex.actions,
moreIndex.files,
moreIndex.settings,
moreIndex.symbols,
moreIndex.runConfigurations
};
}
int prev(int index) {
int[] all = getAll();
Arrays.sort(all);
for (int i = all.length-1; i >= 0; i--) {
if (all[i] != -1 && all[i] < index) return all[i];
}
return all[all.length - 1];
}
@Override
public void addElement(Object obj) {
myDelegate.add(obj);
}
public void update() {
fireContentsChanged(this, 0, getSize() - 1);
}
}
static class More extends JPanel {
static final More instance = new More();
final JLabel label = new JLabel(" ... more ");
private More() {
super(new BorderLayout());
add(label, BorderLayout.CENTER);
}
static More get(boolean isSelected) {
instance.setBackground(UIUtil.getListBackground(isSelected));
instance.label.setForeground(UIUtil.getLabelDisabledForeground());
instance.label.setFont(getTitleFont());
instance.label.setBackground(UIUtil.getListBackground(isSelected));
return instance;
}
}
private static JComponent createTitle(String titleText) {
JLabel titleLabel = new JLabel(titleText);
titleLabel.setFont(getTitleFont());
titleLabel.setForeground(UIUtil.getLabelDisabledForeground());
final Color bg = UIUtil.getListBackground();
SeparatorComponent separatorComponent =
new SeparatorComponent(titleLabel.getPreferredSize().height / 2, new JBColor(Gray._220, Gray._80), null);
JPanel result = new JPanel(new BorderLayout(5, 10));
result.add(titleLabel, BorderLayout.WEST);
result.add(separatorComponent, BorderLayout.CENTER);
result.setBackground(bg);
return result;
}
private enum HistoryType {PSI, FILE, SETTING, ACTION, RUN_CONFIGURATION}
@Nullable
private static HistoryType parseHistoryType(@Nullable String name) {
try {
return HistoryType.valueOf(name);
} catch (Exception e) {
return null;
}
}
private static class HistoryItem {
final String pattern, type, fqn;
private HistoryItem(String pattern, String type, String fqn) {
this.pattern = pattern;
this.type = type;
this.fqn = fqn;
}
public String toString() {
return pattern + "\t" + type + "\t" + fqn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HistoryItem item = (HistoryItem)o;
if (!pattern.equals(item.pattern)) return false;
return true;
}
@Override
public int hashCode() {
return pattern.hashCode();
}
}
}
| avoid blinking in Search Everywhere
| platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java | avoid blinking in Search Everywhere |
|
Java | apache-2.0 | ac3257d944db935726b14af904e39799388c1de5 | 0 | mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.impl;
import com.intellij.ide.CompositeSelectInTarget;
import com.intellij.ide.SelectInContext;
import com.intellij.ide.SelectInTarget;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.SelectableTreeStructureProvider;
import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.ide.scratch.ScratchFileType;
import com.intellij.ide.scratch.ScratchProjectViewPane;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper implements CompositeSelectInTarget {
private String mySubId;
protected ProjectViewSelectInTarget(Project project) {
super(project);
}
@Override
protected final void select(final Object selector, final VirtualFile virtualFile, final boolean requestFocus) {
select(myProject, selector, getMinorViewId(), mySubId, virtualFile, requestFocus);
}
@NotNull
public static ActionCallback select(@NotNull Project project,
final Object toSelect,
@Nullable final String viewId,
@Nullable final String subviewId,
final VirtualFile virtualFile,
final boolean requestFocus) {
final ProjectView projectView = ProjectView.getInstance(project);
if (projectView == null) return ActionCallback.REJECTED;
if (ApplicationManager.getApplication().isUnitTestMode()) {
AbstractProjectViewPane pane = projectView.getProjectViewPaneById(ProjectViewPane.ID);
pane.select(toSelect, virtualFile, requestFocus);
return ActionCallback.DONE;
}
Supplier<Object> toSelectSupplier = toSelect instanceof PsiElement
? PsiUtilCore.createSmartPsiElementPointer((PsiElement)toSelect)::getElement
: () -> toSelect;
ToolWindowManager windowManager = ToolWindowManager.getInstance(project);
final ToolWindow projectViewToolWindow = windowManager.getToolWindow(ToolWindowId.PROJECT_VIEW);
if (projectViewToolWindow == null) return ActionCallback.REJECTED;
ActionCallback result = new ActionCallback();
final Runnable runnable = () -> {
Runnable r = () -> projectView.selectCB(toSelectSupplier.get(), virtualFile, requestFocus).notify(result);
projectView.changeViewCB(ObjectUtils.chooseNotNull(viewId, ProjectViewPane.ID), subviewId).doWhenProcessed(r);
};
if (requestFocus) {
projectViewToolWindow.activate(runnable, true);
}
else {
projectViewToolWindow.show(runnable);
}
return result;
}
@Override
@NotNull
public Collection<SelectInTarget> getSubTargets(@NotNull SelectInContext context) {
List<SelectInTarget> result = new ArrayList<>();
AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getProjectViewPaneById(getMinorViewId());
int index = 0;
for (String subId : pane.getSubIds()) {
result.add(new ProjectSubViewSelectInTarget(this, subId, index++));
}
return result;
}
public boolean isSubIdSelectable(String subId, SelectInContext context) {
return false;
}
@Override
protected boolean canSelect(PsiFileSystemItem file) {
VirtualFile vFile = PsiUtilCore.getVirtualFile(file);
if (vFile == null || !vFile.isValid()) return false;
ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
return index.getContentRootForFile(vFile, false) != null ||
index.isInLibraryClasses(vFile) ||
index.isInLibrarySource(vFile) ||
Comparing.equal(vFile.getParent(), myProject.getBaseDir()) ||
ScratchProjectViewPane.isScratchesMergedIntoProjectTab() && vFile.getFileType() == ScratchFileType.INSTANCE;
}
public String getSubIdPresentableName(String subId) {
AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getProjectViewPaneById(getMinorViewId());
return pane.getPresentableSubIdName(subId);
}
@Override
public void select(PsiElement element, final boolean requestFocus) {
PsiUtilCore.ensureValid(element);
PsiElement toSelect = null;
for (TreeStructureProvider provider : getProvidersDumbAware()) {
if (provider instanceof SelectableTreeStructureProvider) {
toSelect = ((SelectableTreeStructureProvider) provider).getTopLevelElement(element);
}
if (toSelect != null) {
if (!toSelect.isValid()) {
throw new PsiInvalidElementAccessException(toSelect, "Returned by " + provider);
}
break;
}
}
toSelect = findElementToSelect(element, toSelect);
if (toSelect != null) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(toSelect);
select(toSelect, virtualFile, requestFocus);
}
}
private TreeStructureProvider[] getProvidersDumbAware() {
TreeStructureProvider[] allProviders = Extensions.getExtensions(TreeStructureProvider.EP_NAME, myProject);
List<TreeStructureProvider> dumbAware = DumbService.getInstance(myProject).filterByDumbAwareness(allProviders);
return dumbAware.toArray(new TreeStructureProvider[dumbAware.size()]);
}
@Override
public final String getToolWindowId() {
return ToolWindowId.PROJECT_VIEW;
}
public final void setSubId(String subId) {
mySubId = subId;
}
public final String getSubId() {
return mySubId;
}
} | platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.impl;
import com.intellij.ide.CompositeSelectInTarget;
import com.intellij.ide.SelectInContext;
import com.intellij.ide.SelectInTarget;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.SelectableTreeStructureProvider;
import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.ide.scratch.ScratchFileType;
import com.intellij.ide.scratch.ScratchProjectViewPane;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper implements CompositeSelectInTarget {
private String mySubId;
protected ProjectViewSelectInTarget(Project project) {
super(project);
}
@Override
protected final void select(final Object selector, final VirtualFile virtualFile, final boolean requestFocus) {
select(myProject, selector, getMinorViewId(), mySubId, virtualFile, requestFocus);
}
@NotNull
public static ActionCallback select(@NotNull Project project,
final Object toSelect,
@Nullable final String viewId,
@Nullable final String subviewId,
final VirtualFile virtualFile,
final boolean requestFocus) {
final ActionCallback result = new ActionCallback();
final ProjectView projectView = ProjectView.getInstance(project);
if (ApplicationManager.getApplication().isUnitTestMode()) {
AbstractProjectViewPane pane = projectView.getProjectViewPaneById(ProjectViewPane.ID);
pane.select(toSelect, virtualFile, requestFocus);
return result;
}
Supplier<Object> toSelectSupplier = toSelect instanceof PsiElement
? PsiUtilCore.createSmartPsiElementPointer((PsiElement)toSelect)::getElement
: () -> toSelect;
ToolWindowManager windowManager = ToolWindowManager.getInstance(project);
final ToolWindow projectViewToolWindow = windowManager.getToolWindow(ToolWindowId.PROJECT_VIEW);
final Runnable runnable = () -> {
Runnable r = () -> projectView.selectCB(toSelectSupplier.get(), virtualFile, requestFocus).notify(result);
projectView.changeViewCB(ObjectUtils.chooseNotNull(viewId, ProjectViewPane.ID), subviewId).doWhenProcessed(r);
};
if (requestFocus) {
projectViewToolWindow.activate(runnable, true);
}
else {
projectViewToolWindow.show(runnable);
}
return result;
}
@Override
@NotNull
public Collection<SelectInTarget> getSubTargets(@NotNull SelectInContext context) {
List<SelectInTarget> result = new ArrayList<>();
AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getProjectViewPaneById(getMinorViewId());
int index = 0;
for (String subId : pane.getSubIds()) {
result.add(new ProjectSubViewSelectInTarget(this, subId, index++));
}
return result;
}
public boolean isSubIdSelectable(String subId, SelectInContext context) {
return false;
}
@Override
protected boolean canSelect(PsiFileSystemItem file) {
VirtualFile vFile = PsiUtilCore.getVirtualFile(file);
if (vFile == null || !vFile.isValid()) return false;
ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
return index.getContentRootForFile(vFile, false) != null ||
index.isInLibraryClasses(vFile) ||
index.isInLibrarySource(vFile) ||
Comparing.equal(vFile.getParent(), myProject.getBaseDir()) ||
ScratchProjectViewPane.isScratchesMergedIntoProjectTab() && vFile.getFileType() == ScratchFileType.INSTANCE;
}
public String getSubIdPresentableName(String subId) {
AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getProjectViewPaneById(getMinorViewId());
return pane.getPresentableSubIdName(subId);
}
@Override
public void select(PsiElement element, final boolean requestFocus) {
PsiUtilCore.ensureValid(element);
PsiElement toSelect = null;
for (TreeStructureProvider provider : getProvidersDumbAware()) {
if (provider instanceof SelectableTreeStructureProvider) {
toSelect = ((SelectableTreeStructureProvider) provider).getTopLevelElement(element);
}
if (toSelect != null) {
if (!toSelect.isValid()) {
throw new PsiInvalidElementAccessException(toSelect, "Returned by " + provider);
}
break;
}
}
toSelect = findElementToSelect(element, toSelect);
if (toSelect != null) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(toSelect);
select(toSelect, virtualFile, requestFocus);
}
}
private TreeStructureProvider[] getProvidersDumbAware() {
TreeStructureProvider[] allProviders = Extensions.getExtensions(TreeStructureProvider.EP_NAME, myProject);
List<TreeStructureProvider> dumbAware = DumbService.getInstance(myProject).filterByDumbAwareness(allProviders);
return dumbAware.toArray(new TreeStructureProvider[dumbAware.size()]);
}
@Override
public final String getToolWindowId() {
return ToolWindowId.PROJECT_VIEW;
}
public final void setSubId(String subId) {
mySubId = subId;
}
public final String getSubId() {
return mySubId;
}
} | EA-107962 - NPE: ProjectViewSelectInTarget.select
| platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java | EA-107962 - NPE: ProjectViewSelectInTarget.select |
|
Java | apache-2.0 | 069bfab2c5339c23c8201d3ea67be82d3bb550fe | 0 | akosyakov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,signed/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vladmm/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ibinti/intellij-community,kdwink/intellij-community,consulo/consulo,caot/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ryano144/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,semonte/intellij-community,da1z/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,holmes/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,allotria/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,fnouama/intellij-community,fitermay/intellij-community,semonte/intellij-community,kdwink/intellij-community,xfournet/intellij-community,fnouama/intellij-community,holmes/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,signed/intellij-community,FHannes/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,kdwink/intellij-community,hurricup/intellij-community,FHannes/intellij-community,semonte/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,samthor/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,slisson/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,Distrotech/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,xfournet/intellij-community,kool79/intellij-community,blademainer/intellij-community,ernestp/consulo,orekyuu/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,semonte/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,caot/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ryano144/intellij-community,ryano144/intellij-community,amith01994/intellij-community,clumsy/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ibinti/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ibinti/intellij-community,youdonghai/intellij-community,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kool79/intellij-community,retomerz/intellij-community,petteyg/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,slisson/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,dslomov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,da1z/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,samthor/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,consulo/consulo,caot/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,allotria/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,petteyg/intellij-community,supersven/intellij-community,dslomov/intellij-community,diorcety/intellij-community,xfournet/intellij-community,samthor/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,izonder/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,kdwink/intellij-community,amith01994/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,diorcety/intellij-community,ryano144/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fnouama/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,holmes/intellij-community,fitermay/intellij-community,da1z/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,samthor/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ernestp/consulo,orekyuu/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,adedayo/intellij-community,signed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,kool79/intellij-community,xfournet/intellij-community,petteyg/intellij-community,hurricup/intellij-community,fnouama/intellij-community,kdwink/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,slisson/intellij-community,fnouama/intellij-community,signed/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,signed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,signed/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,blademainer/intellij-community,blademainer/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,semonte/intellij-community,kool79/intellij-community,robovm/robovm-studio,izonder/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,caot/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,signed/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,asedunov/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,vladmm/intellij-community,blademainer/intellij-community,vladmm/intellij-community,semonte/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,holmes/intellij-community,adedayo/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,consulo/consulo,da1z/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,signed/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,vvv1559/intellij-community,supersven/intellij-community,kool79/intellij-community,kdwink/intellij-community,hurricup/intellij-community,da1z/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,consulo/consulo,tmpgit/intellij-community,signed/intellij-community,fnouama/intellij-community,amith01994/intellij-community,allotria/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,izonder/intellij-community,holmes/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,apixandru/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,caot/intellij-community,caot/intellij-community,holmes/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,allotria/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,slisson/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,blademainer/intellij-community,da1z/intellij-community,robovm/robovm-studio,hurricup/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,holmes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,slisson/intellij-community,allotria/intellij-community,diorcety/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,samthor/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,petteyg/intellij-community,adedayo/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,consulo/consulo,robovm/robovm-studio,Lekanich/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,ernestp/consulo,allotria/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,ernestp/consulo,retomerz/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,allotria/intellij-community,blademainer/intellij-community,semonte/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,slisson/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,izonder/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,samthor/intellij-community,slisson/intellij-community,FHannes/intellij-community,holmes/intellij-community,apixandru/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ryano144/intellij-community,kool79/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,caot/intellij-community,signed/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ibinti/intellij-community,fnouama/intellij-community,petteyg/intellij-community,consulo/consulo,Lekanich/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,vladmm/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.idea.Bombed;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.util.*;
import com.intellij.util.containers.HashMap;
import com.intellij.util.io.ZipUtil;
import com.intellij.util.ui.UIUtil;
import junit.framework.AssertionFailedError;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.junit.Assert;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.InvocationEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.JarFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author yole
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class PlatformTestUtil {
public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build"));
public static final CvsVirtualFileFilter CVS_FILE_FILTER = new CvsVirtualFileFilter();
public static <T> void registerExtension(final ExtensionPointName<T> name, final T t, final Disposable parentDisposable) {
registerExtension(Extensions.getRootArea(), name, t, parentDisposable);
}
public static <T> void registerExtension(final ExtensionsArea area, final ExtensionPointName<T> name, final T t, final Disposable parentDisposable) {
final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(name.getName());
extensionPoint.registerExtension(t);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
extensionPoint.unregisterExtension(t);
}
});
}
@Nullable
protected static String toString(Object node, @Nullable Queryable.PrintInfo printInfo) {
if (node instanceof AbstractTreeNode) {
if (printInfo != null) {
return ((AbstractTreeNode)node).toTestString(printInfo);
}
else {
@SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"})
final String presentation = ((AbstractTreeNode)node).getTestPresentation();
return presentation;
}
}
else if (node == null) {
return "NULL";
}
else {
return node.toString();
}
}
public static String print(JTree tree, boolean withSelection) {
return print(tree, withSelection, null);
}
public static String print(JTree tree, boolean withSelection, @Nullable Condition<String> nodePrintCondition) {
StringBuilder buffer = new StringBuilder();
final Collection<String> strings = printAsList(tree, withSelection, nodePrintCondition);
for (String string : strings) {
buffer.append(string).append("\n");
}
return buffer.toString();
}
public static Collection<String> printAsList(JTree tree, boolean withSelection, @Nullable Condition<String> nodePrintCondition) {
Collection<String> strings = new ArrayList<String>();
Object root = tree.getModel().getRoot();
printImpl(tree, root, strings, 0, withSelection, nodePrintCondition);
return strings;
}
private static void printImpl(JTree tree,
Object root,
Collection<String> strings,
int level,
boolean withSelection,
@Nullable Condition<String> nodePrintCondition) {
DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode)root;
final Object userObject = defaultMutableTreeNode.getUserObject();
String nodeText;
if (userObject != null) {
nodeText = toString(userObject, null);
}
else {
nodeText = "null";
}
if (nodePrintCondition != null && !nodePrintCondition.value(nodeText)) return;
final StringBuilder buff = StringBuilderSpinAllocator.alloc();
try {
StringUtil.repeatSymbol(buff, ' ', level);
final boolean expanded = tree.isExpanded(new TreePath(defaultMutableTreeNode.getPath()));
if (!defaultMutableTreeNode.isLeaf()) {
buff.append(expanded ? "-" : "+");
}
final boolean selected = tree.getSelectionModel().isPathSelected(new TreePath(defaultMutableTreeNode.getPath()));
if (withSelection && selected) {
buff.append("[");
}
buff.append(nodeText);
if (withSelection && selected) {
buff.append("]");
}
strings.add(buff.toString());
int childCount = tree.getModel().getChildCount(root);
if (expanded) {
for (int i = 0; i < childCount; i++) {
printImpl(tree, tree.getModel().getChild(root, i), strings, level + 1, withSelection, nodePrintCondition);
}
}
}
finally {
StringBuilderSpinAllocator.dispose(buff);
}
}
public static void assertTreeEqual(JTree tree, @NonNls String expected) {
assertTreeEqual(tree, expected, false);
}
public static void assertTreeEqualIgnoringNodesOrder(JTree tree, @NonNls String expected) {
assertTreeEqualIgnoringNodesOrder(tree, expected, false);
}
public static void assertTreeEqual(JTree tree, String expected, boolean checkSelected) {
String treeStringPresentation = print(tree, checkSelected);
assertEquals(expected, treeStringPresentation);
}
public static void assertTreeEqualIgnoringNodesOrder(JTree tree, String expected, boolean checkSelected) {
final Collection<String> actualNodesPresentation = printAsList(tree, checkSelected, null);
final List<String> expectedNodes = StringUtil.split(expected, "\n");
UsefulTestCase.assertSameElements(actualNodesPresentation, expectedNodes);
}
@TestOnly
public static void waitForAlarm(final int delay) throws InterruptedException {
assert !ApplicationManager.getApplication().isWriteAccessAllowed(): "It's a bad idea to wait for an alarm under the write action. Somebody creates an alarm which requires read action and you are deadlocked.";
assert ApplicationManager.getApplication().isDispatchThread();
final AtomicBoolean invoked = new AtomicBoolean();
final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
alarm.addRequest(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
alarm.addRequest(new Runnable() {
@Override
public void run() {
invoked.set(true);
}
}, delay);
}
});
}
}, delay);
UIUtil.dispatchAllInvocationEvents();
boolean sleptAlready = false;
while (!invoked.get()) {
UIUtil.dispatchAllInvocationEvents();
//noinspection BusyWait
Thread.sleep(sleptAlready ? 10 : delay);
sleptAlready = true;
}
UIUtil.dispatchAllInvocationEvents();
}
@TestOnly
public static void dispatchAllInvocationEventsInIdeEventQueue() throws InterruptedException {
assert SwingUtilities.isEventDispatchThread() : Thread.currentThread();
final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
while (true) {
AWTEvent event = eventQueue.peekEvent();
if (event == null) break;
AWTEvent event1 = eventQueue.getNextEvent();
if (event1 instanceof InvocationEvent) {
IdeEventQueue.getInstance().dispatchEvent(event1);
}
}
}
private static Date raidDate(Bombed bombed) {
final Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, bombed.year());
instance.set(Calendar.MONTH, bombed.month());
instance.set(Calendar.DAY_OF_MONTH, bombed.day());
instance.set(Calendar.HOUR_OF_DAY, bombed.time());
instance.set(Calendar.MINUTE, 0);
return instance.getTime();
}
public static boolean bombExplodes(Bombed bombedAnnotation) {
Date now = new Date();
return now.after(raidDate(bombedAnnotation));
}
public static boolean isRotten(Bombed bomb) {
long bombRotPeriod = 30L * 24 * 60 * 60 * 1000; // month
return new Date().after(new Date(raidDate(bomb).getTime() + bombRotPeriod));
}
public static StringBuilder print(AbstractTreeStructure structure,
Object node,
int currentLevel,
@Nullable Comparator comparator,
int maxRowCount,
char paddingChar,
@Nullable Queryable.PrintInfo printInfo) {
StringBuilder buffer = StringBuilderSpinAllocator.alloc();
doPrint(buffer, currentLevel, node, structure, comparator, maxRowCount, 0, paddingChar, printInfo);
return buffer;
}
private static int doPrint(StringBuilder buffer,
int currentLevel,
Object node,
AbstractTreeStructure structure,
@Nullable Comparator comparator,
int maxRowCount,
int currentLine,
char paddingChar,
@Nullable Queryable.PrintInfo printInfo) {
if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine;
StringUtil.repeatSymbol(buffer, paddingChar, currentLevel);
buffer.append(toString(node, printInfo)).append("\n");
currentLine++;
Object[] children = structure.getChildElements(node);
if (comparator != null) {
ArrayList<?> list = new ArrayList<Object>(Arrays.asList(children));
@SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"}) Comparator<Object> c = comparator;
Collections.sort(list, c);
children = ArrayUtil.toObjectArray(list);
}
for (Object child : children) {
currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, printInfo);
}
return currentLine;
}
public static String print(Object[] objects) {
return print(Arrays.asList(objects));
}
public static String print(Collection c) {
StringBuilder result = new StringBuilder();
for (Iterator iterator = c.iterator(); iterator.hasNext();) {
Object each = iterator.next();
result.append(toString(each, null));
if (iterator.hasNext()) {
result.append("\n");
}
}
return result.toString();
}
public static String print(ListModel model) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < model.getSize(); i++) {
result.append(toString(model.getElementAt(i), null));
result.append("\n");
}
return result.toString();
}
public static String print(JTree tree) {
return print(tree, false);
}
public static void assertTreeStructureEquals(final AbstractTreeStructure treeStructure, final String expected) {
assertEquals(expected, print(treeStructure, treeStructure.getRootElement(), 0, null, -1, ' ', null).toString());
}
public static void invokeNamedAction(final String actionId) {
final AnAction action = ActionManager.getInstance().getAction(actionId);
assertNotNull(action);
final Presentation presentation = new Presentation();
@SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext();
final AnActionEvent event = new AnActionEvent(null, context, "", presentation, ActionManager.getInstance(), 0);
action.update(event);
Assert.assertTrue(presentation.isEnabled());
action.actionPerformed(event);
}
public static void assertTiming(final String message, final long expected, final long actual) {
if (COVERAGE_ENABLED_BUILD) return;
final long expectedOnMyMachine = Math.max(1, expected * Timings.MACHINE_TIMING / Timings.ETALON_TIMING);
final double acceptableChangeFactor = 1.1;
// Allow 10% more in case of test machine is busy.
String logMessage = message;
if (actual > expectedOnMyMachine) {
int percentage = (int)(100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine);
logMessage += ". Operation took " + percentage + "% longer than expected";
}
logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." +
" Actual: " + actual + "." +
" Expected on Standard machine: " + expected + ";" +
" Actual on Standard: " + actual * Timings.ETALON_TIMING / Timings.MACHINE_TIMING + ";" +
" Timings: CPU=" + Timings.CPU_TIMING +
", I/O=" + Timings.IO_TIMING + "." +
" (" + (int)(Timings.MACHINE_TIMING*1.0/Timings.ETALON_TIMING*100) + "% of the Standard)" +
".";
if (actual < expectedOnMyMachine) {
System.out.println(logMessage);
TeamCityLogger.info(logMessage);
}
else if (actual < expectedOnMyMachine * acceptableChangeFactor) {
TeamCityLogger.warning(logMessage, null);
}
else {
// throw AssertionFailedError to try one more time
throw new AssertionFailedError(logMessage);
}
}
/**
* example usage: startPerformanceTest("calculating pi",100, testRunnable).cpuBound().assertTiming();
*/
public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expected, @NotNull ThrowableRunnable test) {
return new TestInfo(test, expected,message);
}
// calculates average of the median values in the selected part of the array. E.g. for part=3 returns average in the middle third.
public static long averageAmongMedians(@NotNull long[] time, int part) {
assert part >= 1;
int n = time.length;
Arrays.sort(time);
long total = 0;
for (int i= n /2- n / part /2; i< n /2+ n / part /2; i++) {
total += time[i];
}
return total/(n / part);
}
public static boolean canRunTest(@NotNull Class testCaseClass) {
if (GraphicsEnvironment.isHeadless()) {
for (Class<?> clazz = testCaseClass; clazz != null; clazz = clazz.getSuperclass()) {
if (clazz.getAnnotation(SkipInHeadlessEnvironment.class) != null) {
System.out.println("Class '" + testCaseClass.getName() + "' is skipped because it requires working UI environment");
return false;
}
}
}
return true;
}
public static class TestInfo {
private final ThrowableRunnable test; // runnable to measure
private final int expected; // millis the test is expected to run
private ThrowableRunnable setup; // to run before each test
private boolean usesAllCPUCores; // true if the test runs faster on multi-core
private int attempts = 4; // number of retries if performance failed
private final String message; // to print on fail
private boolean adjustForIO = true; // true if test uses IO, timings need to be re-calibrated according to this agent disk performance
private boolean adjustForCPU = true; // true if test uses CPU, timings need to be re-calibrated according to this agent CPU speed
private TestInfo(@NotNull ThrowableRunnable test, int expected, String message) {
this.test = test;
this.expected = expected;
assert expected > 0 : "Expected must be > 0. Was: "+ expected;
this.message = message;
}
public TestInfo setup(@NotNull ThrowableRunnable setup) { assert this.setup==null; this.setup = setup; return this; }
public TestInfo usesAllCPUCores() { assert adjustForCPU : "This test configured to be io-bound, it cannot use all cores"; usesAllCPUCores = true; return this; }
public TestInfo cpuBound() { adjustForIO = false; adjustForCPU = true; return this; }
public TestInfo ioBound() { adjustForIO = true; adjustForCPU = false; return this; }
public TestInfo attempts(int attempts) { this.attempts = attempts; return this; }
public void assertTiming() {
assert expected != 0 : "Must call .expect() before run test";
if (COVERAGE_ENABLED_BUILD) return;
while (true) {
attempts--;
long start;
try {
if (setup != null) setup.run();
start = System.currentTimeMillis();
test.run();
}
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
long finish = System.currentTimeMillis();
long duration = finish - start;
int expectedOnMyMachine = expected;
if (adjustForCPU) {
expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.CPU_TIMING, Timings.ETALON_CPU_TIMING);
expectedOnMyMachine = usesAllCPUCores ? expectedOnMyMachine * 8 / JobSchedulerImpl.CORES_COUNT : expectedOnMyMachine;
}
if (adjustForIO) {
expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.IO_TIMING, Timings.ETALON_IO_TIMING);
}
final double acceptableChangeFactor = 1.1;
// Allow 10% more in case of test machine is busy.
String logMessage = message;
if (duration > expectedOnMyMachine) {
int percentage = (int)(100.0 * (duration - expectedOnMyMachine) / expectedOnMyMachine);
logMessage += ". (" + percentage + "% longer).";
}
logMessage += " Expected: " + expectedOnMyMachine + "." +
" Actual: " + duration + "." + Timings.getStatistics() ;
if (duration < expectedOnMyMachine) {
int percentage = (int)(100.0 * (expectedOnMyMachine - duration) / expectedOnMyMachine);
logMessage = "(" + percentage + "% faster). " + logMessage;
TeamCityLogger.info(logMessage);
System.out.println("SUCCESS: "+logMessage);
}
else if (duration < expectedOnMyMachine * acceptableChangeFactor) {
TeamCityLogger.warning(logMessage, null);
System.out.println("WARNING: " + logMessage);
}
else {
// try one more time
if (attempts == 0) {
//try {
// Object result = Class.forName("com.intellij.util.ProfilingUtil").getMethod("captureCPUSnapshot").invoke(null);
// System.err.println("CPU snapshot captured in '"+result+"'");
//}
//catch (Exception e) {
//}
throw new AssertionFailedError(logMessage);
}
System.gc();
System.gc();
System.gc();
String s = "Another epic fail (remaining attempts: " + attempts + "): " + logMessage;
TeamCityLogger.warning(s, null);
System.err.println(s);
//if (attempts == 1) {
// try {
// Class.forName("com.intellij.util.ProfilingUtil").getMethod("startCPUProfiling").invoke(null);
// }
// catch (Exception e) {
// }
//}
continue;
}
break;
}
}
private static int adjust(int expectedOnMyMachine, long thisTiming, long ethanolTiming) {
// most of our algorithms are quadratic. sad but true.
double speed = 1.0 * thisTiming / ethanolTiming;
double delta = speed < 1
? 0.9 + Math.pow(speed - 0.7, 2)
: 0.45 + Math.pow(speed - 0.25, 2);
expectedOnMyMachine *= delta;
return expectedOnMyMachine;
}
}
public static void assertTiming(String message, long expected, @NotNull Runnable actionToMeasure) {
assertTiming(message, expected, 4, actionToMeasure);
}
public static long measure(@NotNull Runnable actionToMeasure) {
long start = System.currentTimeMillis();
actionToMeasure.run();
long finish = System.currentTimeMillis();
return finish - start;
}
public static void assertTiming(String message, long expected, int attempts, @NotNull Runnable actionToMeasure) {
while (true) {
attempts--;
long duration = measure(actionToMeasure);
try {
assertTiming(message, expected, duration);
break;
}
catch (AssertionFailedError e) {
if (attempts == 0) throw e;
System.gc();
System.gc();
System.gc();
String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage();
TeamCityLogger.warning(s, null);
System.err.println(s);
}
}
}
private static HashMap<String, VirtualFile> buildNameToFileMap(VirtualFile[] files, @Nullable VirtualFileFilter filter) {
HashMap<String, VirtualFile> map = new HashMap<String, VirtualFile>();
for (VirtualFile file : files) {
if (filter != null && !filter.accept(file)) continue;
map.put(file.getName(), file);
}
return map;
}
public static void assertDirectoriesEqual(VirtualFile dirAfter, VirtualFile dirBefore, @Nullable VirtualFileFilter fileFilter) throws IOException {
FileDocumentManager.getInstance().saveAllDocuments();
dirAfter.getChildren();
dirAfter.refresh(false, false);
VirtualFile[] childrenAfter = dirAfter.getChildren();
if (dirAfter.isInLocalFileSystem()) {
File[] ioAfter = new File(dirAfter.getPath()).listFiles();
shallowCompare(childrenAfter, ioAfter);
}
VirtualFile[] childrenBefore = dirBefore.getChildren();
if (dirBefore.isInLocalFileSystem()) {
File[] ioBefore = new File(dirBefore.getPath()).listFiles();
shallowCompare(childrenBefore, ioBefore);
}
HashMap<String, VirtualFile> mapAfter = buildNameToFileMap(childrenAfter, fileFilter);
HashMap<String, VirtualFile> mapBefore = buildNameToFileMap(childrenBefore, fileFilter);
Set<String> keySetAfter = mapAfter.keySet();
Set<String> keySetBefore = mapBefore.keySet();
assertEquals(keySetAfter, keySetBefore);
for (String name : keySetAfter) {
VirtualFile fileAfter = mapAfter.get(name);
VirtualFile fileBefore = mapBefore.get(name);
if (fileAfter.isDirectory()) {
assertDirectoriesEqual(fileAfter, fileBefore, fileFilter);
}
else {
assertFilesEqual(fileAfter, fileBefore);
}
}
}
private static void shallowCompare(final VirtualFile[] vfs, final File[] io) {
List<String> vfsPaths = new ArrayList<String>();
for (VirtualFile file : vfs) {
vfsPaths.add(file.getPath());
}
List<String> ioPaths = new ArrayList<String>();
for (File file : io) {
ioPaths.add(file.getPath().replace(File.separatorChar, '/'));
}
assertEquals(sortAndJoin(vfsPaths), sortAndJoin(ioPaths));
}
private static String sortAndJoin(List<String> strings) {
Collections.sort(strings);
StringBuilder buf = new StringBuilder();
for (String string : strings) {
buf.append(string);
buf.append('\n');
}
return buf.toString();
}
public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore) throws IOException {
try {
assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore));
}
catch (IOException e) {
FileDocumentManager manager = FileDocumentManager.getInstance();
Document docBefore = manager.getDocument(fileBefore);
boolean canLoadBeforeText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
String textB = docBefore != null
? docBefore.getText()
: !canLoadBeforeText
? null
: LoadTextUtil.getTextByBinaryPresentation(fileBefore.contentsToByteArray(false), fileBefore).toString();
Document docAfter = manager.getDocument(fileAfter);
boolean canLoadAfterText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
String textA = docAfter != null
? docAfter.getText()
: !canLoadAfterText
? null
: LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString();
if (textA != null && textB != null) {
assertEquals(fileAfter.getPath(), textA, textB);
}
else {
Assert.assertArrayEquals(fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray());
}
}
}
public static void assertJarFilesEqual(File file1, File file2) throws IOException {
final File tempDirectory1;
final File tempDirectory2;
final JarFile jarFile1 = new JarFile(file1);
try {
final JarFile jarFile2 = new JarFile(file2);
try {
tempDirectory1 = PlatformTestCase.createTempDir("tmp1");
tempDirectory2 = PlatformTestCase.createTempDir("tmp2");
ZipUtil.extract(jarFile1, tempDirectory1, CVS_FILE_FILTER);
ZipUtil.extract(jarFile2, tempDirectory2, CVS_FILE_FILTER);
}
finally {
jarFile2.close();
}
}
finally {
jarFile1.close();
}
final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1);
assertNotNull(tempDirectory1.toString(), dirAfter);
final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2);
assertNotNull(tempDirectory2.toString(), dirBefore);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
dirAfter.refresh(false, true);
dirBefore.refresh(false, true);
}
});
assertDirectoriesEqual(dirAfter, dirBefore, CVS_FILE_FILTER);
}
public static void assertElementsEqual(final Element expected, final Element actual) throws IOException {
if (!JDOMUtil.areElementsEqual(expected, actual)) {
junit.framework.Assert.assertEquals(printElement(expected), printElement(actual));
}
}
public static String printElement(final Element element) throws IOException {
final StringWriter writer = new StringWriter();
JDOMUtil.writeElement(element, writer, "\n");
return writer.getBuffer().toString();
}
public static class CvsVirtualFileFilter implements VirtualFileFilter, FilenameFilter {
@Override
public boolean accept(VirtualFile file) {
return !file.isDirectory() || !"CVS".equals(file.getName());
}
@Override
public boolean accept(File dir, String name) {
return !name.contains("CVS");
}
}
public static String getCommunityPath() {
final String homePath = PathManager.getHomePath();
if (new File(homePath, "community").exists()) {
return homePath + File.separatorChar + "community";
}
return homePath;
}
public static Comparator<AbstractTreeNode> createComparator(final Queryable.PrintInfo printInfo) {
return new Comparator<AbstractTreeNode>() {
@Override
public int compare(final AbstractTreeNode o1, final AbstractTreeNode o2) {
String displayText1 = o1.toTestString(printInfo);
String displayText2 = o2.toTestString(printInfo);
return Comparing.compare(displayText1, displayText2);
}
};
}
@NotNull
public static <T> T notNull(@Nullable T t) {
assertNotNull(t);
return t;
}
}
| platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.idea.Bombed;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.util.*;
import com.intellij.util.containers.HashMap;
import com.intellij.util.io.ZipUtil;
import com.intellij.util.ui.UIUtil;
import junit.framework.AssertionFailedError;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.junit.Assert;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.InvocationEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.JarFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author yole
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class PlatformTestUtil {
public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build"));
public static final CvsVirtualFileFilter CVS_FILE_FILTER = new CvsVirtualFileFilter();
public static <T> void registerExtension(final ExtensionPointName<T> name, final T t, final Disposable parentDisposable) {
registerExtension(Extensions.getRootArea(), name, t, parentDisposable);
}
public static <T> void registerExtension(final ExtensionsArea area, final ExtensionPointName<T> name, final T t, final Disposable parentDisposable) {
final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(name.getName());
extensionPoint.registerExtension(t);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
extensionPoint.unregisterExtension(t);
}
});
}
@Nullable
protected static String toString(Object node, @Nullable Queryable.PrintInfo printInfo) {
if (node instanceof AbstractTreeNode) {
if (printInfo != null) {
return ((AbstractTreeNode)node).toTestString(printInfo);
}
else {
@SuppressWarnings({"deprecation", "UnnecessaryLocalVariable"})
final String presentation = ((AbstractTreeNode)node).getTestPresentation();
return presentation;
}
}
else if (node == null) {
return "NULL";
}
else {
return node.toString();
}
}
public static String print(JTree tree, boolean withSelection) {
return print(tree, withSelection, null);
}
public static String print(JTree tree, boolean withSelection, @Nullable Condition<String> nodePrintCondition) {
StringBuilder buffer = new StringBuilder();
final Collection<String> strings = printAsList(tree, withSelection, nodePrintCondition);
for (String string : strings) {
buffer.append(string).append("\n");
}
return buffer.toString();
}
public static Collection<String> printAsList(JTree tree, boolean withSelection, @Nullable Condition<String> nodePrintCondition) {
Collection<String> strings = new ArrayList<String>();
Object root = tree.getModel().getRoot();
printImpl(tree, root, strings, 0, withSelection, nodePrintCondition);
return strings;
}
private static void printImpl(JTree tree,
Object root,
Collection<String> strings,
int level,
boolean withSelection,
@Nullable Condition<String> nodePrintCondition) {
DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode)root;
final Object userObject = defaultMutableTreeNode.getUserObject();
String nodeText;
if (userObject != null) {
nodeText = toString(userObject, null);
}
else {
nodeText = "null";
}
if (nodePrintCondition != null && !nodePrintCondition.value(nodeText)) return;
final StringBuilder buff = StringBuilderSpinAllocator.alloc();
try {
StringUtil.repeatSymbol(buff, ' ', level);
final boolean expanded = tree.isExpanded(new TreePath(defaultMutableTreeNode.getPath()));
if (!defaultMutableTreeNode.isLeaf()) {
buff.append(expanded ? "-" : "+");
}
final boolean selected = tree.getSelectionModel().isPathSelected(new TreePath(defaultMutableTreeNode.getPath()));
if (withSelection && selected) {
buff.append("[");
}
buff.append(nodeText);
if (withSelection && selected) {
buff.append("]");
}
strings.add(buff.toString());
int childCount = tree.getModel().getChildCount(root);
if (expanded) {
for (int i = 0; i < childCount; i++) {
printImpl(tree, tree.getModel().getChild(root, i), strings, level + 1, withSelection, nodePrintCondition);
}
}
}
finally {
StringBuilderSpinAllocator.dispose(buff);
}
}
public static void assertTreeEqual(JTree tree, @NonNls String expected) {
assertTreeEqual(tree, expected, false);
}
public static void assertTreeEqualIgnoringNodesOrder(JTree tree, @NonNls String expected) {
assertTreeEqualIgnoringNodesOrder(tree, expected, false);
}
public static void assertTreeEqual(JTree tree, String expected, boolean checkSelected) {
String treeStringPresentation = print(tree, checkSelected);
assertEquals(expected, treeStringPresentation);
}
public static void assertTreeEqualIgnoringNodesOrder(JTree tree, String expected, boolean checkSelected) {
final Collection<String> actualNodesPresentation = printAsList(tree, checkSelected, null);
final List<String> expectedNodes = StringUtil.split(expected, "\n");
UsefulTestCase.assertSameElements(actualNodesPresentation, expectedNodes);
}
@TestOnly
public static void waitForAlarm(final int delay) {
assert !ApplicationManager.getApplication().isWriteAccessAllowed(): "It's a bad idea to wait for an alarm under the write action. Somebody creates an alarm which requires read action and you are deadlocked.";
assert ApplicationManager.getApplication().isDispatchThread();
final AtomicBoolean invoked = new AtomicBoolean();
final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
alarm.addRequest(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
alarm.addRequest(new Runnable() {
@Override
public void run() {
invoked.set(true);
}
}, delay);
}
});
}
}, delay);
UIUtil.dispatchAllInvocationEvents();
boolean sleptAlready = false;
while (!invoked.get()) {
UIUtil.dispatchAllInvocationEvents();
TimeoutUtil.sleep(sleptAlready ? 10 : delay);
sleptAlready = true;
}
UIUtil.dispatchAllInvocationEvents();
}
@TestOnly
public static void dispatchAllInvocationEventsInIdeEventQueue() throws InterruptedException {
assert SwingUtilities.isEventDispatchThread() : Thread.currentThread();
final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
while (true) {
AWTEvent event = eventQueue.peekEvent();
if (event == null) break;
AWTEvent event1 = eventQueue.getNextEvent();
if (event1 instanceof InvocationEvent) {
IdeEventQueue.getInstance().dispatchEvent(event1);
}
}
}
private static Date raidDate(Bombed bombed) {
final Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, bombed.year());
instance.set(Calendar.MONTH, bombed.month());
instance.set(Calendar.DAY_OF_MONTH, bombed.day());
instance.set(Calendar.HOUR_OF_DAY, bombed.time());
instance.set(Calendar.MINUTE, 0);
return instance.getTime();
}
public static boolean bombExplodes(Bombed bombedAnnotation) {
Date now = new Date();
return now.after(raidDate(bombedAnnotation));
}
public static boolean isRotten(Bombed bomb) {
long bombRotPeriod = 30L * 24 * 60 * 60 * 1000; // month
return new Date().after(new Date(raidDate(bomb).getTime() + bombRotPeriod));
}
public static StringBuilder print(AbstractTreeStructure structure,
Object node,
int currentLevel,
@Nullable Comparator comparator,
int maxRowCount,
char paddingChar,
@Nullable Queryable.PrintInfo printInfo) {
StringBuilder buffer = StringBuilderSpinAllocator.alloc();
doPrint(buffer, currentLevel, node, structure, comparator, maxRowCount, 0, paddingChar, printInfo);
return buffer;
}
private static int doPrint(StringBuilder buffer,
int currentLevel,
Object node,
AbstractTreeStructure structure,
@Nullable Comparator comparator,
int maxRowCount,
int currentLine,
char paddingChar,
@Nullable Queryable.PrintInfo printInfo) {
if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine;
StringUtil.repeatSymbol(buffer, paddingChar, currentLevel);
buffer.append(toString(node, printInfo)).append("\n");
currentLine++;
Object[] children = structure.getChildElements(node);
if (comparator != null) {
ArrayList<?> list = new ArrayList<Object>(Arrays.asList(children));
@SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"}) Comparator<Object> c = comparator;
Collections.sort(list, c);
children = ArrayUtil.toObjectArray(list);
}
for (Object child : children) {
currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, printInfo);
}
return currentLine;
}
public static String print(Object[] objects) {
return print(Arrays.asList(objects));
}
public static String print(Collection c) {
StringBuilder result = new StringBuilder();
for (Iterator iterator = c.iterator(); iterator.hasNext();) {
Object each = iterator.next();
result.append(toString(each, null));
if (iterator.hasNext()) {
result.append("\n");
}
}
return result.toString();
}
public static String print(ListModel model) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < model.getSize(); i++) {
result.append(toString(model.getElementAt(i), null));
result.append("\n");
}
return result.toString();
}
public static String print(JTree tree) {
return print(tree, false);
}
public static void assertTreeStructureEquals(final AbstractTreeStructure treeStructure, final String expected) {
assertEquals(expected, print(treeStructure, treeStructure.getRootElement(), 0, null, -1, ' ', null).toString());
}
public static void invokeNamedAction(final String actionId) {
final AnAction action = ActionManager.getInstance().getAction(actionId);
assertNotNull(action);
final Presentation presentation = new Presentation();
@SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext();
final AnActionEvent event = new AnActionEvent(null, context, "", presentation, ActionManager.getInstance(), 0);
action.update(event);
Assert.assertTrue(presentation.isEnabled());
action.actionPerformed(event);
}
public static void assertTiming(final String message, final long expected, final long actual) {
if (COVERAGE_ENABLED_BUILD) return;
final long expectedOnMyMachine = Math.max(1, expected * Timings.MACHINE_TIMING / Timings.ETALON_TIMING);
final double acceptableChangeFactor = 1.1;
// Allow 10% more in case of test machine is busy.
String logMessage = message;
if (actual > expectedOnMyMachine) {
int percentage = (int)(100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine);
logMessage += ". Operation took " + percentage + "% longer than expected";
}
logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." +
" Actual: " + actual + "." +
" Expected on Standard machine: " + expected + ";" +
" Actual on Standard: " + actual * Timings.ETALON_TIMING / Timings.MACHINE_TIMING + ";" +
" Timings: CPU=" + Timings.CPU_TIMING +
", I/O=" + Timings.IO_TIMING + "." +
" (" + (int)(Timings.MACHINE_TIMING*1.0/Timings.ETALON_TIMING*100) + "% of the Standard)" +
".";
if (actual < expectedOnMyMachine) {
System.out.println(logMessage);
TeamCityLogger.info(logMessage);
}
else if (actual < expectedOnMyMachine * acceptableChangeFactor) {
TeamCityLogger.warning(logMessage, null);
}
else {
// throw AssertionFailedError to try one more time
throw new AssertionFailedError(logMessage);
}
}
/**
* example usage: startPerformanceTest("calculating pi",100, testRunnable).cpuBound().assertTiming();
*/
public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expected, @NotNull ThrowableRunnable test) {
return new TestInfo(test, expected,message);
}
// calculates average of the median values in the selected part of the array. E.g. for part=3 returns average in the middle third.
public static long averageAmongMedians(@NotNull long[] time, int part) {
assert part >= 1;
int n = time.length;
Arrays.sort(time);
long total = 0;
for (int i= n /2- n / part /2; i< n /2+ n / part /2; i++) {
total += time[i];
}
return total/(n / part);
}
public static boolean canRunTest(@NotNull Class testCaseClass) {
if (GraphicsEnvironment.isHeadless()) {
for (Class<?> clazz = testCaseClass; clazz != null; clazz = clazz.getSuperclass()) {
if (clazz.getAnnotation(SkipInHeadlessEnvironment.class) != null) {
System.out.println("Class '" + testCaseClass.getName() + "' is skipped because it requires working UI environment");
return false;
}
}
}
return true;
}
public static class TestInfo {
private final ThrowableRunnable test; // runnable to measure
private final int expected; // millis the test is expected to run
private ThrowableRunnable setup; // to run before each test
private boolean usesAllCPUCores; // true if the test runs faster on multi-core
private int attempts = 4; // number of retries if performance failed
private final String message; // to print on fail
private boolean adjustForIO = true; // true if test uses IO, timings need to be re-calibrated according to this agent disk performance
private boolean adjustForCPU = true; // true if test uses CPU, timings need to be re-calibrated according to this agent CPU speed
private TestInfo(@NotNull ThrowableRunnable test, int expected, String message) {
this.test = test;
this.expected = expected;
assert expected > 0 : "Expected must be > 0. Was: "+ expected;
this.message = message;
}
public TestInfo setup(@NotNull ThrowableRunnable setup) { assert this.setup==null; this.setup = setup; return this; }
public TestInfo usesAllCPUCores() { assert adjustForCPU : "This test configured to be io-bound, it cannot use all cores"; usesAllCPUCores = true; return this; }
public TestInfo cpuBound() { adjustForIO = false; adjustForCPU = true; return this; }
public TestInfo ioBound() { adjustForIO = true; adjustForCPU = false; return this; }
public TestInfo attempts(int attempts) { this.attempts = attempts; return this; }
public void assertTiming() {
assert expected != 0 : "Must call .expect() before run test";
if (COVERAGE_ENABLED_BUILD) return;
while (true) {
attempts--;
long start;
try {
if (setup != null) setup.run();
start = System.currentTimeMillis();
test.run();
}
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
long finish = System.currentTimeMillis();
long duration = finish - start;
int expectedOnMyMachine = expected;
if (adjustForCPU) {
expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.CPU_TIMING, Timings.ETALON_CPU_TIMING);
expectedOnMyMachine = usesAllCPUCores ? expectedOnMyMachine * 8 / JobSchedulerImpl.CORES_COUNT : expectedOnMyMachine;
}
if (adjustForIO) {
expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.IO_TIMING, Timings.ETALON_IO_TIMING);
}
final double acceptableChangeFactor = 1.1;
// Allow 10% more in case of test machine is busy.
String logMessage = message;
if (duration > expectedOnMyMachine) {
int percentage = (int)(100.0 * (duration - expectedOnMyMachine) / expectedOnMyMachine);
logMessage += ". (" + percentage + "% longer).";
}
logMessage += " Expected: " + expectedOnMyMachine + "." +
" Actual: " + duration + "." + Timings.getStatistics() ;
if (duration < expectedOnMyMachine) {
int percentage = (int)(100.0 * (expectedOnMyMachine - duration) / expectedOnMyMachine);
logMessage = "(" + percentage + "% faster). " + logMessage;
TeamCityLogger.info(logMessage);
System.out.println("SUCCESS: "+logMessage);
}
else if (duration < expectedOnMyMachine * acceptableChangeFactor) {
TeamCityLogger.warning(logMessage, null);
System.out.println("WARNING: " + logMessage);
}
else {
// try one more time
if (attempts == 0) {
//try {
// Object result = Class.forName("com.intellij.util.ProfilingUtil").getMethod("captureCPUSnapshot").invoke(null);
// System.err.println("CPU snapshot captured in '"+result+"'");
//}
//catch (Exception e) {
//}
throw new AssertionFailedError(logMessage);
}
System.gc();
System.gc();
System.gc();
String s = "Another epic fail (remaining attempts: " + attempts + "): " + logMessage;
TeamCityLogger.warning(s, null);
System.err.println(s);
//if (attempts == 1) {
// try {
// Class.forName("com.intellij.util.ProfilingUtil").getMethod("startCPUProfiling").invoke(null);
// }
// catch (Exception e) {
// }
//}
continue;
}
break;
}
}
private static int adjust(int expectedOnMyMachine, long thisTiming, long ethanolTiming) {
// most of our algorithms are quadratic. sad but true.
double speed = 1.0 * thisTiming / ethanolTiming;
double delta = speed < 1
? 0.9 + Math.pow(speed - 0.7, 2)
: 0.45 + Math.pow(speed - 0.25, 2);
expectedOnMyMachine *= delta;
return expectedOnMyMachine;
}
}
public static void assertTiming(String message, long expected, @NotNull Runnable actionToMeasure) {
assertTiming(message, expected, 4, actionToMeasure);
}
public static long measure(@NotNull Runnable actionToMeasure) {
long start = System.currentTimeMillis();
actionToMeasure.run();
long finish = System.currentTimeMillis();
return finish - start;
}
public static void assertTiming(String message, long expected, int attempts, @NotNull Runnable actionToMeasure) {
while (true) {
attempts--;
long duration = measure(actionToMeasure);
try {
assertTiming(message, expected, duration);
break;
}
catch (AssertionFailedError e) {
if (attempts == 0) throw e;
System.gc();
System.gc();
System.gc();
String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage();
TeamCityLogger.warning(s, null);
System.err.println(s);
}
}
}
private static HashMap<String, VirtualFile> buildNameToFileMap(VirtualFile[] files, @Nullable VirtualFileFilter filter) {
HashMap<String, VirtualFile> map = new HashMap<String, VirtualFile>();
for (VirtualFile file : files) {
if (filter != null && !filter.accept(file)) continue;
map.put(file.getName(), file);
}
return map;
}
public static void assertDirectoriesEqual(VirtualFile dirAfter, VirtualFile dirBefore, @Nullable VirtualFileFilter fileFilter) throws IOException {
FileDocumentManager.getInstance().saveAllDocuments();
dirAfter.getChildren();
dirAfter.refresh(false, false);
VirtualFile[] childrenAfter = dirAfter.getChildren();
if (dirAfter.isInLocalFileSystem()) {
File[] ioAfter = new File(dirAfter.getPath()).listFiles();
shallowCompare(childrenAfter, ioAfter);
}
VirtualFile[] childrenBefore = dirBefore.getChildren();
if (dirBefore.isInLocalFileSystem()) {
File[] ioBefore = new File(dirBefore.getPath()).listFiles();
shallowCompare(childrenBefore, ioBefore);
}
HashMap<String, VirtualFile> mapAfter = buildNameToFileMap(childrenAfter, fileFilter);
HashMap<String, VirtualFile> mapBefore = buildNameToFileMap(childrenBefore, fileFilter);
Set<String> keySetAfter = mapAfter.keySet();
Set<String> keySetBefore = mapBefore.keySet();
assertEquals(keySetAfter, keySetBefore);
for (String name : keySetAfter) {
VirtualFile fileAfter = mapAfter.get(name);
VirtualFile fileBefore = mapBefore.get(name);
if (fileAfter.isDirectory()) {
assertDirectoriesEqual(fileAfter, fileBefore, fileFilter);
}
else {
assertFilesEqual(fileAfter, fileBefore);
}
}
}
private static void shallowCompare(final VirtualFile[] vfs, final File[] io) {
List<String> vfsPaths = new ArrayList<String>();
for (VirtualFile file : vfs) {
vfsPaths.add(file.getPath());
}
List<String> ioPaths = new ArrayList<String>();
for (File file : io) {
ioPaths.add(file.getPath().replace(File.separatorChar, '/'));
}
assertEquals(sortAndJoin(vfsPaths), sortAndJoin(ioPaths));
}
private static String sortAndJoin(List<String> strings) {
Collections.sort(strings);
StringBuilder buf = new StringBuilder();
for (String string : strings) {
buf.append(string);
buf.append('\n');
}
return buf.toString();
}
public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore) throws IOException {
try {
assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore));
}
catch (IOException e) {
FileDocumentManager manager = FileDocumentManager.getInstance();
Document docBefore = manager.getDocument(fileBefore);
boolean canLoadBeforeText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
String textB = docBefore != null
? docBefore.getText()
: !canLoadBeforeText
? null
: LoadTextUtil.getTextByBinaryPresentation(fileBefore.contentsToByteArray(false), fileBefore).toString();
Document docAfter = manager.getDocument(fileAfter);
boolean canLoadAfterText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
String textA = docAfter != null
? docAfter.getText()
: !canLoadAfterText
? null
: LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString();
if (textA != null && textB != null) {
assertEquals(fileAfter.getPath(), textA, textB);
}
else {
Assert.assertArrayEquals(fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray());
}
}
}
public static void assertJarFilesEqual(File file1, File file2) throws IOException {
final File tempDirectory1;
final File tempDirectory2;
final JarFile jarFile1 = new JarFile(file1);
try {
final JarFile jarFile2 = new JarFile(file2);
try {
tempDirectory1 = PlatformTestCase.createTempDir("tmp1");
tempDirectory2 = PlatformTestCase.createTempDir("tmp2");
ZipUtil.extract(jarFile1, tempDirectory1, CVS_FILE_FILTER);
ZipUtil.extract(jarFile2, tempDirectory2, CVS_FILE_FILTER);
}
finally {
jarFile2.close();
}
}
finally {
jarFile1.close();
}
final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1);
assertNotNull(tempDirectory1.toString(), dirAfter);
final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2);
assertNotNull(tempDirectory2.toString(), dirBefore);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
dirAfter.refresh(false, true);
dirBefore.refresh(false, true);
}
});
assertDirectoriesEqual(dirAfter, dirBefore, CVS_FILE_FILTER);
}
public static void assertElementsEqual(final Element expected, final Element actual) throws IOException {
if (!JDOMUtil.areElementsEqual(expected, actual)) {
junit.framework.Assert.assertEquals(printElement(expected), printElement(actual));
}
}
public static String printElement(final Element element) throws IOException {
final StringWriter writer = new StringWriter();
JDOMUtil.writeElement(element, writer, "\n");
return writer.getBuffer().toString();
}
public static class CvsVirtualFileFilter implements VirtualFileFilter, FilenameFilter {
@Override
public boolean accept(VirtualFile file) {
return !file.isDirectory() || !"CVS".equals(file.getName());
}
@Override
public boolean accept(File dir, String name) {
return !name.contains("CVS");
}
}
public static String getCommunityPath() {
final String homePath = PathManager.getHomePath();
if (new File(homePath, "community").exists()) {
return homePath + File.separatorChar + "community";
}
return homePath;
}
public static Comparator<AbstractTreeNode> createComparator(final Queryable.PrintInfo printInfo) {
return new Comparator<AbstractTreeNode>() {
@Override
public int compare(final AbstractTreeNode o1, final AbstractTreeNode o2) {
String displayText1 = o1.toTestString(printInfo);
String displayText2 = o2.toTestString(printInfo);
return Comparing.compare(displayText1, displayText2);
}
};
}
@NotNull
public static <T> T notNull(@Nullable T t) {
assertNotNull(t);
return t;
}
}
| Fix compilation
| platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java | Fix compilation |
|
Java | apache-2.0 | c676d8e0aa51781bb7d4e408561118ee74e3ffc1 | 0 | orekyuu/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,slisson/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,xfournet/intellij-community,jagguli/intellij-community,semonte/intellij-community,retomerz/intellij-community,supersven/intellij-community,robovm/robovm-studio,holmes/intellij-community,amith01994/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,da1z/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,kool79/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,supersven/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,amith01994/intellij-community,holmes/intellij-community,ahb0327/intellij-community,samthor/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,izonder/intellij-community,samthor/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,apixandru/intellij-community,izonder/intellij-community,robovm/robovm-studio,xfournet/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,supersven/intellij-community,gnuhub/intellij-community,slisson/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,amith01994/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,signed/intellij-community,gnuhub/intellij-community,semonte/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,caot/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,signed/intellij-community,ryano144/intellij-community,clumsy/intellij-community,slisson/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,signed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,retomerz/intellij-community,jagguli/intellij-community,retomerz/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,da1z/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,signed/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,clumsy/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,kool79/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,semonte/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,da1z/intellij-community,izonder/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,slisson/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,blademainer/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,allotria/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,hurricup/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,holmes/intellij-community,ibinti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,jagguli/intellij-community,vladmm/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,caot/intellij-community,caot/intellij-community,apixandru/intellij-community,semonte/intellij-community,caot/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,da1z/intellij-community,akosyakov/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,dslomov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,amith01994/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,slisson/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,jagguli/intellij-community,da1z/intellij-community,fitermay/intellij-community,vladmm/intellij-community,supersven/intellij-community,retomerz/intellij-community,kdwink/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,jagguli/intellij-community,xfournet/intellij-community,clumsy/intellij-community,robovm/robovm-studio,clumsy/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,semonte/intellij-community,vladmm/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ryano144/intellij-community,kool79/intellij-community,caot/intellij-community,izonder/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,fitermay/intellij-community,allotria/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,supersven/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,signed/intellij-community,izonder/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,kdwink/intellij-community,caot/intellij-community,signed/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,blademainer/intellij-community,Distrotech/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kool79/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ryano144/intellij-community,vladmm/intellij-community,dslomov/intellij-community,dslomov/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fitermay/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,adedayo/intellij-community,FHannes/intellij-community,kool79/intellij-community,samthor/intellij-community,caot/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,jagguli/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ibinti/intellij-community,supersven/intellij-community,da1z/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,allotria/intellij-community,petteyg/intellij-community,semonte/intellij-community,slisson/intellij-community,Lekanich/intellij-community,signed/intellij-community,clumsy/intellij-community,dslomov/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,izonder/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,semonte/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,signed/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,allotria/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,blademainer/intellij-community,vladmm/intellij-community,signed/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,semonte/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,signed/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,samthor/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,Distrotech/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,petteyg/intellij-community,fitermay/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,fitermay/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,caot/intellij-community,da1z/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,kdwink/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,izonder/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,slisson/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,holmes/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,allotria/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,allotria/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,allotria/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,samthor/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,supersven/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,holmes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,hurricup/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,caot/intellij-community,slisson/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import com.intellij.ide.DataManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl;
import com.intellij.openapi.wm.impl.IdeMenuBar;
import com.intellij.ui.AppUIUtil;
import com.intellij.ui.BalloonLayout;
import com.intellij.ui.FocusTrackback;
import com.intellij.util.ImageLoader;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Map;
public class FrameWrapper implements Disposable, DataProvider {
private String myDimensionKey = null;
private JComponent myComponent = null;
private JComponent myPreferedFocus = null;
private String myTitle = "";
private Image myImage = ImageLoader.loadFromResource(ApplicationInfoImpl.getShadowInstance().getIconUrl());
private boolean myCloseOnEsc = false;
private Window myFrame;
private final Map<String, Object> myDatas = new HashMap<String, Object>();
private Project myProject;
private final ProjectManagerListener myProjectListener = new MyProjectManagerListener();
private FocusTrackback myFocusTrackback;
private FocusWatcher myFocusWatcher;
private ActionCallback myFocusedCallback;
private boolean myDisposed;
protected StatusBar myStatusBar;
private boolean myShown;
private boolean myIsDialog;
private boolean myImageWasChanged;
//Skip restoration of MAXIMIZED_BOTH_PROPERTY
private static final boolean WORKAROUND_FOR_JDK_8007219 = SystemInfo.isMac && SystemInfo.isOracleJvm;
public FrameWrapper(Project project) {
this(project, null);
}
public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey) {
this(project, dimensionServiceKey, false);
}
public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey, boolean isDialog) {
myDimensionKey = dimensionServiceKey;
myIsDialog = isDialog;
if (project != null) {
setProject(project);
}
}
public void setDimensionKey(String dimensionKey) {
myDimensionKey = dimensionKey;
}
public void setData(String dataId, Object data) {
myDatas.put(dataId, data);
}
public void setProject(@NotNull final Project project) {
myProject = project;
setData(CommonDataKeys.PROJECT.getName(), project);
ProjectManager.getInstance().addProjectManagerListener(project, myProjectListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
ProjectManager.getInstance().removeProjectManagerListener(project, myProjectListener);
}
});
}
public void show() {
show(true);
}
public void show(boolean restoreBounds) {
myFocusedCallback = new ActionCallback();
if (myProject != null) {
IdeFocusManager.getInstance(myProject).typeAheadUntil(myFocusedCallback);
}
final Window frame = getFrame();
if (myStatusBar != null) {
myStatusBar.install((IdeFrame)frame);
}
myFocusTrackback = new FocusTrackback(this, IdeFocusManager.findInstance().getFocusOwner(), true);
if (frame instanceof JFrame) {
((JFrame)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
} else {
((JDialog)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
final WindowAdapter focusListener = new WindowAdapter() {
public void windowOpened(WindowEvent e) {
IdeFocusManager fm = IdeFocusManager.getInstance(myProject);
JComponent toFocus = myPreferedFocus;
if (toFocus == null) {
toFocus = fm.getFocusTargetFor(myComponent);
}
if (toFocus != null) {
fm.requestFocus(toFocus, true).notify(myFocusedCallback);
} else {
myFocusedCallback.setRejected();
}
}
};
frame.addWindowListener(focusListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
frame.removeWindowListener(focusListener);
}
});
if (myCloseOnEsc) addCloseOnEsc((RootPaneContainer)frame);
((RootPaneContainer)frame).getContentPane().add(myComponent, BorderLayout.CENTER);
if (frame instanceof JFrame) {
((JFrame)frame).setTitle(myTitle);
} else {
((JDialog)frame).setTitle(myTitle);
}
if (myImageWasChanged) {
frame.setIconImage(myImage);
}
else {
AppUIUtil.updateWindowIcon(myFrame);
}
if (restoreBounds) {
loadFrameState();
}
myFocusWatcher = new FocusWatcher() {
protected void focusLostImpl(final FocusEvent e) {
myFocusTrackback.consume();
}
};
myFocusWatcher.install(myComponent);
myShown = true;
frame.setVisible(true);
if (UIUtil.isUnderAlloyLookAndFeel() && frame instanceof JFrame) {
//please ask [kb] before remove it
((JFrame)frame).setMaximizedBounds(null);
}
}
public void close() {
Disposer.dispose(this);
}
public void dispose() {
if (isDisposed()) return;
Window frame = getFrame();
final JRootPane rootPane = ((RootPaneContainer)frame).getRootPane();
if (rootPane != null) {
DialogWrapper.unregisterKeyboardActions(rootPane);
}
frame.setVisible(false);
if (frame instanceof JFrame) {
FocusTrackback.release((JFrame)frame);
}
if (myStatusBar != null) {
Disposer.dispose(myStatusBar);
myStatusBar = null;
}
myDisposed = true;
}
public boolean isDisposed() {
return myDisposed;
}
private void addCloseOnEsc(final RootPaneContainer frame) {
new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
MenuElement[] selectedPath = menuSelectionManager.getSelectedPath();
if (selectedPath.length > 0) { // hide popup menu if any
menuSelectionManager.clearSelectedPath();
} else {
// if you remove this line problems will start happen on Mac OS X
// 2 projects opened, call Cmd+D on the second opened project and then Esc.
// Weird situation: 2nd IdeFrame will be active, but focus will be somewhere inside the 1st IdeFrame
// App is unusable until Cmd+Tab, Cmd+tab
FrameWrapper.this.myFrame.setVisible(false);
close();
}
}
}.registerCustomShortcutSet(CommonShortcuts.ESCAPE, myComponent, this);
}
public Window getFrame() {
assert !myDisposed : "Already disposed!";
if (myFrame == null) {
final IdeFrame parent = WindowManager.getInstance().getIdeFrame(myProject);
myFrame = myIsDialog ? createJDialog(parent) : createJFrame(parent);
}
return myFrame;
}
protected JFrame createJFrame(IdeFrame parent) {
return new MyJFrame(parent) {
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return FrameWrapper.this.getNorthExtension(key);
}
};
}
protected JDialog createJDialog(IdeFrame parent) {
return new MyJDialog(parent);
}
protected IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public Object getData(@NonNls String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
return myProject;
}
return null;
}
public void setComponent(JComponent component) {
myComponent = component;
}
public void setPreferredFocusedComponent(JComponent preferedFocus) {
myPreferedFocus = preferedFocus;
}
public void closeOnEsc() {
myCloseOnEsc = true;
}
public void setImage(Image image) {
myImageWasChanged = true;
myImage = image;
}
protected void loadFrameState() {
final Window frame = getFrame();
final Point location;
final Dimension size;
final int extendedState;
DimensionService dimensionService = DimensionService.getInstance();
if (myDimensionKey == null || dimensionService == null) {
location = null;
size = null;
extendedState = -1;
}
else {
location = dimensionService.getLocation(myDimensionKey);
size = dimensionService.getSize(myDimensionKey);
extendedState = dimensionService.getExtendedState(myDimensionKey);
}
if (size != null && location != null) {
frame.setLocation(location);
frame.setSize(size);
((RootPaneContainer)frame).getRootPane().revalidate();
}
else {
final IdeFrame ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(myProject);
if (ideFrame != null) {
frame.pack();
frame.setBounds(ideFrame.suggestChildFrameBounds());
}
}
if (!WORKAROUND_FOR_JDK_8007219 && extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) {
((JFrame)frame).setExtendedState(extendedState);
}
}
private static void saveFrameState(String dimensionKey, Component frame) {
DimensionService dimensionService = DimensionService.getInstance();
if (dimensionKey == null || dimensionService == null) return;
dimensionService.setLocation(dimensionKey, frame.getLocation());
dimensionService.setSize(dimensionKey, frame.getSize());
if (frame instanceof JFrame) {
dimensionService.setExtendedState(dimensionKey, ((JFrame)frame).getExtendedState());
}
}
public void setTitle(String title) {
myTitle = title;
}
public void addDisposable(@NotNull Disposable disposable) {
Disposer.register(this, disposable);
}
protected void setStatusBar(StatusBar statusBar) {
if (myStatusBar != null) {
Disposer.dispose(myStatusBar);
}
myStatusBar = statusBar;
}
private class MyJFrame extends JFrame implements DataProvider, IdeFrame.Child {
private boolean myDisposing;
private final IdeFrame myParent;
private String myFrameTitle;
private String myFileTitle;
private File myFile;
private MyJFrame(IdeFrame parent) throws HeadlessException {
myParent = parent;
setGlassPane(new IdeGlassPaneImpl(getRootPane()));
if (SystemInfo.isMac) {
setJMenuBar(new IdeMenuBar(ActionManagerEx.getInstanceEx(), DataManager.getInstance()));
}
MouseGestureManager.getInstance().add(this);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt());
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
@Override
public JComponent getComponent() {
return getRootPane();
}
@Override
public StatusBar getStatusBar() {
return myStatusBar != null ? myStatusBar : myParent.getStatusBar();
}
@Override
public Rectangle suggestChildFrameBounds() {
return myParent.suggestChildFrameBounds();
}
@Override
public Project getProject() {
return myParent.getProject();
}
@Override
public void setFrameTitle(String title) {
myFrameTitle = title;
updateTitle();
}
@Override
public void setFileTitle(String fileTitle, File ioFile) {
myFileTitle = fileTitle;
myFile = ioFile;
updateTitle();
}
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public BalloonLayout getBalloonLayout() {
return null;
}
private void updateTitle() {
IdeFrameImpl.updateTitle(this, myFrameTitle, myFileTitle, myFile);
}
@Override
public IdeFrame getParentFrame() {
return myParent;
}
public void dispose() {
if (myDisposing) return;
myDisposing = true;
MouseGestureManager.getInstance().remove(this);
if (myShown) {
saveFrameState(myDimensionKey, this);
}
Disposer.dispose(FrameWrapper.this);
myDatas.clear();
myProject = null;
myPreferedFocus = null;
if (myFocusTrackback != null) {
myFocusTrackback.restoreFocus();
}
if (myComponent != null && myFocusWatcher != null) {
myFocusWatcher.deinstall(myComponent);
}
myFocusWatcher = null;
myFocusedCallback = null;
super.dispose();
}
public Object getData(String dataId) {
if (IdeFrame.KEY.getName().equals(dataId)) {
return this;
}
Object data = FrameWrapper.this.getData(dataId);
return data != null ? data : myDatas.get(dataId);
}
@Override
public void paint(Graphics g) {
UIUtil.applyRenderingHints(g);
super.paint(g);
}
}
private class MyJDialog extends JDialog implements DataProvider, IdeFrame.Child {
private boolean myDisposing;
private final IdeFrame myParent;
private MyJDialog(IdeFrame parent) throws HeadlessException {
super((JFrame)parent);
myParent = parent;
setGlassPane(new IdeGlassPaneImpl(getRootPane()));
getRootPane().putClientProperty("Window.style", "small");
setBackground(UIUtil.getPanelBackground());
MouseGestureManager.getInstance().add(this);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt());
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
@Override
public JComponent getComponent() {
return getRootPane();
}
@Override
public StatusBar getStatusBar() {
return null;
}
@Nullable
@Override
public BalloonLayout getBalloonLayout() {
return null;
}
@Override
public Rectangle suggestChildFrameBounds() {
return myParent.suggestChildFrameBounds();
}
@Override
public Project getProject() {
return myParent.getProject();
}
@Override
public void setFrameTitle(String title) {
setTitle(title);
}
@Override
public void setFileTitle(String fileTitle, File ioFile) {
setTitle(fileTitle);
}
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public IdeFrame getParentFrame() {
return myParent;
}
public void dispose() {
if (myDisposing) return;
myDisposing = true;
MouseGestureManager.getInstance().remove(this);
if (myShown) {
saveFrameState(myDimensionKey, this);
}
Disposer.dispose(FrameWrapper.this);
myDatas.clear();
myProject = null;
myPreferedFocus = null;
if (myFocusTrackback != null) {
myFocusTrackback.restoreFocus();
}
if (myComponent != null && myFocusWatcher != null) {
myFocusWatcher.deinstall(myComponent);
}
myFocusWatcher = null;
myFocusedCallback = null;
super.dispose();
}
public Object getData(String dataId) {
if (IdeFrame.KEY.getName().equals(dataId)) {
return this;
}
Object data = FrameWrapper.this.getData(dataId);
return data != null ? data : myDatas.get(dataId);
}
@Override
public void paint(Graphics g) {
UIUtil.applyRenderingHints(g);
super.paint(g);
}
}
public void setLocation(Point location) {
getFrame().setLocation(location);
}
public void setSize(Dimension size) {
getFrame().setSize(size);
}
private class MyProjectManagerListener extends ProjectManagerAdapter {
public void projectClosing(Project project) {
if (project == myProject) {
close();
}
}
}
}
| platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import com.intellij.ide.DataManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl;
import com.intellij.openapi.wm.impl.IdeMenuBar;
import com.intellij.ui.AppUIUtil;
import com.intellij.ui.BalloonLayout;
import com.intellij.ui.FocusTrackback;
import com.intellij.util.ImageLoader;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.Map;
public class FrameWrapper implements Disposable, DataProvider {
private String myDimensionKey = null;
private JComponent myComponent = null;
private JComponent myPreferedFocus = null;
private String myTitle = "";
private Image myImage = ImageLoader.loadFromResource(ApplicationInfoImpl.getShadowInstance().getIconUrl());
private boolean myCloseOnEsc = false;
private Window myFrame;
private final Map<String, Object> myDatas = new HashMap<String, Object>();
private Project myProject;
private final ProjectManagerListener myProjectListener = new MyProjectManagerListener();
private FocusTrackback myFocusTrackback;
private FocusWatcher myFocusWatcher;
private ActionCallback myFocusedCallback;
private boolean myDisposed;
protected StatusBar myStatusBar;
private boolean myShown;
private boolean myIsDialog;
private boolean myImageWasChanged;
//Skip restoration of MAXIMIZED_BOTH_PROPERTY
private static final boolean WORKAROUND_FOR_JDK_8007219 = SystemInfo.isMac && SystemInfo.isOracleJvm;
public FrameWrapper(Project project) {
this(project, null);
}
public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey) {
this(project, dimensionServiceKey, false);
}
public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey, boolean isDialog) {
myDimensionKey = dimensionServiceKey;
myIsDialog = isDialog;
if (project != null) {
setProject(project);
}
}
public void setDimensionKey(String dimensionKey) {
myDimensionKey = dimensionKey;
}
public void setData(String dataId, Object data) {
myDatas.put(dataId, data);
}
public void setProject(@NotNull final Project project) {
myProject = project;
setData(CommonDataKeys.PROJECT.getName(), project);
ProjectManager.getInstance().addProjectManagerListener(project, myProjectListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
ProjectManager.getInstance().removeProjectManagerListener(project, myProjectListener);
}
});
}
public void show() {
show(true);
}
public void show(boolean restoreBounds) {
myFocusedCallback = new ActionCallback();
if (myProject != null) {
IdeFocusManager.getInstance(myProject).typeAheadUntil(myFocusedCallback);
}
final Window frame = getFrame();
if (myStatusBar != null) {
myStatusBar.install((IdeFrame)frame);
}
myFocusTrackback = new FocusTrackback(this, IdeFocusManager.findInstance().getFocusOwner(), true);
if (frame instanceof JFrame) {
((JFrame)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
} else {
((JDialog)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
final WindowAdapter focusListener = new WindowAdapter() {
public void windowOpened(WindowEvent e) {
IdeFocusManager fm = IdeFocusManager.getInstance(myProject);
JComponent toFocus = myPreferedFocus;
if (toFocus == null) {
toFocus = fm.getFocusTargetFor(myComponent);
}
if (toFocus != null) {
fm.requestFocus(toFocus, true).notify(myFocusedCallback);
} else {
myFocusedCallback.setRejected();
}
}
};
frame.addWindowListener(focusListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
frame.removeWindowListener(focusListener);
}
});
if (myCloseOnEsc) addCloseOnEsc((RootPaneContainer)frame);
((RootPaneContainer)frame).getContentPane().add(myComponent, BorderLayout.CENTER);
if (frame instanceof JFrame) {
((JFrame)frame).setTitle(myTitle);
} else {
((JDialog)frame).setTitle(myTitle);
}
if (myImageWasChanged) {
frame.setIconImage(myImage);
}
else {
AppUIUtil.updateWindowIcon(myFrame);
}
if (restoreBounds) {
loadFrameState();
}
myFocusWatcher = new FocusWatcher() {
protected void focusLostImpl(final FocusEvent e) {
myFocusTrackback.consume();
}
};
myFocusWatcher.install(myComponent);
myShown = true;
frame.setVisible(true);
if (UIUtil.isUnderAlloyLookAndFeel() && frame instanceof JFrame) {
//please ask [kb] before remove it
((JFrame)frame).setMaximizedBounds(null);
}
}
public void close() {
Disposer.dispose(this);
}
public void dispose() {
if (isDisposed()) return;
Window frame = getFrame();
final JRootPane rootPane = ((RootPaneContainer)frame).getRootPane();
if (rootPane != null) {
DialogWrapper.unregisterKeyboardActions(rootPane);
}
frame.setVisible(false);
frame.dispose();
if (frame instanceof JFrame) {
FocusTrackback.release((JFrame)frame);
}
if (myStatusBar != null) {
Disposer.dispose(myStatusBar);
myStatusBar = null;
}
myDisposed = true;
}
public boolean isDisposed() {
return myDisposed;
}
private void addCloseOnEsc(final RootPaneContainer frame) {
frame.getRootPane().registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
MenuElement[] selectedPath = menuSelectionManager.getSelectedPath();
if (selectedPath.length > 0) { // hide popup menu if any
menuSelectionManager.clearSelectedPath();
}
else {
close();
}
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW
);
}
public Window getFrame() {
assert !myDisposed : "Already disposed!";
if (myFrame == null) {
final IdeFrame parent = WindowManager.getInstance().getIdeFrame(myProject);
myFrame = myIsDialog ? createJDialog(parent) : createJFrame(parent);
}
return myFrame;
}
protected JFrame createJFrame(IdeFrame parent) {
return new MyJFrame(parent) {
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return FrameWrapper.this.getNorthExtension(key);
}
};
}
protected JDialog createJDialog(IdeFrame parent) {
return new MyJDialog(parent);
}
protected IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public Object getData(@NonNls String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
return myProject;
}
return null;
}
public void setComponent(JComponent component) {
myComponent = component;
}
public void setPreferredFocusedComponent(JComponent preferedFocus) {
myPreferedFocus = preferedFocus;
}
public void closeOnEsc() {
myCloseOnEsc = true;
}
public void setImage(Image image) {
myImageWasChanged = true;
myImage = image;
}
protected void loadFrameState() {
final Window frame = getFrame();
final Point location;
final Dimension size;
final int extendedState;
DimensionService dimensionService = DimensionService.getInstance();
if (myDimensionKey == null || dimensionService == null) {
location = null;
size = null;
extendedState = -1;
}
else {
location = dimensionService.getLocation(myDimensionKey);
size = dimensionService.getSize(myDimensionKey);
extendedState = dimensionService.getExtendedState(myDimensionKey);
}
if (size != null && location != null) {
frame.setLocation(location);
frame.setSize(size);
((RootPaneContainer)frame).getRootPane().revalidate();
}
else {
final IdeFrame ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(myProject);
if (ideFrame != null) {
frame.pack();
frame.setBounds(ideFrame.suggestChildFrameBounds());
}
}
if (!WORKAROUND_FOR_JDK_8007219 && extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) {
((JFrame)frame).setExtendedState(extendedState);
}
}
private static void saveFrameState(String dimensionKey, Component frame) {
DimensionService dimensionService = DimensionService.getInstance();
if (dimensionKey == null || dimensionService == null) return;
dimensionService.setLocation(dimensionKey, frame.getLocation());
dimensionService.setSize(dimensionKey, frame.getSize());
if (frame instanceof JFrame) {
dimensionService.setExtendedState(dimensionKey, ((JFrame)frame).getExtendedState());
}
}
public void setTitle(String title) {
myTitle = title;
}
public void addDisposable(@NotNull Disposable disposable) {
Disposer.register(this, disposable);
}
protected void setStatusBar(StatusBar statusBar) {
if (myStatusBar != null) {
Disposer.dispose(myStatusBar);
}
myStatusBar = statusBar;
}
private class MyJFrame extends JFrame implements DataProvider, IdeFrame.Child {
private boolean myDisposing;
private final IdeFrame myParent;
private String myFrameTitle;
private String myFileTitle;
private File myFile;
private MyJFrame(IdeFrame parent) throws HeadlessException {
myParent = parent;
setGlassPane(new IdeGlassPaneImpl(getRootPane()));
if (SystemInfo.isMac) {
setJMenuBar(new IdeMenuBar(ActionManagerEx.getInstanceEx(), DataManager.getInstance()));
}
MouseGestureManager.getInstance().add(this);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt());
}
@Override
public JComponent getComponent() {
return getRootPane();
}
@Override
public StatusBar getStatusBar() {
return myStatusBar != null ? myStatusBar : myParent.getStatusBar();
}
@Override
public Rectangle suggestChildFrameBounds() {
return myParent.suggestChildFrameBounds();
}
@Override
public Project getProject() {
return myParent.getProject();
}
@Override
public void setFrameTitle(String title) {
myFrameTitle = title;
updateTitle();
}
@Override
public void setFileTitle(String fileTitle, File ioFile) {
myFileTitle = fileTitle;
myFile = ioFile;
updateTitle();
}
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public BalloonLayout getBalloonLayout() {
return null;
}
private void updateTitle() {
IdeFrameImpl.updateTitle(this, myFrameTitle, myFileTitle, myFile);
}
@Override
public IdeFrame getParentFrame() {
return myParent;
}
public void dispose() {
if (myDisposing) return;
myDisposing = true;
MouseGestureManager.getInstance().remove(this);
if (myShown) {
saveFrameState(myDimensionKey, this);
}
Disposer.dispose(FrameWrapper.this);
myDatas.clear();
myProject = null;
myPreferedFocus = null;
if (myFocusTrackback != null) {
myFocusTrackback.restoreFocus();
}
if (myComponent != null && myFocusWatcher != null) {
myFocusWatcher.deinstall(myComponent);
}
myFocusWatcher = null;
myFocusedCallback = null;
super.dispose();
}
public Object getData(String dataId) {
if (IdeFrame.KEY.getName().equals(dataId)) {
return this;
}
Object data = FrameWrapper.this.getData(dataId);
return data != null ? data : myDatas.get(dataId);
}
@Override
public void paint(Graphics g) {
UIUtil.applyRenderingHints(g);
super.paint(g);
}
}
private class MyJDialog extends JDialog implements DataProvider, IdeFrame.Child {
private boolean myDisposing;
private final IdeFrame myParent;
private MyJDialog(IdeFrame parent) throws HeadlessException {
super((JFrame)parent);
myParent = parent;
setGlassPane(new IdeGlassPaneImpl(getRootPane()));
getRootPane().putClientProperty("Window.style", "small");
setBackground(UIUtil.getPanelBackground());
MouseGestureManager.getInstance().add(this);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt());
}
@Override
public JComponent getComponent() {
return getRootPane();
}
@Override
public StatusBar getStatusBar() {
return null;
}
@Nullable
@Override
public BalloonLayout getBalloonLayout() {
return null;
}
@Override
public Rectangle suggestChildFrameBounds() {
return myParent.suggestChildFrameBounds();
}
@Override
public Project getProject() {
return myParent.getProject();
}
@Override
public void setFrameTitle(String title) {
setTitle(title);
}
@Override
public void setFileTitle(String fileTitle, File ioFile) {
setTitle(fileTitle);
}
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return null;
}
@Override
public IdeFrame getParentFrame() {
return myParent;
}
public void dispose() {
if (myDisposing) return;
myDisposing = true;
MouseGestureManager.getInstance().remove(this);
if (myShown) {
saveFrameState(myDimensionKey, this);
}
Disposer.dispose(FrameWrapper.this);
myDatas.clear();
myProject = null;
myPreferedFocus = null;
if (myFocusTrackback != null) {
myFocusTrackback.restoreFocus();
}
if (myComponent != null && myFocusWatcher != null) {
myFocusWatcher.deinstall(myComponent);
}
myFocusWatcher = null;
myFocusedCallback = null;
super.dispose();
}
public Object getData(String dataId) {
if (IdeFrame.KEY.getName().equals(dataId)) {
return this;
}
Object data = FrameWrapper.this.getData(dataId);
return data != null ? data : myDatas.get(dataId);
}
@Override
public void paint(Graphics g) {
UIUtil.applyRenderingHints(g);
super.paint(g);
}
}
public void setLocation(Point location) {
getFrame().setLocation(location);
}
public void setSize(Dimension size) {
getFrame().setSize(size);
}
private class MyProjectManagerListener extends ProjectManagerAdapter {
public void projectClosing(Project project) {
if (project == myProject) {
close();
}
}
}
}
| fix lost focus on Mac OS X
| platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java | fix lost focus on Mac OS X |
|
Java | apache-2.0 | 21199464de4aa48733ffa8f86461994f3b4374d6 | 0 | langfr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,xasx/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,filiphr/camunda-bpm-platform,camunda/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,falko/camunda-bpm-platform,langfr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,falko/camunda-bpm-platform,xasx/camunda-bpm-platform,xasx/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,langfr/camunda-bpm-platform,filiphr/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,filiphr/camunda-bpm-platform,falko/camunda-bpm-platform,falko/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,filiphr/camunda-bpm-platform,falko/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,langfr/camunda-bpm-platform,falko/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,camunda/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,langfr/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,camunda/camunda-bpm-platform,langfr/camunda-bpm-platform,filiphr/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,xasx/camunda-bpm-platform,filiphr/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,xasx/camunda-bpm-platform,camunda/camunda-bpm-platform,xasx/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.task;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.inverted;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByAssignee;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCaseExecutionId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCaseInstanceId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCreateTime;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByDescription;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByDueDate;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByExecutionId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByFollowUpDate;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskById;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByName;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByPriority;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByProcessInstanceId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.verifySortingAndCount;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.filter.Filter;
import org.camunda.bpm.engine.impl.TaskQueryImpl;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.repository.CaseDefinition;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.engine.runtime.CaseInstance;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.DelegationState;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.FileValue;
/**
* @author Joram Barrez
* @author Frederik Heremans
* @author Falko Menge
*/
public class TaskQueryTest extends PluggableProcessEngineTestCase {
private List<String> taskIds;
// The range of Oracle's NUMBER field is limited to ~10e+125
// which is below Double.MAX_VALUE, so we only test with the following
// max value
protected static final double MAX_DOUBLE_VALUE = 10E+124;
public void setUp() throws Exception {
identityService.saveUser(identityService.newUser("kermit"));
identityService.saveUser(identityService.newUser("gonzo"));
identityService.saveUser(identityService.newUser("fozzie"));
identityService.saveGroup(identityService.newGroup("management"));
identityService.saveGroup(identityService.newGroup("accountancy"));
identityService.createMembership("kermit", "management");
identityService.createMembership("kermit", "accountancy");
identityService.createMembership("fozzie", "management");
taskIds = generateTestTasks();
}
public void tearDown() throws Exception {
identityService.deleteGroup("accountancy");
identityService.deleteGroup("management");
identityService.deleteUser("fozzie");
identityService.deleteUser("gonzo");
identityService.deleteUser("kermit");
taskService.deleteTasks(taskIds, true);
}
public void tesBasicTaskPropertiesNotNull() {
Task task = taskService.createTaskQuery().taskId(taskIds.get(0)).singleResult();
assertNotNull(task.getDescription());
assertNotNull(task.getId());
assertNotNull(task.getName());
assertNotNull(task.getCreateTime());
}
public void testQueryNoCriteria() {
TaskQuery query = taskService.createTaskQuery();
assertEquals(12, query.count());
assertEquals(12, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByTaskId() {
TaskQuery query = taskService.createTaskQuery().taskId(taskIds.get(0));
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidTaskId() {
TaskQuery query = taskService.createTaskQuery().taskId("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByName() {
TaskQuery query = taskService.createTaskQuery().taskName("testTask");
assertEquals(6, query.list().size());
assertEquals(6, query.count());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByInvalidName() {
TaskQuery query = taskService.createTaskQuery().taskName("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskName(null).singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByNameLike() {
TaskQuery query = taskService.createTaskQuery().taskNameLike("gonzo%");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidNameLike() {
TaskQuery query = taskService.createTaskQuery().taskName("1");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskName(null).singleResult();
fail();
} catch (ProcessEngineException e) { }
}
public void testQueryByDescription() {
TaskQuery query = taskService.createTaskQuery().taskDescription("testTask description");
assertEquals(6, query.list().size());
assertEquals(6, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByInvalidDescription() {
TaskQuery query = taskService.createTaskQuery().taskDescription("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskDescription(null).list();
fail();
} catch (ProcessEngineException e) {
}
}
/**
* CAM-6363
*
* Verify that search by name returns case insensitive results
*/
public void testTaskQueryLookupByNameCaseInsensitive() {
TaskQuery query = taskService.createTaskQuery();
query.taskName("testTask");
List<Task> tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(6));
query = taskService.createTaskQuery();
query.taskName("TeStTaSk");
tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(6));
}
/**
* CAM-6165
*
* Verify that search by name like returns case insensitive results
*/
public void testTaskQueryLookupByNameLikeCaseInsensitive() {
TaskQuery query = taskService.createTaskQuery();
query.taskNameLike("%task%");
List<Task> tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(10));
query = taskService.createTaskQuery();
query.taskNameLike("%Task%");
tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(10));
}
public void testQueryByDescriptionLike() {
TaskQuery query = taskService.createTaskQuery().taskDescriptionLike("%gonzo%");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidDescriptionLike() {
TaskQuery query = taskService.createTaskQuery().taskDescriptionLike("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskDescriptionLike(null).list();
fail();
} catch (ProcessEngineException e) {
}
}
public void testQueryByPriority() {
TaskQuery query = taskService.createTaskQuery().taskPriority(10);
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
query = taskService.createTaskQuery().taskPriority(100);
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
query = taskService.createTaskQuery().taskMinPriority(50);
assertEquals(3, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(10);
assertEquals(5, query.list().size());
query = taskService.createTaskQuery().taskMaxPriority(10);
assertEquals(9, query.list().size());
query = taskService.createTaskQuery().taskMaxPriority(3);
assertEquals(6, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(50).taskMaxPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskPriority(30).taskMaxPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(30).taskPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(30).taskPriority(20).taskMaxPriority(10);
assertEquals(0, query.list().size());
}
public void testQueryByInvalidPriority() {
try {
taskService.createTaskQuery().taskPriority(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByAssignee() {
TaskQuery query = taskService.createTaskQuery().taskAssignee("gonzo");
assertEquals(1, query.count());
assertEquals(1, query.list().size());
assertNotNull(query.singleResult());
query = taskService.createTaskQuery().taskAssignee("kermit");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
assertNull(query.singleResult());
}
public void testQueryByAssigneeLike() {
TaskQuery query = taskService.createTaskQuery().taskAssigneeLike("gonz%");
assertEquals(1, query.count());
assertEquals(1, query.list().size());
assertNotNull(query.singleResult());
query = taskService.createTaskQuery().taskAssignee("gonz");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
assertNull(query.singleResult());
}
public void testQueryByNullAssignee() {
try {
taskService.createTaskQuery().taskAssignee(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByUnassigned() {
TaskQuery query = taskService.createTaskQuery().taskUnassigned();
assertEquals(10, query.count());
assertEquals(10, query.list().size());
}
public void testQueryByAssigned() {
TaskQuery query = taskService.createTaskQuery().taskAssigned();
assertEquals(2, query.count());
assertEquals(2, query.list().size());
}
public void testQueryByCandidateUser() {
// kermit is candidate for 12 tasks, two of them are already assigned
TaskQuery query = taskService.createTaskQuery().taskCandidateUser("kermit");
assertEquals(10, query.count());
assertEquals(10, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("kermit").includeAssignedTasks();
assertEquals(12, query.count());
assertEquals(12, query.list().size());
// fozzie is candidate for 3 tasks, one of them is already assigned
query = taskService.createTaskQuery().taskCandidateUser("fozzie");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("fozzie").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// gonzo is candidate for one task, which is already assinged
query = taskService.createTaskQuery().taskCandidateUser("gonzo");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("gonzo").includeAssignedTasks();
assertEquals(1, query.count());
assertEquals(1, query.list().size());
}
public void testQueryByNullCandidateUser() {
try {
taskService.createTaskQuery().taskCandidateUser(null).list();
fail();
} catch(ProcessEngineException e) {}
}
public void testQueryByIncludeAssignedTasksWithMissingCandidateUserOrGroup() {
try {
taskService.createTaskQuery().includeAssignedTasks();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByCandidateGroup() {
// management group is candidate for 3 tasks, one of them is already assigned
TaskQuery query = taskService.createTaskQuery().taskCandidateGroup("management");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("management").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// accountancy group is candidate for 3 tasks, one of them is already assigned
query = taskService.createTaskQuery().taskCandidateGroup("accountancy");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("accountancy").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// sales group is candidate for no tasks
query = taskService.createTaskQuery().taskCandidateGroup("sales");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("sales").includeAssignedTasks();
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testQueryWithCandidateGroups() {
// test withCandidateGroups
TaskQuery query = taskService.createTaskQuery().withCandidateGroups();
assertEquals(4, query.count());
assertEquals(4, query.list().size());
assertEquals(5, query.includeAssignedTasks().count());
assertEquals(5, query.includeAssignedTasks().list().size());
}
public void testQueryWithoutCandidateGroups() {
// test withoutCandidateGroups
TaskQuery query = taskService.createTaskQuery().withoutCandidateGroups();
assertEquals(6, query.count());
assertEquals(6, query.list().size());
assertEquals(7, query.includeAssignedTasks().count());
assertEquals(7, query.includeAssignedTasks().list().size());
}
public void testQueryByNullCandidateGroup() {
try {
taskService.createTaskQuery().taskCandidateGroup(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByCandidateGroupIn() {
List<String> groups = Arrays.asList("management", "accountancy");
TaskQuery query = taskService.createTaskQuery().taskCandidateGroupIn(groups);
assertEquals(4, query.count());
assertEquals(4, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroupIn(groups).includeAssignedTasks();
assertEquals(5, query.count());
assertEquals(5, query.list().size());
// Unexisting groups or groups that don't have candidate tasks shouldn't influence other results
groups = Arrays.asList("management", "accountancy", "sales", "unexising");
query = taskService.createTaskQuery().taskCandidateGroupIn(groups);
assertEquals(4, query.count());
assertEquals(4, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroupIn(groups).includeAssignedTasks();
assertEquals(5, query.count());
assertEquals(5, query.list().size());
}
public void testQueryByNullCandidateGroupIn() {
try {
taskService.createTaskQuery().taskCandidateGroupIn(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
try {
taskService.createTaskQuery().taskCandidateGroupIn(new ArrayList<String>()).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByDelegationState() {
TaskQuery query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(12, query.count());
assertEquals(12, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
String taskId= taskService.createTaskQuery().taskAssignee("gonzo").singleResult().getId();
taskService.delegateTask(taskId, "kermit");
query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(11, query.count());
assertEquals(11, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(1, query.count());
assertEquals(1, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
taskService.resolveTask(taskId);
query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(11, query.count());
assertEquals(11, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(1, query.count());
assertEquals(1, query.list().size());
}
public void testQueryCreatedOn() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Exact matching of createTime, should result in 6 tasks
Date createTime = sdf.parse("01/01/2001 01:01:01.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedOn(createTime);
assertEquals(6, query.count());
assertEquals(6, query.list().size());
}
public void testQueryCreatedBefore() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Should result in 7 tasks
Date before = sdf.parse("03/02/2002 02:02:02.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedBefore(before);
assertEquals(7, query.count());
assertEquals(7, query.list().size());
before = sdf.parse("01/01/2001 01:01:01.000");
query = taskService.createTaskQuery().taskCreatedBefore(before);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testQueryCreatedAfter() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Should result in 3 tasks
Date after = sdf.parse("03/03/2003 03:03:03.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedAfter(after);
assertEquals(3, query.count());
assertEquals(3, query.list().size());
after = sdf.parse("05/05/2005 05:05:05.000");
query = taskService.createTaskQuery().taskCreatedAfter(after);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testCreateTimeCombinations() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Exact matching of createTime, should result in 6 tasks
Date createTime = sdf.parse("01/01/2001 01:01:01.000");
Date oneHourAgo = new Date(createTime.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(createTime.getTime() + 60 * 60 * 1000);
assertEquals(6, taskService.createTaskQuery()
.taskCreatedAfter(oneHourAgo).taskCreatedOn(createTime).taskCreatedBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKey() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// 1 task should exist with key "taskKey1"
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKey("taskKey1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
// No task should be found with unexisting key
Long count = taskService.createTaskQuery().taskDefinitionKey("unexistingKey").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKeyLike() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// Ends with matching, TaskKey1 and TaskKey123 match
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKeyLike("taskKey1%").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// Starts with matching, TaskKey123 matches
tasks = taskService.createTaskQuery().taskDefinitionKeyLike("%123").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey123", tasks.get(0).getTaskDefinitionKey());
// Contains matching, TaskKey123 matches
tasks = taskService.createTaskQuery().taskDefinitionKeyLike("%Key12%").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey123", tasks.get(0).getTaskDefinitionKey());
// No task should be found with unexisting key
Long count = taskService.createTaskQuery().taskDefinitionKeyLike("%unexistingKey%").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKeyIn() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// 1 Task should be found with TaskKey1
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
// 2 Tasks should be found with TaskKey1 and TaskKey123
tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1", "taskKey123").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// 2 Tasks should be found with TaskKey1, TaskKey123 and UnexistingKey
tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1", "taskKey123", "unexistingKey").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// No task should be found with UnexistingKey
Long count = taskService.createTaskQuery().taskDefinitionKeyIn("unexistingKey").count();
assertEquals(0L, count.longValue());
count = taskService.createTaskQuery().taskDefinitionKey("unexistingKey").taskDefinitionKeyIn("taskKey1").count();
assertEquals(0l, count.longValue());
}
@Deployment
public void testTaskVariableValueEquals() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// No task should be found for an unexisting var
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("unexistingVar", "value").count());
// Create a map with a variable for all default types
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("longVar", 928374L);
variables.put("shortVar", (short) 123);
variables.put("integerVar", 1234);
variables.put("stringVar", "stringValue");
variables.put("booleanVar", true);
Date date = Calendar.getInstance().getTime();
variables.put("dateVar", date);
variables.put("nullVar", null);
taskService.setVariablesLocal(task.getId(), variables);
// Test query matches
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("longVar", 928374L).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 123).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 1234).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "stringValue").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", true).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("dateVar", date).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("nullVar", null).count());
// Test query for other values on existing variables
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("longVar", 999L).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 999).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 999).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "999").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", false).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("dateVar", otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("nullVar", "999").count());
// Test query for not equals
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("longVar", 999L).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("shortVar", (short) 999).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("integerVar", 999).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("stringVar", "999").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("booleanVar", false).count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testTaskVariableValueEquals.bpmn20.xml")
public void testTaskVariableValueLike() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("stringVar", "stringValue");
taskService.setVariablesLocal(task.getId(), variables);
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVal%").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngValue").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVal%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVar%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVar").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVar%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVal").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("nonExistingVar", "string%").count());
// test with null value
try {
taskService.createTaskQuery().taskVariableValueLike("stringVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testTaskVariableValueEquals.bpmn20.xml")
public void testTaskVariableValueCompare() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("numericVar", 928374);
Date date = new GregorianCalendar(2014, 2, 2, 2, 2, 2).getTime();
variables.put("dateVar", date);
variables.put("stringVar", "ab");
variables.put("nullVar", null);
taskService.setVariablesLocal(task.getId(), variables);
// test compare methods with numeric values
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928373).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928375).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928373).count());
// test compare methods with date values
Date before = new GregorianCalendar(2014, 2, 2, 2, 2, 1).getTime();
Date after = new GregorianCalendar(2014, 2, 2, 2, 2, 3).getTime();
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", before).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", after).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", before).count());
//test with string values
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "aa").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "ba").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "aa").count());
// test with null value
try {
taskService.createTaskQuery().taskVariableValueGreaterThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test with boolean value
try {
taskService.createTaskQuery().taskVariableValueGreaterThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test non existing variable
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nonExisting", 123).count());
}
@Deployment
public void testProcessVariableValueEquals() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("longVar", 928374L);
variables.put("shortVar", (short) 123);
variables.put("integerVar", 1234);
variables.put("stringVar", "stringValue");
variables.put("booleanVar", true);
Date date = Calendar.getInstance().getTime();
variables.put("dateVar", date);
variables.put("nullVar", null);
// Start process-instance with all types of variables
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
// Test query matches
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("longVar", 928374L).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("shortVar", (short) 123).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("integerVar", 1234).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("stringVar", "stringValue").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("booleanVar", true).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("dateVar", date).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("nullVar", null).count());
// Test query for other values on existing variables
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("longVar", 999L).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("shortVar", (short) 999).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("integerVar", 999).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("stringVar", "999").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("booleanVar", false).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("dateVar", otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("nullVar", "999").count());
// Test querying for task variables don't match the process-variables
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("longVar", 928374L).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 123).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 1234).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "stringValue").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", true).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("nullVar", null).count());
// Test querying for task variables not equals
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("longVar", 999L).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("shortVar", (short) 999).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("integerVar", 999).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("stringVar", "999").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("booleanVar", false).count());
// and query for the existing variable with NOT shoudl result in nothing found:
assertEquals(0, taskService.createTaskQuery().processVariableValueNotEquals("longVar", 928374L).count());
// Test combination of task-variable and process-variable
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
taskService.setVariableLocal(task.getId(), "taskVar", "theValue");
taskService.setVariableLocal(task.getId(), "longVar", 928374L);
assertEquals(1, taskService.createTaskQuery()
.processVariableValueEquals("longVar", 928374L)
.taskVariableValueEquals("taskVar", "theValue")
.count());
assertEquals(1, taskService.createTaskQuery()
.processVariableValueEquals("longVar", 928374L)
.taskVariableValueEquals("longVar", 928374L)
.count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessVariableValueEquals.bpmn20.xml")
public void testProcessVariableValueLike() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("stringVar", "stringValue");
runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVal%").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngValue").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVal%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVar%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVar").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVar%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVal").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("nonExistingVar", "string%").count());
// test with null value
try {
taskService.createTaskQuery().processVariableValueLike("stringVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessVariableValueEquals.bpmn20.xml")
public void testProcessVariableValueCompare() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("numericVar", 928374);
Date date = new GregorianCalendar(2014, 2, 2, 2, 2, 2).getTime();
variables.put("dateVar", date);
variables.put("stringVar", "ab");
variables.put("nullVar", null);
runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
// test compare methods with numeric values
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928373).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928375).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928373).count());
// test compare methods with date values
Date before = new GregorianCalendar(2014, 2, 2, 2, 2, 1).getTime();
Date after = new GregorianCalendar(2014, 2, 2, 2, 2, 3).getTime();
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", before).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("dateVar", after).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", before).count());
//test with string values
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "aa").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "ba").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "aa").count());
// test with null value
try {
taskService.createTaskQuery().processVariableValueGreaterThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test with boolean value
try {
taskService.createTaskQuery().processVariableValueGreaterThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test non existing variable
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("nonExisting", 123).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testProcessVariableValueEqualsNumber() throws Exception {
// long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123L));
// non-matching long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 12345L));
// short
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 123));
// double
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123.0d));
// integer
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123));
// untyped null (should not match)
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", null));
// typed null (should not match)
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Variables.longValue(null)));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "123"));
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123L)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123.0d)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue((short) 123)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(null)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testProcessVariableValueNumberComparison() throws Exception {
// long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123L));
// non-matching long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 12345L));
// short
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 123));
// double
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123.0d));
// integer
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123));
// untyped null
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", null));
// typed null
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Variables.longValue(null)));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "123"));
assertEquals(4, taskService.createTaskQuery().processVariableValueNotEquals("var", Variables.numberValue(123)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("var", Variables.numberValue(123)).count());
assertEquals(5, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("var", Variables.numberValue(123)).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueLessThanOrEquals("var", Variables.numberValue(123)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testTaskVariableValueEqualsNumber() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("oneTaskProcess").list();
assertEquals(8, tasks.size());
taskService.setVariableLocal(tasks.get(0).getId(), "var", 123L);
taskService.setVariableLocal(tasks.get(1).getId(), "var", 12345L);
taskService.setVariableLocal(tasks.get(2).getId(), "var", (short) 123);
taskService.setVariableLocal(tasks.get(3).getId(), "var", 123.0d);
taskService.setVariableLocal(tasks.get(4).getId(), "var", 123);
taskService.setVariableLocal(tasks.get(5).getId(), "var", null);
taskService.setVariableLocal(tasks.get(6).getId(), "var", Variables.longValue(null));
taskService.setVariableLocal(tasks.get(7).getId(), "var", "123");
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123L)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123.0d)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue((short) 123)).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(null)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberMax() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", MAX_DOUBLE_VALUE));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Long.MAX_VALUE));
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(MAX_DOUBLE_VALUE)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(Long.MAX_VALUE)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberLongValueOverflow() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", MAX_DOUBLE_VALUE));
// this results in an overflow
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (long) MAX_DOUBLE_VALUE));
// the query should not find the long variable
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(MAX_DOUBLE_VALUE)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberNonIntegerDoubleShouldNotMatchInteger() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 42).putValue("var2", 52.4d));
// querying by 42.4 should not match the integer variable 42
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(42.4d)).count());
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42.4d));
// querying by 52 should not find the double variable 52.4
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(52)).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionId() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionId(processInstance.getProcessDefinitionId()).list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionId("unexisting").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionKey() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("oneTaskProcess").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionKey("unexisting").count());
}
@Deployment(resources = {
"org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml",
"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"
})
public void testProcessDefinitionKeyIn() throws Exception {
// Start for each deployed process definition a process instance
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
// 1 task should be found with oneTaskProcess
List<Task> tasks = taskService.createTaskQuery().processDefinitionKeyIn("oneTaskProcess").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// 2 Tasks should be found with both process definition keys
tasks = taskService.createTaskQuery()
.processDefinitionKeyIn("oneTaskProcess", "taskDefinitionKeyProcess")
.list();
assertNotNull(tasks);
assertEquals(3, tasks.size());
Set<String> keysFound = new HashSet<String>();
for (Task task : tasks) {
keysFound.add(task.getTaskDefinitionKey());
}
assertTrue(keysFound.contains("taskKey123"));
assertTrue(keysFound.contains("theTask"));
assertTrue(keysFound.contains("taskKey1"));
// 1 Tasks should be found with oneTaskProcess,and NonExistingKey
tasks = taskService.createTaskQuery().processDefinitionKeyIn("oneTaskProcess", "NonExistingKey").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// No task should be found with NonExistingKey
Long count = taskService.createTaskQuery().processDefinitionKeyIn("NonExistingKey").count();
assertEquals(0L, count.longValue());
count = taskService.createTaskQuery()
.processDefinitionKeyIn("oneTaskProcess").processDefinitionKey("NonExistingKey").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionName() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionName("The One Task Process").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionName("unexisting").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionNameLike() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionNameLike("The One Task%").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionNameLike("The One Task").count());
assertEquals(0, taskService.createTaskQuery().processDefinitionNameLike("The Other Task%").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKey() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
assertEquals(1, taskService.createTaskQuery().processDefinitionName("The One Task Process").processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(1, taskService.createTaskQuery().processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKey("NON-EXISTING").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKeyIn() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-2");
// 1 task should be found with BUSINESS-KEY-1
List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKeyIn("BUSINESS-KEY-1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// 2 tasks should be found with BUSINESS-KEY-1 and BUSINESS-KEY-2
tasks = taskService.createTaskQuery()
.processInstanceBusinessKeyIn("BUSINESS-KEY-1", "BUSINESS-KEY-2")
.list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
for (Task task : tasks) {
assertEquals("theTask", task.getTaskDefinitionKey());
}
// 1 tasks should be found with BUSINESS-KEY-1 and NON-EXISTING-KEY
Task task = taskService.createTaskQuery()
.processInstanceBusinessKeyIn("BUSINESS-KEY-1", "NON-EXISTING-KEY")
.singleResult();
assertNotNull(tasks);
assertEquals("theTask", task.getTaskDefinitionKey());
long count = taskService.createTaskQuery().processInstanceBusinessKeyIn("BUSINESS-KEY-1").processInstanceBusinessKey("NON-EXISTING-KEY")
.count();
assertEquals(0l, count);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKeyLike() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
assertEquals(1, taskService.createTaskQuery().processDefinitionName("The One Task Process").processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(1, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUSINESS-KEY%").list().size());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUSINESS-KEY").count());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUZINESS-KEY%").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueDate() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setDueDate(dueDate);
taskService.saveTask(task);
assertEquals(1, taskService.createTaskQuery().dueDate(dueDate).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().dueDate(otherDate.getTime()).count());
Calendar priorDate = Calendar.getInstance();
priorDate.setTime(dueDate);
priorDate.roll(Calendar.YEAR, -1);
assertEquals(1, taskService.createTaskQuery().dueAfter(priorDate.getTime())
.count());
assertEquals(1, taskService.createTaskQuery()
.dueBefore(otherDate.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueBefore() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Calendar dueDateCal = Calendar.getInstance();
task.setDueDate(dueDateCal.getTime());
taskService.saveTask(task);
Calendar oneHourAgo = Calendar.getInstance();
oneHourAgo.setTime(dueDateCal.getTime());
oneHourAgo.add(Calendar.HOUR, -1);
Calendar oneHourLater = Calendar.getInstance();
oneHourLater.setTime(dueDateCal.getTime());
oneHourLater.add(Calendar.HOUR, 1);
assertEquals(1, taskService.createTaskQuery().dueBefore(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourAgo.getTime()).count());
// Update due-date to null, shouldn't show up anymore in query that matched before
task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
task.setDueDate(null);
taskService.saveTask(task);
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourAgo.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueAfter() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Calendar dueDateCal = Calendar.getInstance();
task.setDueDate(dueDateCal.getTime());
taskService.saveTask(task);
Calendar oneHourAgo = Calendar.getInstance();
oneHourAgo.setTime(dueDateCal.getTime());
oneHourAgo.add(Calendar.HOUR, -1);
Calendar oneHourLater = Calendar.getInstance();
oneHourLater.setTime(dueDateCal.getTime());
oneHourLater.add(Calendar.HOUR, 1);
assertEquals(1, taskService.createTaskQuery().dueAfter(oneHourAgo.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater.getTime()).count());
// Update due-date to null, shouldn't show up anymore in query that matched before
task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
task.setDueDate(null);
taskService.saveTask(task);
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourAgo.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueDateCombinations() throws ParseException {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setDueDate(dueDate);
taskService.saveTask(task);
Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
assertEquals(1, taskService.createTaskQuery()
.dueAfter(oneHourAgo).dueDate(dueDate).dueBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.dueAfter(oneHourLater).dueDate(dueDate).dueBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.dueAfter(oneHourLater).dueDate(dueDate).count());
assertEquals(0, taskService.createTaskQuery()
.dueDate(dueDate).dueBefore(oneHourAgo).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testFollowUpDate() throws Exception {
Calendar otherDate = Calendar.getInstance();
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// do not find any task instances with follow up date
assertEquals(0, taskService.createTaskQuery().followUpDate(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId())
// we might have tasks from other test cases - so we limit to the current PI
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// set follow-up date on task
Date followUpDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setFollowUpDate(followUpDate);
taskService.saveTask(task);
assertEquals(followUpDate, taskService.createTaskQuery().taskId(task.getId()).singleResult().getFollowUpDate());
assertEquals(1, taskService.createTaskQuery().followUpDate(followUpDate).count());
otherDate.setTime(followUpDate);
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().followUpDate(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().followUpBefore(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId()) //
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().followUpAfter(otherDate.getTime()).count());
otherDate.add(Calendar.YEAR, -2);
assertEquals(1, taskService.createTaskQuery().followUpAfter(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().followUpBefore(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().processInstanceId(processInstance.getId()) //
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
taskService.complete(task.getId());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testFollowUpDateCombinations() throws ParseException {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set follow-up date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setFollowUpDate(dueDate);
taskService.saveTask(task);
Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
assertEquals(1, taskService.createTaskQuery()
.followUpAfter(oneHourAgo).followUpDate(dueDate).followUpBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.followUpAfter(oneHourLater).followUpDate(dueDate).followUpBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.followUpAfter(oneHourLater).followUpDate(dueDate).count());
assertEquals(0, taskService.createTaskQuery()
.followUpDate(dueDate).followUpBefore(oneHourAgo).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByActivityInstanceId() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId = runtimeService.getActivityInstance(processInstance.getId())
.getChildActivityInstances()[0].getId();
assertEquals(1, taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId).list().size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByMultipleActivityInstanceIds() throws Exception {
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId1 = runtimeService.getActivityInstance(processInstance1.getId())
.getChildActivityInstances()[0].getId();
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId2 = runtimeService.getActivityInstance(processInstance2.getId())
.getChildActivityInstances()[0].getId();
List<Task> result1 = taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId1).list();
assertEquals(1, result1.size());
assertEquals(processInstance1.getId(), result1.get(0).getProcessInstanceId());
List<Task> result2 = taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId2).list();
assertEquals(1, result2.size());
assertEquals(processInstance2.getId(), result2.get(0).getProcessInstanceId());
assertEquals(2, taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId1, activityInstanceId2).list().size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByInvalidActivityInstanceId() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess");
assertEquals(0, taskService.createTaskQuery().activityInstanceIdIn("anInvalidActivityInstanceId").list().size());
}
public void testQueryPaging() {
TaskQuery query = taskService.createTaskQuery().taskCandidateUser("kermit");
assertEquals(10, query.listPage(0, Integer.MAX_VALUE).size());
// Verifying the un-paged results
assertEquals(10, query.count());
assertEquals(10, query.list().size());
// Verifying paged results
assertEquals(2, query.listPage(0, 2).size());
assertEquals(2, query.listPage(2, 2).size());
assertEquals(3, query.listPage(4, 3).size());
assertEquals(1, query.listPage(9, 3).size());
assertEquals(1, query.listPage(9, 1).size());
// Verifying odd usages
assertEquals(0, query.listPage(-1, -1).size());
assertEquals(0, query.listPage(10, 2).size()); // 9 is the last index with a result
assertEquals(10, query.listPage(0, 15).size()); // there are only 10 tasks
}
public void testQuerySorting() {
// default ordering is by id
int expectedCount = 12;
verifySortingAndCount(taskService.createTaskQuery(), expectedCount, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().asc(), expectedCount, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskName().asc(), expectedCount, taskByName());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskPriority().asc(), expectedCount, taskByPriority());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskAssignee().asc(), expectedCount, taskByAssignee());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskDescription().asc(), expectedCount, taskByDescription());
verifySortingAndCount(taskService.createTaskQuery().orderByProcessInstanceId().asc(), expectedCount, taskByProcessInstanceId());
verifySortingAndCount(taskService.createTaskQuery().orderByExecutionId().asc(), expectedCount, taskByExecutionId());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskCreateTime().asc(), expectedCount, taskByCreateTime());
verifySortingAndCount(taskService.createTaskQuery().orderByDueDate().asc(), expectedCount, taskByDueDate());
verifySortingAndCount(taskService.createTaskQuery().orderByFollowUpDate().asc(), expectedCount, taskByFollowUpDate());
verifySortingAndCount(taskService.createTaskQuery().orderByCaseInstanceId().asc(), expectedCount, taskByCaseInstanceId());
verifySortingAndCount(taskService.createTaskQuery().orderByCaseExecutionId().asc(), expectedCount, taskByCaseExecutionId());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().desc(), expectedCount, inverted(taskById()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskName().desc(), expectedCount, inverted(taskByName()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskPriority().desc(), expectedCount, inverted(taskByPriority()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskAssignee().desc(), expectedCount, inverted(taskByAssignee()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskDescription().desc(), expectedCount, inverted(taskByDescription()));
verifySortingAndCount(taskService.createTaskQuery().orderByProcessInstanceId().desc(), expectedCount, inverted(taskByProcessInstanceId()));
verifySortingAndCount(taskService.createTaskQuery().orderByExecutionId().desc(), expectedCount, inverted(taskByExecutionId()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskCreateTime().desc(), expectedCount, inverted(taskByCreateTime()));
verifySortingAndCount(taskService.createTaskQuery().orderByDueDate().desc(), expectedCount, inverted(taskByDueDate()));
verifySortingAndCount(taskService.createTaskQuery().orderByFollowUpDate().desc(), expectedCount, inverted(taskByFollowUpDate()));
verifySortingAndCount(taskService.createTaskQuery().orderByCaseInstanceId().desc(), expectedCount, inverted(taskByCaseInstanceId()));
verifySortingAndCount(taskService.createTaskQuery().orderByCaseExecutionId().desc(), expectedCount, inverted(taskByCaseExecutionId()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().taskName("testTask").asc(), 6, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().taskName("testTask").desc(), 6, inverted(taskById()));
}
public void testQuerySortingByNameShouldBeCaseInsensitive() {
// create task with capitalized name
Task task = taskService.newTask("caseSensitiveTestTask");
task.setName("CaseSensitiveTestTask");
taskService.saveTask(task);
// create task filter
Filter filter = filterService.newTaskFilter("taskNameOrdering");
filterService.saveFilter(filter);
List<String> sortedNames = getTaskNamesFromTasks(taskService.createTaskQuery().list());
Collections.sort(sortedNames, String.CASE_INSENSITIVE_ORDER);
// ascending ordering
TaskQuery taskQuery = taskService.createTaskQuery().orderByTaskNameCaseInsensitive().asc();
List<String> ascNames = getTaskNamesFromTasks(taskQuery.list());
assertEquals(sortedNames, ascNames);
// test filter merging
ascNames = getTaskNamesFromTasks(filterService.list(filter.getId(), taskQuery));
assertEquals(sortedNames, ascNames);
// descending ordering
// reverse sorted names to test descending ordering
Collections.reverse(sortedNames);
taskQuery = taskService.createTaskQuery().orderByTaskNameCaseInsensitive().desc();
List<String> descNames = getTaskNamesFromTasks(taskQuery.list());
assertEquals(sortedNames, descNames);
// test filter merging
descNames = getTaskNamesFromTasks(filterService.list(filter.getId(), taskQuery));
assertEquals(sortedNames, descNames);
// delete test task
taskService.deleteTask(task.getId(), true);
// delete filter
filterService.deleteFilter(filter.getId());
}
public void testQueryOrderByTaskName() {
// asc
List<Task> tasks = taskService.createTaskQuery()
.orderByTaskName()
.asc()
.list();
assertEquals(12, tasks.size());
List<String> taskNames = getTaskNamesFromTasks(tasks);
assertEquals("accountancy description", taskNames.get(0));
assertEquals("accountancy description", taskNames.get(1));
assertEquals("gonzoTask", taskNames.get(2));
assertEquals("managementAndAccountancyTask", taskNames.get(3));
assertEquals("managementTask", taskNames.get(4));
assertEquals("managementTask", taskNames.get(5));
assertEquals("testTask", taskNames.get(6));
assertEquals("testTask", taskNames.get(7));
assertEquals("testTask", taskNames.get(8));
assertEquals("testTask", taskNames.get(9));
assertEquals("testTask", taskNames.get(10));
assertEquals("testTask", taskNames.get(11));
// desc
tasks = taskService.createTaskQuery()
.orderByTaskName()
.desc()
.list();
assertEquals(12, tasks.size());
taskNames = getTaskNamesFromTasks(tasks);
assertEquals("testTask", taskNames.get(0));
assertEquals("testTask", taskNames.get(1));
assertEquals("testTask", taskNames.get(2));
assertEquals("testTask", taskNames.get(3));
assertEquals("testTask", taskNames.get(4));
assertEquals("testTask", taskNames.get(5));
assertEquals("managementTask", taskNames.get(6));
assertEquals("managementTask", taskNames.get(7));
assertEquals("managementAndAccountancyTask", taskNames.get(8));
assertEquals("gonzoTask", taskNames.get(9));
assertEquals("accountancy description", taskNames.get(10));
assertEquals("accountancy description", taskNames.get(11));
}
public List<String> getTaskNamesFromTasks(List<Task> tasks) {
List<String> names = new ArrayList<String>();
for (Task task : tasks) {
names.add(task.getName());
}
return names;
}
public void testNativeQuery() {
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(Task.class));
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(TaskEntity.class));
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).list().size());
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class)).count());
assertEquals(144, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + tablePrefix + "ACT_RU_TASK T1, " + tablePrefix + "ACT_RU_TASK T2").count());
// join task and variable instances
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T1, "+managementService.getTableName(VariableInstanceEntity.class)+" V1 WHERE V1.TASK_ID_ = T1.ID_").count());
List<Task> tasks = taskService.createNativeTaskQuery().sql("SELECT T1.* FROM " + managementService.getTableName(Task.class) + " T1, "+managementService.getTableName(VariableInstanceEntity.class)+" V1 WHERE V1.TASK_ID_ = T1.ID_").list();
assertEquals(1, tasks.size());
assertEquals("gonzoTask", tasks.get(0).getName());
// select with distinct
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT DISTINCT T1.* FROM " + tablePrefix + "ACT_RU_TASK T1").list().size());
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = 'gonzoTask'").count());
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = 'gonzoTask'").list().size());
// use parameters
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = #{taskName}").parameter("taskName", "gonzoTask").count());
}
public void testNativeQueryPaging() {
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(Task.class));
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(TaskEntity.class));
assertEquals(5, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).listPage(0, 5).size());
assertEquals(2, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).listPage(10, 12).size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionId() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionId(caseDefinitionId);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionId() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionId("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionKey() {
String caseDefinitionKey = repositoryService
.createCaseDefinitionQuery()
.singleResult()
.getKey();
caseService
.withCaseDefinitionByKey(caseDefinitionKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionKey(caseDefinitionKey);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionKey() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionKey("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionKey(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionName() {
CaseDefinition caseDefinition = repositoryService
.createCaseDefinitionQuery()
.singleResult();
String caseDefinitionId = caseDefinition.getId();
String caseDefinitionName = caseDefinition.getName();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionName(caseDefinitionName);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionName() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionName("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionName(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionNameLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionNameLike("One T%");
verifyQueryResults(query, 1);
query.caseDefinitionNameLike("%Task Case");
verifyQueryResults(query, 1);
query.caseDefinitionNameLike("%Task%");
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionNameLike() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionNameLike("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionNameLike(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceId() {
String caseDefinitionId = getCaseDefinitionId();
String caseInstanceId = caseService
.withCaseDefinition(caseDefinitionId)
.create()
.getId();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId(caseInstanceId);
verifyQueryResults(query, 1);
}
@Deployment(resources=
{
"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testQueryByCaseInstanceIdHierarchy.cmmn",
"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testQueryByCaseInstanceIdHierarchy.bpmn20.xml"
})
public void testQueryByCaseInstanceIdHierarchy() {
// given
String caseInstanceId = caseService
.withCaseDefinitionByKey("case")
.create()
.getId();
String processTaskId = caseService
.createCaseExecutionQuery()
.activityId("PI_ProcessTask_1")
.singleResult()
.getId();
// then
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId(caseInstanceId);
verifyQueryResults(query, 2);
for (Task task : query.list()) {
assertEquals(caseInstanceId, task.getCaseInstanceId());
taskService.complete(task.getId());
}
verifyQueryResults(query, 1);
assertEquals(caseInstanceId, query.singleResult().getCaseInstanceId());
taskService.complete(query.singleResult().getId());
verifyQueryResults(query, 0);
}
public void testQueryByInvalidCaseInstanceId() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceBusinessKey() {
String caseDefinitionId = getCaseDefinitionId();
String businessKey = "aBusinessKey";
caseService
.withCaseDefinition(caseDefinitionId)
.businessKey(businessKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKey(businessKey);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseInstanceBusinessKey() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKey("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceBusinessKey(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceBusinessKeyLike() {
String caseDefinitionId = getCaseDefinitionId();
String businessKey = "aBusinessKey";
caseService
.withCaseDefinition(caseDefinitionId)
.businessKey(businessKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKeyLike("aBus%");
verifyQueryResults(query, 1);
query.caseInstanceBusinessKeyLike("%sinessKey");
verifyQueryResults(query, 1);
query.caseInstanceBusinessKeyLike("%sines%");
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseInstanceBusinessKeyLike() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKeyLike("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceBusinessKeyLike(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn"})
public void testQueryByCaseExecutionId() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
String humanTaskExecutionId = startDefaultCaseExecutionManually();
TaskQuery query = taskService.createTaskQuery();
query.caseExecutionId(humanTaskExecutionId);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseExecutionId() {
TaskQuery query = taskService.createTaskQuery();
query.caseExecutionId("invalid");
verifyQueryResults(query, 0);
try {
query.caseExecutionId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aNullValue", null);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aBooleanValue", true);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueEquals() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
/**
* Starts the one deployed case at the point of the manual activity PI_HumanTask_1
* with the given variable.
*/
protected void startDefaultCaseWithVariable(Object variableValue, String variableName) {
String caseDefinitionId = getCaseDefinitionId();
createCaseWithVariable(caseDefinitionId, variableValue, variableName);
}
/**
* @return the case definition id if only one case is deployed.
*/
protected String getCaseDefinitionId() {
String caseDefinitionId = repositoryService
.createCaseDefinitionQuery()
.singleResult()
.getId();
return caseDefinitionId;
}
protected void createCaseWithVariable(String caseDefinitionId, Object variableValue, String variableName) {
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable(variableName, variableValue)
.create();
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aStringValue", "abd");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aBooleanValue", false);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aShortValue", (short) 124);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("anIntegerValue", 457);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aLongValue", (long) 790);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
Date before = new Date(now.getTime() - 100000);
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aDateValue", before);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueNotEquals() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
/**
* @return
*/
protected FileValue createDefaultFileValue() {
FileValue fileValue = Variables.fileValue("tst.txt").file("somebytes".getBytes()).create();
return fileValue;
}
/**
* Starts the case execution for oneTaskCase.cmmn<p>
* Only works for testcases, which deploy that process.
*
* @return the execution id for the activity PI_HumanTask_1
*/
protected String startDefaultCaseExecutionManually() {
String humanTaskExecutionId = caseService
.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.singleResult()
.getId();
caseService
.withCaseExecution(humanTaskExecutionId)
.manualStart();
return humanTaskExecutionId;
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aStringValue", "ab");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aShortValue", (short) 122);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("anIntegerValue", 455);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aLongValue", (long) 788);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date before = new Date(now.getTime() - 100000);
query.caseInstanceVariableValueGreaterThan("aDateValue", before);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aDoubleValue", 1.4);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn"})
public void testQueryByFileCaseInstanceVariableValueGreaterThan() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
startDefaultCaseExecutionManually();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aStringValue", "ab");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aShortValue", (short) 122);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueGreaterThanOrEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("anIntegerValue", 455);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aLongValue", (long) 788);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date before = new Date(now.getTime() - 100000);
query.caseInstanceVariableValueGreaterThanOrEquals("aDateValue", before);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDoubleValue", 1.4);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueGreaterThanOrEqual() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aStringValue", "abd");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aShortValue", (short) 124);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("anIntegerValue", 457);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aLongValue", (long) 790);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date after = new Date(now.getTime() + 100000);
query.caseInstanceVariableValueLessThan("aDateValue", after);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableLessThan() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueLessThan() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aStringValue", "abd");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aShortValue", (short) 124);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueLessThanOrEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("anIntegerValue", 457);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aLongValue", (long) 790);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date after = new Date(now.getTime() + 100000);
query.caseInstanceVariableValueLessThanOrEquals("aDateValue", after);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueLessThanOrEqual() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLike("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "ab%");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "%bc");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "%b%");
verifyQueryResults(query, 1);
}
@Deployment
public void testQueryByVariableInParallelBranch() throws Exception {
runtimeService.startProcessInstanceByKey("parallelGateway");
// when there are two process variables of the same name but different types
Execution task1Execution = runtimeService.createExecutionQuery().activityId("task1").singleResult();
runtimeService.setVariableLocal(task1Execution.getId(), "var", 12345L);
Execution task2Execution = runtimeService.createExecutionQuery().activityId("task2").singleResult();
runtimeService.setVariableLocal(task2Execution.getId(), "var", 12345);
// then the task query should be able to filter by both variables and return both tasks
assertEquals(2, taskService.createTaskQuery().processVariableValueEquals("var", 12345).count());
assertEquals(2, taskService.createTaskQuery().processVariableValueEquals("var", 12345L).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByProcessVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
// when I make a task query with ascending variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// then in alphabetical order
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
// when I make a task query with descending variable ordering by String values
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.desc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// then in alphabetical order
assertEquals(instance2.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
// when I make a task query with variable ordering by Integer values
List<Task> unorderedTasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
// then the tasks are in no particular ordering
assertEquals(3, unorderedTasks.size());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testLocalExecutionVariable.bpmn20.xml")
public void testQueryResultOrderingByExecutionVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "cValue"));
// and some local variables on the tasks
Task task1 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
runtimeService.setVariableLocal(task1.getExecutionId(), "var", "cValue");
Task task2 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
runtimeService.setVariableLocal(task2.getExecutionId(), "var", "bValue");
Task task3 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
runtimeService.setVariableLocal(task3.getExecutionId(), "var", "aValue");
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("parallelGateway")
.orderByExecutionVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByTaskVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
// and some local variables on the tasks
Task task1 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
taskService.setVariableLocal(task1.getId(), "var", "cValue");
Task task2 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
taskService.setVariableLocal(task2.getId(), "var", "bValue");
Task task3 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
taskService.setVariableLocal(task3.getId(), "var", "aValue");
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByTaskVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn")
public void testQueryResultOrderingByCaseInstanceVariables() {
// given three tasks with String case instance variables
CaseInstance instance1 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "cValue"));
CaseInstance instance2 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "aValue"));
CaseInstance instance3 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "bValue"));
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.caseDefinitionKey("oneTaskCase")
.orderByCaseInstanceVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance2.getId(), tasks.get(0).getCaseInstanceId());
assertEquals(instance3.getId(), tasks.get(1).getCaseInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getCaseInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn")
public void testQueryResultOrderingByCaseExecutionVariables() {
// given three tasks with String case instance variables
CaseInstance instance1 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "cValue"));
CaseInstance instance2 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "aValue"));
CaseInstance instance3 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "bValue"));
// and local case execution variables
CaseExecution caseExecution1 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance1.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution1.getId())
.setVariableLocal("var", "aValue")
.manualStart();
CaseExecution caseExecution2 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance2.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution2.getId())
.setVariableLocal("var", "bValue")
.manualStart();
CaseExecution caseExecution3 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance3.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution3.getId())
.setVariableLocal("var", "cValue")
.manualStart();
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.caseDefinitionKey("oneTaskCase")
.orderByCaseExecutionVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance1.getId(), tasks.get(0).getCaseInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getCaseInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getCaseInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithNullValues() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance4 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
Task firstTask = tasks.get(0);
// the null-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance4.getId())) {
// then the others in ascending order
assertEquals(instance3.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(3).getProcessInstanceId());
} else {
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
assertEquals(instance4.getId(), tasks.get(3).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithMixedTypes() {
// given three tasks with String and Integer process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
Task firstTask = tasks.get(0);
// the numeric-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance1.getId())) {
// then the others in ascending order
assertEquals(instance3.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
} else {
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByStringVariableWithMixedCase() {
// given three tasks with String and Integer process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "a"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "B"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "c"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// first the numeric valued task (since it is treated like null-valued)
assertEquals(instance1.getId(), tasks.get(0).getProcessInstanceId());
// then the others in alphabetical order
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesOfAllPrimitiveTypes() {
// given three tasks with String and Integer process instance variables
ProcessInstance booleanInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", true));
ProcessInstance shortInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 16));
ProcessInstance longInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 500L));
ProcessInstance intInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 400));
ProcessInstance stringInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "300"));
ProcessInstance dateInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", new Date(1000L)));
ProcessInstance doubleInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42.5d));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.BOOLEAN)
.asc()
.list();
verifyFirstOrLastTask(tasks, booleanInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.SHORT)
.asc()
.list();
verifyFirstOrLastTask(tasks, shortInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.LONG)
.asc()
.list();
verifyFirstOrLastTask(tasks, longInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
verifyFirstOrLastTask(tasks, intInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
verifyFirstOrLastTask(tasks, stringInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.DATE)
.asc()
.list();
verifyFirstOrLastTask(tasks, dateInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.DOUBLE)
.asc()
.list();
verifyFirstOrLastTask(tasks, doubleInstance);
}
public void testQueryByUnsupportedValueTypes() {
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.BYTES);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type byte", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.NULL);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type null", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.NUMBER);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type number", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.OBJECT);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type object", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.FILE);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type file", e.getMessage());
}
}
/**
* verify that either the first or the last task of the list belong to the given process instance
*/
protected void verifyFirstOrLastTask(List<Task> tasks, ProcessInstance belongingProcessInstance) {
if (tasks.size() == 0) {
fail("no tasks given");
}
int numTasks = tasks.size();
boolean matches = tasks.get(0).getProcessInstanceId().equals(belongingProcessInstance.getId());
matches = matches || tasks.get(numTasks - 1).getProcessInstanceId()
.equals(belongingProcessInstance.getId());
assertTrue("neither first nor last task belong to process instance " + belongingProcessInstance.getId(),
matches);
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithMixedTypesAndSameColumn() {
// given three tasks with Integer and Long process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 800));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 500L));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
Task firstTask = tasks.get(0);
// the Long-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance3.getId())) {
// then the others in ascending order
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
} else {
assertEquals(instance1.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByTwoVariables() {
// given three tasks with String process instance variables
ProcessInstance bInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b").putValue("var2", 14));
ProcessInstance bInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b").putValue("var2", 30));
ProcessInstance cInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c").putValue("var2", 50));
ProcessInstance cInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c").putValue("var2", 30));
ProcessInstance aInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a").putValue("var2", 14));
ProcessInstance aInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a").putValue("var2", 50));
// when I make a task query with variable primary ordering by var values
// and secondary ordering by var2 values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.desc()
.orderByProcessVariable("var2", ValueType.INTEGER)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = c; var2 = 30
assertEquals(cInstance2.getId(), tasks.get(0).getProcessInstanceId());
// var = c; var2 = 50
assertEquals(cInstance1.getId(), tasks.get(1).getProcessInstanceId());
// var = b; var2 = 14
assertEquals(bInstance1.getId(), tasks.get(2).getProcessInstanceId());
// var = b; var2 = 30
assertEquals(bInstance2.getId(), tasks.get(3).getProcessInstanceId());
// var = a; var2 = 14
assertEquals(aInstance1.getId(), tasks.get(4).getProcessInstanceId());
// var = a; var2 = 50
assertEquals(aInstance2.getId(), tasks.get(5).getProcessInstanceId());
// when I make a task query with variable primary ordering by var2 values
// and secondary ordering by var values
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var2", ValueType.INTEGER)
.desc()
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = a; var2 = 50
assertEquals(aInstance2.getId(), tasks.get(0).getProcessInstanceId());
// var = c; var2 = 50
assertEquals(cInstance1.getId(), tasks.get(1).getProcessInstanceId());
// var = b; var2 = 30
assertEquals(bInstance2.getId(), tasks.get(2).getProcessInstanceId());
// var = c; var2 = 30
assertEquals(cInstance2.getId(), tasks.get(3).getProcessInstanceId());
// var = a; var2 = 14
assertEquals(aInstance1.getId(), tasks.get(4).getProcessInstanceId());
// var = b; var2 = 14
assertEquals(bInstance1.getId(), tasks.get(5).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithSecondaryOrderingByProcessInstanceId() {
// given three tasks with String process instance variables
ProcessInstance bInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b"));
ProcessInstance bInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b"));
ProcessInstance cInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c"));
ProcessInstance cInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c"));
ProcessInstance aInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a"));
ProcessInstance aInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.orderByProcessInstanceId()
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = a
verifyTasksSortedByProcessInstanceId(Arrays.asList(aInstance1, aInstance2),
tasks.subList(0, 2));
// var = b
verifyTasksSortedByProcessInstanceId(Arrays.asList(bInstance1, bInstance2),
tasks.subList(2, 4));
// var = c
verifyTasksSortedByProcessInstanceId(Arrays.asList(cInstance1, cInstance2),
tasks.subList(4, 6));
}
public void testQueryResultOrderingWithInvalidParameters() {
try {
taskService.createTaskQuery().orderByProcessVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByExecutionVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByExecutionVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByTaskVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByTaskVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseInstanceVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseInstanceVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseExecutionVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseExecutionVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
}
protected void verifyTasksSortedByProcessInstanceId(List<ProcessInstance> expectedProcessInstances,
List<Task> actualTasks) {
assertEquals(expectedProcessInstances.size(), actualTasks.size());
List<ProcessInstance> instances = new ArrayList<ProcessInstance>(expectedProcessInstances);
Collections.sort(instances, new Comparator<ProcessInstance>() {
public int compare(ProcessInstance p1, ProcessInstance p2) {
return p1.getId().compareTo(p2.getId());
}
});
for (int i = 0; i < instances.size(); i++) {
assertEquals(instances.get(i).getId(), actualTasks.get(i).getProcessInstanceId());
}
}
private void verifyQueryResults(TaskQuery query, int countExpected) {
assertEquals(countExpected, query.list().size());
assertEquals(countExpected, query.count());
if (countExpected == 1) {
assertNotNull(query.singleResult());
} else if (countExpected > 1){
verifySingleResultFails(query);
} else if (countExpected == 0) {
assertNull(query.singleResult());
}
}
private void verifySingleResultFails(TaskQuery query) {
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/oneTaskWithFormKeyProcess.bpmn20.xml"})
public void testInitializeFormKeys() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testProcess");
// if initializeFormKeys
Task task = taskService.createTaskQuery()
.processInstanceId(processInstance.getId())
.initializeFormKeys()
.singleResult();
// then the form key is present
assertEquals("exampleFormKey", task.getFormKey());
// if NOT initializeFormKeys
task = taskService.createTaskQuery()
.processInstanceId(processInstance.getId())
.singleResult();
try {
// then the form key is not retrievable
task.getFormKey();
fail("exception expected.");
} catch (BadUserRequestException e) {
assertEquals("ENGINE-03052 The form key is not initialized. You must call initializeFormKeys() on the task query before you can retrieve the form key.", e.getMessage());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryOrderByProcessVariableInteger() {
ProcessInstance instance500 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 500));
ProcessInstance instance1000 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 1000));
ProcessInstance instance250 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 250));
// asc
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
assertEquals(3, tasks.size());
assertEquals(instance250.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance500.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1000.getId(), tasks.get(2).getProcessInstanceId());
// desc
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.desc()
.list();
assertEquals(3, tasks.size());
assertEquals(instance1000.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance500.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance250.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryOrderByTaskVariableInteger() {
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task500 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
taskService.setVariableLocal(task500.getId(), "var", 500);
Task task250 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
taskService.setVariableLocal(task250.getId(), "var", 250);
Task task1000 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
taskService.setVariableLocal(task1000.getId(), "var", 1000);
// asc
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByTaskVariable("var", ValueType.INTEGER)
.asc()
.list();
assertEquals(3, tasks.size());
assertEquals(task250.getId(), tasks.get(0).getId());
assertEquals(task500.getId(), tasks.get(1).getId());
assertEquals(task1000.getId(), tasks.get(2).getId());
// desc
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.desc()
.list();
assertEquals(3, tasks.size());
assertEquals(task1000.getId(), tasks.get(0).getId());
assertEquals(task500.getId(), tasks.get(1).getId());
assertEquals(task250.getId(), tasks.get(2).getId());
}
public void testQueryByParentTaskId() {
String parentTaskId = "parentTask";
Task parent = taskService.newTask(parentTaskId);
taskService.saveTask(parent);
Task sub1 = taskService.newTask("subTask1");
sub1.setParentTaskId(parentTaskId);
taskService.saveTask(sub1);
Task sub2 = taskService.newTask("subTask2");
sub2.setParentTaskId(parentTaskId);
taskService.saveTask(sub2);
TaskQuery query = taskService.createTaskQuery().taskParentTaskId(parentTaskId);
verifyQueryResults(query, 2);
taskService.deleteTask(parentTaskId, true);
}
public void testExtendTaskQueryList_ProcessDefinitionKeyIn() {
// given
String processDefinitionKey = "invoice";
TaskQuery query = taskService
.createTaskQuery()
.processDefinitionKeyIn(processDefinitionKey);
TaskQuery extendingQuery = taskService.createTaskQuery();
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] processDefinitionKeys = ((TaskQueryImpl) result).getProcessDefinitionKeys();
assertEquals(1, processDefinitionKeys.length);
assertEquals(processDefinitionKey, processDefinitionKeys[0]);
}
public void testExtendingTaskQueryList_ProcessDefinitionKeyIn() {
// given
String processDefinitionKey = "invoice";
TaskQuery query = taskService.createTaskQuery();
TaskQuery extendingQuery = taskService
.createTaskQuery()
.processDefinitionKeyIn(processDefinitionKey);
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] processDefinitionKeys = ((TaskQueryImpl) result).getProcessDefinitionKeys();
assertEquals(1, processDefinitionKeys.length);
assertEquals(processDefinitionKey, processDefinitionKeys[0]);
}
public void testExtendTaskQueryList_TaskDefinitionKeyIn() {
// given
String taskDefinitionKey = "assigneApprover";
TaskQuery query = taskService
.createTaskQuery()
.taskDefinitionKeyIn(taskDefinitionKey);
TaskQuery extendingQuery = taskService.createTaskQuery();
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] key = ((TaskQueryImpl) result).getKeys();
assertEquals(1, key.length);
assertEquals(taskDefinitionKey, key[0]);
}
public void testExtendingTaskQueryList_TaskDefinitionKeyIn() {
// given
String taskDefinitionKey = "assigneApprover";
TaskQuery query = taskService.createTaskQuery();
TaskQuery extendingQuery = taskService
.createTaskQuery()
.taskDefinitionKeyIn(taskDefinitionKey);
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] key = ((TaskQueryImpl) result).getKeys();
assertEquals(1, key.length);
assertEquals(taskDefinitionKey, key[0]);
}
/**
* Generates some test tasks.
* - 6 tasks where kermit is a candidate
* - 1 tasks where gonzo is assignee and kermit and gonzo are candidates
* - 2 tasks assigned to management group
* - 2 tasks assigned to accountancy group
* - 1 task assigned to fozzie and to both the management and accountancy group
*/
private List<String> generateTestTasks() throws Exception {
List<String> ids = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// 6 tasks for kermit
ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
for (int i = 0; i < 6; i++) {
Task task = taskService.newTask();
task.setName("testTask");
task.setDescription("testTask description");
task.setPriority(3);
taskService.saveTask(task);
ids.add(task.getId());
taskService.addCandidateUser(task.getId(), "kermit");
}
ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
// 1 task for gonzo
Task task = taskService.newTask();
task.setName("gonzoTask");
task.setDescription("gonzo description");
task.setPriority(4);
taskService.saveTask(task);
taskService.setAssignee(task.getId(), "gonzo");
taskService.setVariable(task.getId(), "testVar", "someVariable");
taskService.addCandidateUser(task.getId(), "kermit");
taskService.addCandidateUser(task.getId(), "gonzo");
ids.add(task.getId());
ClockUtil.setCurrentTime(sdf.parse("03/03/2003 03:03:03.000"));
// 2 tasks for management group
for (int i = 0; i < 2; i++) {
task = taskService.newTask();
task.setName("managementTask");
task.setPriority(10);
taskService.saveTask(task);
taskService.addCandidateGroup(task.getId(), "management");
ids.add(task.getId());
}
ClockUtil.setCurrentTime(sdf.parse("04/04/2004 04:04:04.000"));
// 2 tasks for accountancy group
for (int i = 0; i < 2; i++) {
task = taskService.newTask();
task.setName("accountancyTask");
task.setName("accountancy description");
taskService.saveTask(task);
taskService.addCandidateGroup(task.getId(), "accountancy");
ids.add(task.getId());
}
ClockUtil.setCurrentTime(sdf.parse("05/05/2005 05:05:05.000"));
// 1 task assigned to management and accountancy group
task = taskService.newTask();
task.setName("managementAndAccountancyTask");
taskService.saveTask(task);
taskService.setAssignee(task.getId(), "fozzie");
taskService.addCandidateGroup(task.getId(), "management");
taskService.addCandidateGroup(task.getId(), "accountancy");
ids.add(task.getId());
return ids;
}
}
| engine/src/test/java/org/camunda/bpm/engine/test/api/task/TaskQueryTest.java | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.task;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.inverted;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByAssignee;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCaseExecutionId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCaseInstanceId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByCreateTime;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByDescription;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByDueDate;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByExecutionId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByFollowUpDate;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskById;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByName;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByPriority;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.taskByProcessInstanceId;
import static org.camunda.bpm.engine.test.api.runtime.TestOrderingUtil.verifySortingAndCount;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.filter.Filter;
import org.camunda.bpm.engine.impl.TaskQueryImpl;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.repository.CaseDefinition;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.engine.runtime.CaseInstance;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.DelegationState;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.FileValue;
/**
* @author Joram Barrez
* @author Frederik Heremans
* @author Falko Menge
*/
public class TaskQueryTest extends PluggableProcessEngineTestCase {
public static final int WORKER_COUNT = 1000;
private List<String> taskIds;
// The range of Oracle's NUMBER field is limited to ~10e+125
// which is below Double.MAX_VALUE, so we only test with the following
// max value
protected static final double MAX_DOUBLE_VALUE = 10E+124;
public void setUp() throws Exception {
identityService.saveUser(identityService.newUser("kermit"));
identityService.saveUser(identityService.newUser("gonzo"));
identityService.saveUser(identityService.newUser("fozzie"));
identityService.saveGroup(identityService.newGroup("management"));
identityService.saveGroup(identityService.newGroup("accountancy"));
identityService.createMembership("kermit", "management");
identityService.createMembership("kermit", "accountancy");
identityService.createMembership("fozzie", "management");
taskIds = generateTestTasks();
}
public void tearDown() throws Exception {
identityService.deleteGroup("accountancy");
identityService.deleteGroup("management");
identityService.deleteUser("fozzie");
identityService.deleteUser("gonzo");
identityService.deleteUser("kermit");
taskService.deleteTasks(taskIds, true);
}
public void tesBasicTaskPropertiesNotNull() {
Task task = taskService.createTaskQuery().taskId(taskIds.get(0)).singleResult();
assertNotNull(task.getDescription());
assertNotNull(task.getId());
assertNotNull(task.getName());
assertNotNull(task.getCreateTime());
}
public void testQueryNoCriteria() {
TaskQuery query = taskService.createTaskQuery();
assertEquals(12, query.count());
assertEquals(12, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByTaskId() {
TaskQuery query = taskService.createTaskQuery().taskId(taskIds.get(0));
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidTaskId() {
TaskQuery query = taskService.createTaskQuery().taskId("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByName() {
TaskQuery query = taskService.createTaskQuery().taskName("testTask");
assertEquals(6, query.list().size());
assertEquals(6, query.count());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByInvalidName() {
TaskQuery query = taskService.createTaskQuery().taskName("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskName(null).singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByNameLike() {
TaskQuery query = taskService.createTaskQuery().taskNameLike("gonzo%");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidNameLike() {
TaskQuery query = taskService.createTaskQuery().taskName("1");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskName(null).singleResult();
fail();
} catch (ProcessEngineException e) { }
}
public void testQueryByDescription() {
TaskQuery query = taskService.createTaskQuery().taskDescription("testTask description");
assertEquals(6, query.list().size());
assertEquals(6, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByInvalidDescription() {
TaskQuery query = taskService.createTaskQuery().taskDescription("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskDescription(null).list();
fail();
} catch (ProcessEngineException e) {
}
}
/**
* CAM-6363
*
* Verify that search by name returns case insensitive results
*/
public void testTaskQueryLookupByNameCaseInsensitive() {
TaskQuery query = taskService.createTaskQuery();
query.taskName("testTask");
List<Task> tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(6));
query = taskService.createTaskQuery();
query.taskName("TeStTaSk");
tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(6));
}
/**
* CAM-6165
*
* Verify that search by name like returns case insensitive results
*/
public void testTaskQueryLookupByNameLikeCaseInsensitive() {
TaskQuery query = taskService.createTaskQuery();
query.taskNameLike("%task%");
List<Task> tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(10));
query = taskService.createTaskQuery();
query.taskNameLike("%Task%");
tasks = query.list();
assertNotNull(tasks);
assertThat(tasks.size(),is(10));
}
public void testQueryByDescriptionLike() {
TaskQuery query = taskService.createTaskQuery().taskDescriptionLike("%gonzo%");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidDescriptionLike() {
TaskQuery query = taskService.createTaskQuery().taskDescriptionLike("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
taskService.createTaskQuery().taskDescriptionLike(null).list();
fail();
} catch (ProcessEngineException e) {
}
}
public void testQueryByPriority() {
TaskQuery query = taskService.createTaskQuery().taskPriority(10);
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
query = taskService.createTaskQuery().taskPriority(100);
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
query = taskService.createTaskQuery().taskMinPriority(50);
assertEquals(3, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(10);
assertEquals(5, query.list().size());
query = taskService.createTaskQuery().taskMaxPriority(10);
assertEquals(9, query.list().size());
query = taskService.createTaskQuery().taskMaxPriority(3);
assertEquals(6, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(50).taskMaxPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskPriority(30).taskMaxPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(30).taskPriority(10);
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskMinPriority(30).taskPriority(20).taskMaxPriority(10);
assertEquals(0, query.list().size());
}
public void testQueryByInvalidPriority() {
try {
taskService.createTaskQuery().taskPriority(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByAssignee() {
TaskQuery query = taskService.createTaskQuery().taskAssignee("gonzo");
assertEquals(1, query.count());
assertEquals(1, query.list().size());
assertNotNull(query.singleResult());
query = taskService.createTaskQuery().taskAssignee("kermit");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
assertNull(query.singleResult());
}
public void testQueryByAssigneeLike() {
TaskQuery query = taskService.createTaskQuery().taskAssigneeLike("gonz%");
assertEquals(1, query.count());
assertEquals(1, query.list().size());
assertNotNull(query.singleResult());
query = taskService.createTaskQuery().taskAssignee("gonz");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
assertNull(query.singleResult());
}
public void testQueryByNullAssignee() {
try {
taskService.createTaskQuery().taskAssignee(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByUnassigned() {
TaskQuery query = taskService.createTaskQuery().taskUnassigned();
assertEquals(10, query.count());
assertEquals(10, query.list().size());
}
public void testQueryByAssigned() {
TaskQuery query = taskService.createTaskQuery().taskAssigned();
assertEquals(2, query.count());
assertEquals(2, query.list().size());
}
public void testQueryByCandidateUser() {
// kermit is candidate for 12 tasks, two of them are already assigned
TaskQuery query = taskService.createTaskQuery().taskCandidateUser("kermit");
assertEquals(10, query.count());
assertEquals(10, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("kermit").includeAssignedTasks();
assertEquals(12, query.count());
assertEquals(12, query.list().size());
// fozzie is candidate for 3 tasks, one of them is already assigned
query = taskService.createTaskQuery().taskCandidateUser("fozzie");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("fozzie").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// gonzo is candidate for one task, which is already assinged
query = taskService.createTaskQuery().taskCandidateUser("gonzo");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateUser("gonzo").includeAssignedTasks();
assertEquals(1, query.count());
assertEquals(1, query.list().size());
}
public void testQueryByNullCandidateUser() {
try {
taskService.createTaskQuery().taskCandidateUser(null).list();
fail();
} catch(ProcessEngineException e) {}
}
public void testQueryByIncludeAssignedTasksWithMissingCandidateUserOrGroup() {
try {
taskService.createTaskQuery().includeAssignedTasks();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByCandidateGroupWithManyThreads() throws Exception{
List <Thread> workers = new ArrayList<Thread>();
final CountDownLatch barrier = new CountDownLatch(WORKER_COUNT + 1);
final List<Exception> errors = new ArrayList<Exception>();
for (int i = 0; i < WORKER_COUNT; i++) {
Thread worker = new Thread() {
@Override
public void run() {
barrier.countDown();
try {
taskService.createTaskQuery().taskCandidateGroup("management").list();
} catch (Exception e) {
errors.add(e);
}
}
};
workers.add(worker);
worker.start();
}
barrier.countDown();
assertThat(errors.size(),is(0));
}
public void testQueryByCandidateGroup() {
// management group is candidate for 3 tasks, one of them is already assigned
TaskQuery query = taskService.createTaskQuery().taskCandidateGroup("management");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("management").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// accountancy group is candidate for 3 tasks, one of them is already assigned
query = taskService.createTaskQuery().taskCandidateGroup("accountancy");
assertEquals(2, query.count());
assertEquals(2, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("accountancy").includeAssignedTasks();
assertEquals(3, query.count());
assertEquals(3, query.list().size());
// sales group is candidate for no tasks
query = taskService.createTaskQuery().taskCandidateGroup("sales");
assertEquals(0, query.count());
assertEquals(0, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroup("sales").includeAssignedTasks();
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testQueryWithCandidateGroups() {
// test withCandidateGroups
TaskQuery query = taskService.createTaskQuery().withCandidateGroups();
assertEquals(4, query.count());
assertEquals(4, query.list().size());
assertEquals(5, query.includeAssignedTasks().count());
assertEquals(5, query.includeAssignedTasks().list().size());
}
public void testQueryWithoutCandidateGroups() {
// test withoutCandidateGroups
TaskQuery query = taskService.createTaskQuery().withoutCandidateGroups();
assertEquals(6, query.count());
assertEquals(6, query.list().size());
assertEquals(7, query.includeAssignedTasks().count());
assertEquals(7, query.includeAssignedTasks().list().size());
}
public void testQueryByNullCandidateGroup() {
try {
taskService.createTaskQuery().taskCandidateGroup(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByCandidateGroupIn() {
List<String> groups = Arrays.asList("management", "accountancy");
TaskQuery query = taskService.createTaskQuery().taskCandidateGroupIn(groups);
assertEquals(4, query.count());
assertEquals(4, query.list().size());
try {
query.singleResult();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroupIn(groups).includeAssignedTasks();
assertEquals(5, query.count());
assertEquals(5, query.list().size());
// Unexisting groups or groups that don't have candidate tasks shouldn't influence other results
groups = Arrays.asList("management", "accountancy", "sales", "unexising");
query = taskService.createTaskQuery().taskCandidateGroupIn(groups);
assertEquals(4, query.count());
assertEquals(4, query.list().size());
// test including assigned tasks
query = taskService.createTaskQuery().taskCandidateGroupIn(groups).includeAssignedTasks();
assertEquals(5, query.count());
assertEquals(5, query.list().size());
}
public void testQueryByNullCandidateGroupIn() {
try {
taskService.createTaskQuery().taskCandidateGroupIn(null).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
try {
taskService.createTaskQuery().taskCandidateGroupIn(new ArrayList<String>()).list();
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
public void testQueryByDelegationState() {
TaskQuery query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(12, query.count());
assertEquals(12, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
String taskId= taskService.createTaskQuery().taskAssignee("gonzo").singleResult().getId();
taskService.delegateTask(taskId, "kermit");
query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(11, query.count());
assertEquals(11, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(1, query.count());
assertEquals(1, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
taskService.resolveTask(taskId);
query = taskService.createTaskQuery().taskDelegationState(null);
assertEquals(11, query.count());
assertEquals(11, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
query = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED);
assertEquals(1, query.count());
assertEquals(1, query.list().size());
}
public void testQueryCreatedOn() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Exact matching of createTime, should result in 6 tasks
Date createTime = sdf.parse("01/01/2001 01:01:01.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedOn(createTime);
assertEquals(6, query.count());
assertEquals(6, query.list().size());
}
public void testQueryCreatedBefore() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Should result in 7 tasks
Date before = sdf.parse("03/02/2002 02:02:02.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedBefore(before);
assertEquals(7, query.count());
assertEquals(7, query.list().size());
before = sdf.parse("01/01/2001 01:01:01.000");
query = taskService.createTaskQuery().taskCreatedBefore(before);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testQueryCreatedAfter() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Should result in 3 tasks
Date after = sdf.parse("03/03/2003 03:03:03.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedAfter(after);
assertEquals(3, query.count());
assertEquals(3, query.list().size());
after = sdf.parse("05/05/2005 05:05:05.000");
query = taskService.createTaskQuery().taskCreatedAfter(after);
assertEquals(0, query.count());
assertEquals(0, query.list().size());
}
public void testCreateTimeCombinations() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Exact matching of createTime, should result in 6 tasks
Date createTime = sdf.parse("01/01/2001 01:01:01.000");
Date oneHourAgo = new Date(createTime.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(createTime.getTime() + 60 * 60 * 1000);
assertEquals(6, taskService.createTaskQuery()
.taskCreatedAfter(oneHourAgo).taskCreatedOn(createTime).taskCreatedBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).count());
assertEquals(0, taskService.createTaskQuery()
.taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKey() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// 1 task should exist with key "taskKey1"
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKey("taskKey1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
// No task should be found with unexisting key
Long count = taskService.createTaskQuery().taskDefinitionKey("unexistingKey").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKeyLike() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// Ends with matching, TaskKey1 and TaskKey123 match
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKeyLike("taskKey1%").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// Starts with matching, TaskKey123 matches
tasks = taskService.createTaskQuery().taskDefinitionKeyLike("%123").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey123", tasks.get(0).getTaskDefinitionKey());
// Contains matching, TaskKey123 matches
tasks = taskService.createTaskQuery().taskDefinitionKeyLike("%Key12%").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey123", tasks.get(0).getTaskDefinitionKey());
// No task should be found with unexisting key
Long count = taskService.createTaskQuery().taskDefinitionKeyLike("%unexistingKey%").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml")
public void testTaskDefinitionKeyIn() throws Exception {
// Start process instance, 2 tasks will be available
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
// 1 Task should be found with TaskKey1
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
// 2 Tasks should be found with TaskKey1 and TaskKey123
tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1", "taskKey123").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// 2 Tasks should be found with TaskKey1, TaskKey123 and UnexistingKey
tasks = taskService.createTaskQuery().taskDefinitionKeyIn("taskKey1", "taskKey123", "unexistingKey").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
assertEquals("taskKey1", tasks.get(0).getTaskDefinitionKey());
assertEquals("taskKey123", tasks.get(1).getTaskDefinitionKey());
// No task should be found with UnexistingKey
Long count = taskService.createTaskQuery().taskDefinitionKeyIn("unexistingKey").count();
assertEquals(0L, count.longValue());
count = taskService.createTaskQuery().taskDefinitionKey("unexistingKey").taskDefinitionKeyIn("taskKey1").count();
assertEquals(0l, count.longValue());
}
@Deployment
public void testTaskVariableValueEquals() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// No task should be found for an unexisting var
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("unexistingVar", "value").count());
// Create a map with a variable for all default types
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("longVar", 928374L);
variables.put("shortVar", (short) 123);
variables.put("integerVar", 1234);
variables.put("stringVar", "stringValue");
variables.put("booleanVar", true);
Date date = Calendar.getInstance().getTime();
variables.put("dateVar", date);
variables.put("nullVar", null);
taskService.setVariablesLocal(task.getId(), variables);
// Test query matches
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("longVar", 928374L).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 123).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 1234).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "stringValue").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", true).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("dateVar", date).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("nullVar", null).count());
// Test query for other values on existing variables
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("longVar", 999L).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 999).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 999).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "999").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", false).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("dateVar", otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("nullVar", "999").count());
// Test query for not equals
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("longVar", 999L).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("shortVar", (short) 999).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("integerVar", 999).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("stringVar", "999").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueNotEquals("booleanVar", false).count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testTaskVariableValueEquals.bpmn20.xml")
public void testTaskVariableValueLike() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("stringVar", "stringValue");
taskService.setVariablesLocal(task.getId(), variables);
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVal%").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngValue").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVal%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVar%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVar").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "%ngVar%").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("stringVar", "stringVal").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLike("nonExistingVar", "string%").count());
// test with null value
try {
taskService.createTaskQuery().taskVariableValueLike("stringVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testTaskVariableValueEquals.bpmn20.xml")
public void testTaskVariableValueCompare() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("numericVar", 928374);
Date date = new GregorianCalendar(2014, 2, 2, 2, 2, 2).getTime();
variables.put("dateVar", date);
variables.put("stringVar", "ab");
variables.put("nullVar", null);
taskService.setVariablesLocal(task.getId(), variables);
// test compare methods with numeric values
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928373).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928375).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("numericVar", 928373).count());
// test compare methods with date values
Date before = new GregorianCalendar(2014, 2, 2, 2, 2, 1).getTime();
Date after = new GregorianCalendar(2014, 2, 2, 2, 2, 3).getTime();
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", before).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", after).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("dateVar", before).count());
//test with string values
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "aa").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThan("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "ba").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThan("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("stringVar", "aa").count());
// test with null value
try {
taskService.createTaskQuery().taskVariableValueGreaterThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test with boolean value
try {
taskService.createTaskQuery().taskVariableValueGreaterThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueGreaterThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test non existing variable
assertEquals(0, taskService.createTaskQuery().taskVariableValueLessThanOrEquals("nonExisting", 123).count());
}
@Deployment
public void testProcessVariableValueEquals() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("longVar", 928374L);
variables.put("shortVar", (short) 123);
variables.put("integerVar", 1234);
variables.put("stringVar", "stringValue");
variables.put("booleanVar", true);
Date date = Calendar.getInstance().getTime();
variables.put("dateVar", date);
variables.put("nullVar", null);
// Start process-instance with all types of variables
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
// Test query matches
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("longVar", 928374L).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("shortVar", (short) 123).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("integerVar", 1234).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("stringVar", "stringValue").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("booleanVar", true).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("dateVar", date).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("nullVar", null).count());
// Test query for other values on existing variables
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("longVar", 999L).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("shortVar", (short) 999).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("integerVar", 999).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("stringVar", "999").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("booleanVar", false).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("dateVar", otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("nullVar", "999").count());
// Test querying for task variables don't match the process-variables
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("longVar", 928374L).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("shortVar", (short) 123).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("integerVar", 1234).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("stringVar", "stringValue").count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("booleanVar", true).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().taskVariableValueEquals("nullVar", null).count());
// Test querying for task variables not equals
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("longVar", 999L).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("shortVar", (short) 999).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("integerVar", 999).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("stringVar", "999").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueNotEquals("booleanVar", false).count());
// and query for the existing variable with NOT shoudl result in nothing found:
assertEquals(0, taskService.createTaskQuery().processVariableValueNotEquals("longVar", 928374L).count());
// Test combination of task-variable and process-variable
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
taskService.setVariableLocal(task.getId(), "taskVar", "theValue");
taskService.setVariableLocal(task.getId(), "longVar", 928374L);
assertEquals(1, taskService.createTaskQuery()
.processVariableValueEquals("longVar", 928374L)
.taskVariableValueEquals("taskVar", "theValue")
.count());
assertEquals(1, taskService.createTaskQuery()
.processVariableValueEquals("longVar", 928374L)
.taskVariableValueEquals("longVar", 928374L)
.count());
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessVariableValueEquals.bpmn20.xml")
public void testProcessVariableValueLike() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("stringVar", "stringValue");
runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVal%").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngValue").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVal%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVar%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVar").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "%ngVar%").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("stringVar", "stringVal").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLike("nonExistingVar", "string%").count());
// test with null value
try {
taskService.createTaskQuery().processVariableValueLike("stringVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
}
@Deployment(resources="org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessVariableValueEquals.bpmn20.xml")
public void testProcessVariableValueCompare() throws Exception {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("numericVar", 928374);
Date date = new GregorianCalendar(2014, 2, 2, 2, 2, 2).getTime();
variables.put("dateVar", date);
variables.put("stringVar", "ab");
variables.put("nullVar", null);
runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
// test compare methods with numeric values
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928373).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928375).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("numericVar", 928373).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928375).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928374).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("numericVar", 928373).count());
// test compare methods with date values
Date before = new GregorianCalendar(2014, 2, 2, 2, 2, 1).getTime();
Date after = new GregorianCalendar(2014, 2, 2, 2, 2, 3).getTime();
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", before).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("dateVar", after).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("dateVar", before).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", after).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", date).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("dateVar", before).count());
//test with string values
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "aa").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThan("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "ba").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("stringVar", "aa").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "ba").count());
assertEquals(1, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "ab").count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("stringVar", "aa").count());
// test with null value
try {
taskService.createTaskQuery().processVariableValueGreaterThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThan("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThanOrEquals("nullVar", null).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test with boolean value
try {
taskService.createTaskQuery().processVariableValueGreaterThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThan("nullVar", true).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
try {
taskService.createTaskQuery().processVariableValueLessThanOrEquals("nullVar", false).count();
fail("expected exception");
} catch (final ProcessEngineException e) {/*OK*/}
// test non existing variable
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThanOrEquals("nonExisting", 123).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testProcessVariableValueEqualsNumber() throws Exception {
// long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123L));
// non-matching long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 12345L));
// short
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 123));
// double
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123.0d));
// integer
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123));
// untyped null (should not match)
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", null));
// typed null (should not match)
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Variables.longValue(null)));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "123"));
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123L)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(123.0d)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue((short) 123)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(null)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testProcessVariableValueNumberComparison() throws Exception {
// long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123L));
// non-matching long
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 12345L));
// short
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 123));
// double
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123.0d));
// integer
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 123));
// untyped null
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", null));
// typed null
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Variables.longValue(null)));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "123"));
assertEquals(4, taskService.createTaskQuery().processVariableValueNotEquals("var", Variables.numberValue(123)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueGreaterThan("var", Variables.numberValue(123)).count());
assertEquals(5, taskService.createTaskQuery().processVariableValueGreaterThanOrEquals("var", Variables.numberValue(123)).count());
assertEquals(0, taskService.createTaskQuery().processVariableValueLessThan("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().processVariableValueLessThanOrEquals("var", Variables.numberValue(123)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testTaskVariableValueEqualsNumber() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("oneTaskProcess").list();
assertEquals(8, tasks.size());
taskService.setVariableLocal(tasks.get(0).getId(), "var", 123L);
taskService.setVariableLocal(tasks.get(1).getId(), "var", 12345L);
taskService.setVariableLocal(tasks.get(2).getId(), "var", (short) 123);
taskService.setVariableLocal(tasks.get(3).getId(), "var", 123.0d);
taskService.setVariableLocal(tasks.get(4).getId(), "var", 123);
taskService.setVariableLocal(tasks.get(5).getId(), "var", null);
taskService.setVariableLocal(tasks.get(6).getId(), "var", Variables.longValue(null));
taskService.setVariableLocal(tasks.get(7).getId(), "var", "123");
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123L)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(123.0d)).count());
assertEquals(4, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue((short) 123)).count());
assertEquals(1, taskService.createTaskQuery().taskVariableValueEquals("var", Variables.numberValue(null)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberMax() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", MAX_DOUBLE_VALUE));
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", Long.MAX_VALUE));
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(MAX_DOUBLE_VALUE)).count());
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(Long.MAX_VALUE)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberLongValueOverflow() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", MAX_DOUBLE_VALUE));
// this results in an overflow
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (long) MAX_DOUBLE_VALUE));
// the query should not find the long variable
assertEquals(1, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(MAX_DOUBLE_VALUE)).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testVariableEqualsNumberNonIntegerDoubleShouldNotMatchInteger() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 42).putValue("var2", 52.4d));
// querying by 42.4 should not match the integer variable 42
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(42.4d)).count());
runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42.4d));
// querying by 52 should not find the double variable 52.4
assertEquals(0, taskService.createTaskQuery().processVariableValueEquals("var", Variables.numberValue(52)).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionId() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionId(processInstance.getProcessDefinitionId()).list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionId("unexisting").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionKey() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("oneTaskProcess").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionKey("unexisting").count());
}
@Deployment(resources = {
"org/camunda/bpm/engine/test/api/task/taskDefinitionProcess.bpmn20.xml",
"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"
})
public void testProcessDefinitionKeyIn() throws Exception {
// Start for each deployed process definition a process instance
runtimeService.startProcessInstanceByKey("taskDefinitionKeyProcess");
runtimeService.startProcessInstanceByKey("oneTaskProcess");
// 1 task should be found with oneTaskProcess
List<Task> tasks = taskService.createTaskQuery().processDefinitionKeyIn("oneTaskProcess").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// 2 Tasks should be found with both process definition keys
tasks = taskService.createTaskQuery()
.processDefinitionKeyIn("oneTaskProcess", "taskDefinitionKeyProcess")
.list();
assertNotNull(tasks);
assertEquals(3, tasks.size());
Set<String> keysFound = new HashSet<String>();
for (Task task : tasks) {
keysFound.add(task.getTaskDefinitionKey());
}
assertTrue(keysFound.contains("taskKey123"));
assertTrue(keysFound.contains("theTask"));
assertTrue(keysFound.contains("taskKey1"));
// 1 Tasks should be found with oneTaskProcess,and NonExistingKey
tasks = taskService.createTaskQuery().processDefinitionKeyIn("oneTaskProcess", "NonExistingKey").orderByTaskName().asc().list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// No task should be found with NonExistingKey
Long count = taskService.createTaskQuery().processDefinitionKeyIn("NonExistingKey").count();
assertEquals(0L, count.longValue());
count = taskService.createTaskQuery()
.processDefinitionKeyIn("oneTaskProcess").processDefinitionKey("NonExistingKey").count();
assertEquals(0L, count.longValue());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionName() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionName("The One Task Process").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionName("unexisting").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessDefinitionNameLike() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
List<Task> tasks = taskService.createTaskQuery().processDefinitionNameLike("The One Task%").list();
assertEquals(1, tasks.size());
assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(0, taskService.createTaskQuery().processDefinitionNameLike("The One Task").count());
assertEquals(0, taskService.createTaskQuery().processDefinitionNameLike("The Other Task%").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKey() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
assertEquals(1, taskService.createTaskQuery().processDefinitionName("The One Task Process").processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(1, taskService.createTaskQuery().processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKey("NON-EXISTING").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKeyIn() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-2");
// 1 task should be found with BUSINESS-KEY-1
List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKeyIn("BUSINESS-KEY-1").list();
assertNotNull(tasks);
assertEquals(1, tasks.size());
assertEquals("theTask", tasks.get(0).getTaskDefinitionKey());
// 2 tasks should be found with BUSINESS-KEY-1 and BUSINESS-KEY-2
tasks = taskService.createTaskQuery()
.processInstanceBusinessKeyIn("BUSINESS-KEY-1", "BUSINESS-KEY-2")
.list();
assertNotNull(tasks);
assertEquals(2, tasks.size());
for (Task task : tasks) {
assertEquals("theTask", task.getTaskDefinitionKey());
}
// 1 tasks should be found with BUSINESS-KEY-1 and NON-EXISTING-KEY
Task task = taskService.createTaskQuery()
.processInstanceBusinessKeyIn("BUSINESS-KEY-1", "NON-EXISTING-KEY")
.singleResult();
assertNotNull(tasks);
assertEquals("theTask", task.getTaskDefinitionKey());
long count = taskService.createTaskQuery().processInstanceBusinessKeyIn("BUSINESS-KEY-1").processInstanceBusinessKey("NON-EXISTING-KEY")
.count();
assertEquals(0l, count);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testProcessInstanceBusinessKeyLike() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess", "BUSINESS-KEY-1");
assertEquals(1, taskService.createTaskQuery().processDefinitionName("The One Task Process").processInstanceBusinessKey("BUSINESS-KEY-1").list().size());
assertEquals(1, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUSINESS-KEY%").list().size());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUSINESS-KEY").count());
assertEquals(0, taskService.createTaskQuery().processInstanceBusinessKeyLike("BUZINESS-KEY%").count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueDate() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setDueDate(dueDate);
taskService.saveTask(task);
assertEquals(1, taskService.createTaskQuery().dueDate(dueDate).count());
Calendar otherDate = Calendar.getInstance();
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().dueDate(otherDate.getTime()).count());
Calendar priorDate = Calendar.getInstance();
priorDate.setTime(dueDate);
priorDate.roll(Calendar.YEAR, -1);
assertEquals(1, taskService.createTaskQuery().dueAfter(priorDate.getTime())
.count());
assertEquals(1, taskService.createTaskQuery()
.dueBefore(otherDate.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueBefore() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Calendar dueDateCal = Calendar.getInstance();
task.setDueDate(dueDateCal.getTime());
taskService.saveTask(task);
Calendar oneHourAgo = Calendar.getInstance();
oneHourAgo.setTime(dueDateCal.getTime());
oneHourAgo.add(Calendar.HOUR, -1);
Calendar oneHourLater = Calendar.getInstance();
oneHourLater.setTime(dueDateCal.getTime());
oneHourLater.add(Calendar.HOUR, 1);
assertEquals(1, taskService.createTaskQuery().dueBefore(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourAgo.getTime()).count());
// Update due-date to null, shouldn't show up anymore in query that matched before
task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
task.setDueDate(null);
taskService.saveTask(task);
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueBefore(oneHourAgo.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueAfter() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Calendar dueDateCal = Calendar.getInstance();
task.setDueDate(dueDateCal.getTime());
taskService.saveTask(task);
Calendar oneHourAgo = Calendar.getInstance();
oneHourAgo.setTime(dueDateCal.getTime());
oneHourAgo.add(Calendar.HOUR, -1);
Calendar oneHourLater = Calendar.getInstance();
oneHourLater.setTime(dueDateCal.getTime());
oneHourLater.add(Calendar.HOUR, 1);
assertEquals(1, taskService.createTaskQuery().dueAfter(oneHourAgo.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater.getTime()).count());
// Update due-date to null, shouldn't show up anymore in query that matched before
task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
task.setDueDate(null);
taskService.saveTask(task);
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater.getTime()).count());
assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourAgo.getTime()).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testTaskDueDateCombinations() throws ParseException {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set due-date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setDueDate(dueDate);
taskService.saveTask(task);
Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
assertEquals(1, taskService.createTaskQuery()
.dueAfter(oneHourAgo).dueDate(dueDate).dueBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.dueAfter(oneHourLater).dueDate(dueDate).dueBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.dueAfter(oneHourLater).dueDate(dueDate).count());
assertEquals(0, taskService.createTaskQuery()
.dueDate(dueDate).dueBefore(oneHourAgo).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testFollowUpDate() throws Exception {
Calendar otherDate = Calendar.getInstance();
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// do not find any task instances with follow up date
assertEquals(0, taskService.createTaskQuery().followUpDate(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId())
// we might have tasks from other test cases - so we limit to the current PI
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// set follow-up date on task
Date followUpDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setFollowUpDate(followUpDate);
taskService.saveTask(task);
assertEquals(followUpDate, taskService.createTaskQuery().taskId(task.getId()).singleResult().getFollowUpDate());
assertEquals(1, taskService.createTaskQuery().followUpDate(followUpDate).count());
otherDate.setTime(followUpDate);
otherDate.add(Calendar.YEAR, 1);
assertEquals(0, taskService.createTaskQuery().followUpDate(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().followUpBefore(otherDate.getTime()).count());
assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId()) //
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().followUpAfter(otherDate.getTime()).count());
otherDate.add(Calendar.YEAR, -2);
assertEquals(1, taskService.createTaskQuery().followUpAfter(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().followUpBefore(otherDate.getTime()).count());
assertEquals(0, taskService.createTaskQuery().processInstanceId(processInstance.getId()) //
.followUpBeforeOrNotExistent(otherDate.getTime()).count());
taskService.complete(task.getId());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testFollowUpDateCombinations() throws ParseException {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
// Set follow-up date on task
Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
task.setFollowUpDate(dueDate);
taskService.saveTask(task);
Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
assertEquals(1, taskService.createTaskQuery()
.followUpAfter(oneHourAgo).followUpDate(dueDate).followUpBefore(oneHourLater).count());
assertEquals(0, taskService.createTaskQuery()
.followUpAfter(oneHourLater).followUpDate(dueDate).followUpBefore(oneHourAgo).count());
assertEquals(0, taskService.createTaskQuery()
.followUpAfter(oneHourLater).followUpDate(dueDate).count());
assertEquals(0, taskService.createTaskQuery()
.followUpDate(dueDate).followUpBefore(oneHourAgo).count());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByActivityInstanceId() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId = runtimeService.getActivityInstance(processInstance.getId())
.getChildActivityInstances()[0].getId();
assertEquals(1, taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId).list().size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByMultipleActivityInstanceIds() throws Exception {
ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId1 = runtimeService.getActivityInstance(processInstance1.getId())
.getChildActivityInstances()[0].getId();
ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
String activityInstanceId2 = runtimeService.getActivityInstance(processInstance2.getId())
.getChildActivityInstances()[0].getId();
List<Task> result1 = taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId1).list();
assertEquals(1, result1.size());
assertEquals(processInstance1.getId(), result1.get(0).getProcessInstanceId());
List<Task> result2 = taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId2).list();
assertEquals(1, result2.size());
assertEquals(processInstance2.getId(), result2.get(0).getProcessInstanceId());
assertEquals(2, taskService.createTaskQuery().activityInstanceIdIn(activityInstanceId1, activityInstanceId2).list().size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"})
public void testQueryByInvalidActivityInstanceId() throws Exception {
runtimeService.startProcessInstanceByKey("oneTaskProcess");
assertEquals(0, taskService.createTaskQuery().activityInstanceIdIn("anInvalidActivityInstanceId").list().size());
}
public void testQueryPaging() {
TaskQuery query = taskService.createTaskQuery().taskCandidateUser("kermit");
assertEquals(10, query.listPage(0, Integer.MAX_VALUE).size());
// Verifying the un-paged results
assertEquals(10, query.count());
assertEquals(10, query.list().size());
// Verifying paged results
assertEquals(2, query.listPage(0, 2).size());
assertEquals(2, query.listPage(2, 2).size());
assertEquals(3, query.listPage(4, 3).size());
assertEquals(1, query.listPage(9, 3).size());
assertEquals(1, query.listPage(9, 1).size());
// Verifying odd usages
assertEquals(0, query.listPage(-1, -1).size());
assertEquals(0, query.listPage(10, 2).size()); // 9 is the last index with a result
assertEquals(10, query.listPage(0, 15).size()); // there are only 10 tasks
}
public void testQuerySorting() {
// default ordering is by id
int expectedCount = 12;
verifySortingAndCount(taskService.createTaskQuery(), expectedCount, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().asc(), expectedCount, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskName().asc(), expectedCount, taskByName());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskPriority().asc(), expectedCount, taskByPriority());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskAssignee().asc(), expectedCount, taskByAssignee());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskDescription().asc(), expectedCount, taskByDescription());
verifySortingAndCount(taskService.createTaskQuery().orderByProcessInstanceId().asc(), expectedCount, taskByProcessInstanceId());
verifySortingAndCount(taskService.createTaskQuery().orderByExecutionId().asc(), expectedCount, taskByExecutionId());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskCreateTime().asc(), expectedCount, taskByCreateTime());
verifySortingAndCount(taskService.createTaskQuery().orderByDueDate().asc(), expectedCount, taskByDueDate());
verifySortingAndCount(taskService.createTaskQuery().orderByFollowUpDate().asc(), expectedCount, taskByFollowUpDate());
verifySortingAndCount(taskService.createTaskQuery().orderByCaseInstanceId().asc(), expectedCount, taskByCaseInstanceId());
verifySortingAndCount(taskService.createTaskQuery().orderByCaseExecutionId().asc(), expectedCount, taskByCaseExecutionId());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().desc(), expectedCount, inverted(taskById()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskName().desc(), expectedCount, inverted(taskByName()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskPriority().desc(), expectedCount, inverted(taskByPriority()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskAssignee().desc(), expectedCount, inverted(taskByAssignee()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskDescription().desc(), expectedCount, inverted(taskByDescription()));
verifySortingAndCount(taskService.createTaskQuery().orderByProcessInstanceId().desc(), expectedCount, inverted(taskByProcessInstanceId()));
verifySortingAndCount(taskService.createTaskQuery().orderByExecutionId().desc(), expectedCount, inverted(taskByExecutionId()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskCreateTime().desc(), expectedCount, inverted(taskByCreateTime()));
verifySortingAndCount(taskService.createTaskQuery().orderByDueDate().desc(), expectedCount, inverted(taskByDueDate()));
verifySortingAndCount(taskService.createTaskQuery().orderByFollowUpDate().desc(), expectedCount, inverted(taskByFollowUpDate()));
verifySortingAndCount(taskService.createTaskQuery().orderByCaseInstanceId().desc(), expectedCount, inverted(taskByCaseInstanceId()));
verifySortingAndCount(taskService.createTaskQuery().orderByCaseExecutionId().desc(), expectedCount, inverted(taskByCaseExecutionId()));
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().taskName("testTask").asc(), 6, taskById());
verifySortingAndCount(taskService.createTaskQuery().orderByTaskId().taskName("testTask").desc(), 6, inverted(taskById()));
}
public void testQuerySortingByNameShouldBeCaseInsensitive() {
// create task with capitalized name
Task task = taskService.newTask("caseSensitiveTestTask");
task.setName("CaseSensitiveTestTask");
taskService.saveTask(task);
// create task filter
Filter filter = filterService.newTaskFilter("taskNameOrdering");
filterService.saveFilter(filter);
List<String> sortedNames = getTaskNamesFromTasks(taskService.createTaskQuery().list());
Collections.sort(sortedNames, String.CASE_INSENSITIVE_ORDER);
// ascending ordering
TaskQuery taskQuery = taskService.createTaskQuery().orderByTaskNameCaseInsensitive().asc();
List<String> ascNames = getTaskNamesFromTasks(taskQuery.list());
assertEquals(sortedNames, ascNames);
// test filter merging
ascNames = getTaskNamesFromTasks(filterService.list(filter.getId(), taskQuery));
assertEquals(sortedNames, ascNames);
// descending ordering
// reverse sorted names to test descending ordering
Collections.reverse(sortedNames);
taskQuery = taskService.createTaskQuery().orderByTaskNameCaseInsensitive().desc();
List<String> descNames = getTaskNamesFromTasks(taskQuery.list());
assertEquals(sortedNames, descNames);
// test filter merging
descNames = getTaskNamesFromTasks(filterService.list(filter.getId(), taskQuery));
assertEquals(sortedNames, descNames);
// delete test task
taskService.deleteTask(task.getId(), true);
// delete filter
filterService.deleteFilter(filter.getId());
}
public void testQueryOrderByTaskName() {
// asc
List<Task> tasks = taskService.createTaskQuery()
.orderByTaskName()
.asc()
.list();
assertEquals(12, tasks.size());
List<String> taskNames = getTaskNamesFromTasks(tasks);
assertEquals("accountancy description", taskNames.get(0));
assertEquals("accountancy description", taskNames.get(1));
assertEquals("gonzoTask", taskNames.get(2));
assertEquals("managementAndAccountancyTask", taskNames.get(3));
assertEquals("managementTask", taskNames.get(4));
assertEquals("managementTask", taskNames.get(5));
assertEquals("testTask", taskNames.get(6));
assertEquals("testTask", taskNames.get(7));
assertEquals("testTask", taskNames.get(8));
assertEquals("testTask", taskNames.get(9));
assertEquals("testTask", taskNames.get(10));
assertEquals("testTask", taskNames.get(11));
// desc
tasks = taskService.createTaskQuery()
.orderByTaskName()
.desc()
.list();
assertEquals(12, tasks.size());
taskNames = getTaskNamesFromTasks(tasks);
assertEquals("testTask", taskNames.get(0));
assertEquals("testTask", taskNames.get(1));
assertEquals("testTask", taskNames.get(2));
assertEquals("testTask", taskNames.get(3));
assertEquals("testTask", taskNames.get(4));
assertEquals("testTask", taskNames.get(5));
assertEquals("managementTask", taskNames.get(6));
assertEquals("managementTask", taskNames.get(7));
assertEquals("managementAndAccountancyTask", taskNames.get(8));
assertEquals("gonzoTask", taskNames.get(9));
assertEquals("accountancy description", taskNames.get(10));
assertEquals("accountancy description", taskNames.get(11));
}
public List<String> getTaskNamesFromTasks(List<Task> tasks) {
List<String> names = new ArrayList<String>();
for (Task task : tasks) {
names.add(task.getName());
}
return names;
}
public void testNativeQuery() {
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(Task.class));
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(TaskEntity.class));
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).list().size());
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class)).count());
assertEquals(144, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + tablePrefix + "ACT_RU_TASK T1, " + tablePrefix + "ACT_RU_TASK T2").count());
// join task and variable instances
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T1, "+managementService.getTableName(VariableInstanceEntity.class)+" V1 WHERE V1.TASK_ID_ = T1.ID_").count());
List<Task> tasks = taskService.createNativeTaskQuery().sql("SELECT T1.* FROM " + managementService.getTableName(Task.class) + " T1, "+managementService.getTableName(VariableInstanceEntity.class)+" V1 WHERE V1.TASK_ID_ = T1.ID_").list();
assertEquals(1, tasks.size());
assertEquals("gonzoTask", tasks.get(0).getName());
// select with distinct
assertEquals(12, taskService.createNativeTaskQuery().sql("SELECT DISTINCT T1.* FROM " + tablePrefix + "ACT_RU_TASK T1").list().size());
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = 'gonzoTask'").count());
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = 'gonzoTask'").list().size());
// use parameters
assertEquals(1, taskService.createNativeTaskQuery().sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = #{taskName}").parameter("taskName", "gonzoTask").count());
}
public void testNativeQueryPaging() {
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(Task.class));
assertEquals(tablePrefix + "ACT_RU_TASK", managementService.getTableName(TaskEntity.class));
assertEquals(5, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).listPage(0, 5).size());
assertEquals(2, taskService.createNativeTaskQuery().sql("SELECT * FROM " + managementService.getTableName(Task.class)).listPage(10, 12).size());
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionId() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionId(caseDefinitionId);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionId() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionId("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionKey() {
String caseDefinitionKey = repositoryService
.createCaseDefinitionQuery()
.singleResult()
.getKey();
caseService
.withCaseDefinitionByKey(caseDefinitionKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionKey(caseDefinitionKey);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionKey() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionKey("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionKey(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionName() {
CaseDefinition caseDefinition = repositoryService
.createCaseDefinitionQuery()
.singleResult();
String caseDefinitionId = caseDefinition.getId();
String caseDefinitionName = caseDefinition.getName();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionName(caseDefinitionName);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionName() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionName("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionName(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseDefinitionNameLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionNameLike("One T%");
verifyQueryResults(query, 1);
query.caseDefinitionNameLike("%Task Case");
verifyQueryResults(query, 1);
query.caseDefinitionNameLike("%Task%");
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseDefinitionNameLike() {
TaskQuery query = taskService.createTaskQuery();
query.caseDefinitionNameLike("invalid");
verifyQueryResults(query, 0);
try {
query.caseDefinitionNameLike(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceId() {
String caseDefinitionId = getCaseDefinitionId();
String caseInstanceId = caseService
.withCaseDefinition(caseDefinitionId)
.create()
.getId();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId(caseInstanceId);
verifyQueryResults(query, 1);
}
@Deployment(resources=
{
"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testQueryByCaseInstanceIdHierarchy.cmmn",
"org/camunda/bpm/engine/test/api/task/TaskQueryTest.testQueryByCaseInstanceIdHierarchy.bpmn20.xml"
})
public void testQueryByCaseInstanceIdHierarchy() {
// given
String caseInstanceId = caseService
.withCaseDefinitionByKey("case")
.create()
.getId();
String processTaskId = caseService
.createCaseExecutionQuery()
.activityId("PI_ProcessTask_1")
.singleResult()
.getId();
// then
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId(caseInstanceId);
verifyQueryResults(query, 2);
for (Task task : query.list()) {
assertEquals(caseInstanceId, task.getCaseInstanceId());
taskService.complete(task.getId());
}
verifyQueryResults(query, 1);
assertEquals(caseInstanceId, query.singleResult().getCaseInstanceId());
taskService.complete(query.singleResult().getId());
verifyQueryResults(query, 0);
}
public void testQueryByInvalidCaseInstanceId() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceId("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceBusinessKey() {
String caseDefinitionId = getCaseDefinitionId();
String businessKey = "aBusinessKey";
caseService
.withCaseDefinition(caseDefinitionId)
.businessKey(businessKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKey(businessKey);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseInstanceBusinessKey() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKey("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceBusinessKey(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByCaseInstanceBusinessKeyLike() {
String caseDefinitionId = getCaseDefinitionId();
String businessKey = "aBusinessKey";
caseService
.withCaseDefinition(caseDefinitionId)
.businessKey(businessKey)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKeyLike("aBus%");
verifyQueryResults(query, 1);
query.caseInstanceBusinessKeyLike("%sinessKey");
verifyQueryResults(query, 1);
query.caseInstanceBusinessKeyLike("%sines%");
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseInstanceBusinessKeyLike() {
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceBusinessKeyLike("invalid");
verifyQueryResults(query, 0);
try {
query.caseInstanceBusinessKeyLike(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn"})
public void testQueryByCaseExecutionId() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.create();
String humanTaskExecutionId = startDefaultCaseExecutionManually();
TaskQuery query = taskService.createTaskQuery();
query.caseExecutionId(humanTaskExecutionId);
verifyQueryResults(query, 1);
}
public void testQueryByInvalidCaseExecutionId() {
TaskQuery query = taskService.createTaskQuery();
query.caseExecutionId("invalid");
verifyQueryResults(query, 0);
try {
query.caseExecutionId(null);
fail("expected exception");
} catch (ProcessEngineException e) {
// OK
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aNullValue", null);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aBooleanValue", true);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableValueEquals() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueEquals() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
/**
* Starts the one deployed case at the point of the manual activity PI_HumanTask_1
* with the given variable.
*/
protected void startDefaultCaseWithVariable(Object variableValue, String variableName) {
String caseDefinitionId = getCaseDefinitionId();
createCaseWithVariable(caseDefinitionId, variableValue, variableName);
}
/**
* @return the case definition id if only one case is deployed.
*/
protected String getCaseDefinitionId() {
String caseDefinitionId = repositoryService
.createCaseDefinitionQuery()
.singleResult()
.getId();
return caseDefinitionId;
}
protected void createCaseWithVariable(String caseDefinitionId, Object variableValue, String variableName) {
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable(variableName, variableValue)
.create();
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aStringValue", "abd");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aBooleanValue", false);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aShortValue", (short) 124);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("anIntegerValue", 457);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aLongValue", (long) 790);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
Date before = new Date(now.getTime() - 100000);
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aDateValue", before);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueNotEquals("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueNotEquals() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
/**
* @return
*/
protected FileValue createDefaultFileValue() {
FileValue fileValue = Variables.fileValue("tst.txt").file("somebytes".getBytes()).create();
return fileValue;
}
/**
* Starts the case execution for oneTaskCase.cmmn<p>
* Only works for testcases, which deploy that process.
*
* @return the execution id for the activity PI_HumanTask_1
*/
protected String startDefaultCaseExecutionManually() {
String humanTaskExecutionId = caseService
.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.singleResult()
.getId();
caseService
.withCaseExecution(humanTaskExecutionId)
.manualStart();
return humanTaskExecutionId;
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueNotEquals() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueNotEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aStringValue", "ab");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aShortValue", (short) 122);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("anIntegerValue", 455);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aLongValue", (long) 788);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date before = new Date(now.getTime() - 100000);
query.caseInstanceVariableValueGreaterThan("aDateValue", before);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThan("aDoubleValue", 1.4);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableGreaterThan() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn"})
public void testQueryByFileCaseInstanceVariableValueGreaterThan() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
startDefaultCaseExecutionManually();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThan(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aStringValue", "ab");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aShortValue", (short) 122);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueGreaterThanOrEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("anIntegerValue", 455);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aLongValue", (long) 788);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date before = new Date(now.getTime() - 100000);
query.caseInstanceVariableValueGreaterThanOrEquals("aDateValue", before);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDoubleValue", 1.4);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueGreaterThanOrEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableGreaterThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueGreaterThanOrEqual() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueGreaterThanOrEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aStringValue", "abd");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aShortValue", (short) 124);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("anIntegerValue", 457);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aLongValue", (long) 790);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date after = new Date(now.getTime() + 100000);
query.caseInstanceVariableValueLessThan("aDateValue", after);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThan("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueLessThan() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableLessThan() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueLessThan() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThan(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aStringValue", "abd");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aStringValue", "abc");
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByBooleanCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aBooleanValue", true)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aBooleanValue", false).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByShortCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aShortValue", (short) 123)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aShortValue", (short) 124);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aShortValue", (short) 123);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByIntegerCaseInstanceVariableValueLessThanOrEquals() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("anIntegerValue", 456)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("anIntegerValue", 457);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("anIntegerValue", 456);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByLongCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aLongValue", (long) 789)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aLongValue", (long) 790);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aLongValue", (long) 789);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDateCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
Date now = new Date();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDateValue", now)
.create();
TaskQuery query = taskService.createTaskQuery();
Date after = new Date(now.getTime() + 100000);
query.caseInstanceVariableValueLessThanOrEquals("aDateValue", after);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDateValue", now);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByDoubleCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aDoubleValue", 1.5)
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDoubleValue", 1.6);
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLessThanOrEquals("aDoubleValue", 1.5);
verifyQueryResults(query, 1);
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByByteArrayCaseInstanceVariableValueLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
byte[] bytes = "somebytes".getBytes();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aByteArrayValue", bytes)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aByteArrayValue", bytes).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryBySerializableCaseInstanceVariableLessThanOrEqual() {
String caseDefinitionId = getCaseDefinitionId();
List<String> serializable = new ArrayList<String>();
serializable.add("one");
serializable.add("two");
serializable.add("three");
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aSerializableValue", serializable)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals("aSerializableValue", serializable).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByFileCaseInstanceVariableValueLessThanOrEqual() {
FileValue fileValue = createDefaultFileValue();
String variableName = "aFileValue";
startDefaultCaseWithVariable(fileValue, variableName);
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLessThanOrEquals(variableName, fileValue).list();
fail();
} catch (ProcessEngineException e) {
assertThat(e.getMessage(), containsString("Variables of type File cannot be used to query"));
}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByNullCaseInstanceVariableValueLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aNullValue", null)
.create();
TaskQuery query = taskService.createTaskQuery();
try {
query.caseInstanceVariableValueLike("aNullValue", null).list();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
public void testQueryByStringCaseInstanceVariableValueLike() {
String caseDefinitionId = getCaseDefinitionId();
caseService
.withCaseDefinition(caseDefinitionId)
.setVariable("aStringValue", "abc")
.create();
TaskQuery query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "ab%");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "%bc");
verifyQueryResults(query, 1);
query = taskService.createTaskQuery();
query.caseInstanceVariableValueLike("aStringValue", "%b%");
verifyQueryResults(query, 1);
}
@Deployment
public void testQueryByVariableInParallelBranch() throws Exception {
runtimeService.startProcessInstanceByKey("parallelGateway");
// when there are two process variables of the same name but different types
Execution task1Execution = runtimeService.createExecutionQuery().activityId("task1").singleResult();
runtimeService.setVariableLocal(task1Execution.getId(), "var", 12345L);
Execution task2Execution = runtimeService.createExecutionQuery().activityId("task2").singleResult();
runtimeService.setVariableLocal(task2Execution.getId(), "var", 12345);
// then the task query should be able to filter by both variables and return both tasks
assertEquals(2, taskService.createTaskQuery().processVariableValueEquals("var", 12345).count());
assertEquals(2, taskService.createTaskQuery().processVariableValueEquals("var", 12345L).count());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByProcessVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
// when I make a task query with ascending variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// then in alphabetical order
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
// when I make a task query with descending variable ordering by String values
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.desc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// then in alphabetical order
assertEquals(instance2.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
// when I make a task query with variable ordering by Integer values
List<Task> unorderedTasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
// then the tasks are in no particular ordering
assertEquals(3, unorderedTasks.size());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testLocalExecutionVariable.bpmn20.xml")
public void testQueryResultOrderingByExecutionVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("parallelGateway",
Collections.<String, Object>singletonMap("var", "cValue"));
// and some local variables on the tasks
Task task1 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
runtimeService.setVariableLocal(task1.getExecutionId(), "var", "cValue");
Task task2 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
runtimeService.setVariableLocal(task2.getExecutionId(), "var", "bValue");
Task task3 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
runtimeService.setVariableLocal(task3.getExecutionId(), "var", "aValue");
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("parallelGateway")
.orderByExecutionVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByTaskVariables() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
// and some local variables on the tasks
Task task1 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
taskService.setVariableLocal(task1.getId(), "var", "cValue");
Task task2 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
taskService.setVariableLocal(task2.getId(), "var", "bValue");
Task task3 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
taskService.setVariableLocal(task3.getId(), "var", "aValue");
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByTaskVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn")
public void testQueryResultOrderingByCaseInstanceVariables() {
// given three tasks with String case instance variables
CaseInstance instance1 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "cValue"));
CaseInstance instance2 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "aValue"));
CaseInstance instance3 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "bValue"));
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.caseDefinitionKey("oneTaskCase")
.orderByCaseInstanceVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance2.getId(), tasks.get(0).getCaseInstanceId());
assertEquals(instance3.getId(), tasks.get(1).getCaseInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getCaseInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/cmmn/oneTaskCaseWithManualActivation.cmmn")
public void testQueryResultOrderingByCaseExecutionVariables() {
// given three tasks with String case instance variables
CaseInstance instance1 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "cValue"));
CaseInstance instance2 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "aValue"));
CaseInstance instance3 = caseService.createCaseInstanceByKey("oneTaskCase",
Collections.<String, Object>singletonMap("var", "bValue"));
// and local case execution variables
CaseExecution caseExecution1 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance1.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution1.getId())
.setVariableLocal("var", "aValue")
.manualStart();
CaseExecution caseExecution2 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance2.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution2.getId())
.setVariableLocal("var", "bValue")
.manualStart();
CaseExecution caseExecution3 = caseService.createCaseExecutionQuery()
.activityId("PI_HumanTask_1")
.caseInstanceId(instance3.getId())
.singleResult();
caseService
.withCaseExecution(caseExecution3.getId())
.setVariableLocal("var", "cValue")
.manualStart();
// when I make a task query with ascending variable ordering by tasks variables
List<Task> tasks = taskService.createTaskQuery()
.caseDefinitionKey("oneTaskCase")
.orderByCaseExecutionVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly by their local variables
assertEquals(3, tasks.size());
assertEquals(instance1.getId(), tasks.get(0).getCaseInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getCaseInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getCaseInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithNullValues() {
// given three tasks with String process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "bValue"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
ProcessInstance instance4 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
Task firstTask = tasks.get(0);
// the null-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance4.getId())) {
// then the others in ascending order
assertEquals(instance3.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(3).getProcessInstanceId());
} else {
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
assertEquals(instance4.getId(), tasks.get(3).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithMixedTypes() {
// given three tasks with String and Integer process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "cValue"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "aValue"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
Task firstTask = tasks.get(0);
// the numeric-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance1.getId())) {
// then the others in ascending order
assertEquals(instance3.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
} else {
assertEquals(instance3.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1.getId(), tasks.get(2).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByStringVariableWithMixedCase() {
// given three tasks with String and Integer process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "a"));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "B"));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "c"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
// first the numeric valued task (since it is treated like null-valued)
assertEquals(instance1.getId(), tasks.get(0).getProcessInstanceId());
// then the others in alphabetical order
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesOfAllPrimitiveTypes() {
// given three tasks with String and Integer process instance variables
ProcessInstance booleanInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", true));
ProcessInstance shortInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", (short) 16));
ProcessInstance longInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 500L));
ProcessInstance intInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 400));
ProcessInstance stringInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", "300"));
ProcessInstance dateInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", new Date(1000L)));
ProcessInstance doubleInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42.5d));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.BOOLEAN)
.asc()
.list();
verifyFirstOrLastTask(tasks, booleanInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.SHORT)
.asc()
.list();
verifyFirstOrLastTask(tasks, shortInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.LONG)
.asc()
.list();
verifyFirstOrLastTask(tasks, longInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
verifyFirstOrLastTask(tasks, intInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
verifyFirstOrLastTask(tasks, stringInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.DATE)
.asc()
.list();
verifyFirstOrLastTask(tasks, dateInstance);
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.DOUBLE)
.asc()
.list();
verifyFirstOrLastTask(tasks, doubleInstance);
}
public void testQueryByUnsupportedValueTypes() {
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.BYTES);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type byte", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.NULL);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type null", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.NUMBER);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type number", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.OBJECT);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type object", e.getMessage());
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", ValueType.FILE);
fail("this type is not supported");
} catch (ProcessEngineException e) {
// happy path
assertTextPresent("Cannot order by variables of type file", e.getMessage());
}
}
/**
* verify that either the first or the last task of the list belong to the given process instance
*/
protected void verifyFirstOrLastTask(List<Task> tasks, ProcessInstance belongingProcessInstance) {
if (tasks.size() == 0) {
fail("no tasks given");
}
int numTasks = tasks.size();
boolean matches = tasks.get(0).getProcessInstanceId().equals(belongingProcessInstance.getId());
matches = matches || tasks.get(numTasks - 1).getProcessInstanceId()
.equals(belongingProcessInstance.getId());
assertTrue("neither first nor last task belong to process instance " + belongingProcessInstance.getId(),
matches);
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithMixedTypesAndSameColumn() {
// given three tasks with Integer and Long process instance variables
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 42));
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 800));
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Collections.<String, Object>singletonMap("var", 500L));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(3, tasks.size());
Task firstTask = tasks.get(0);
// the Long-valued task should be either first or last
if (firstTask.getProcessInstanceId().equals(instance3.getId())) {
// then the others in ascending order
assertEquals(instance1.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(2).getProcessInstanceId());
} else {
assertEquals(instance1.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance2.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance3.getId(), tasks.get(2).getProcessInstanceId());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByTwoVariables() {
// given three tasks with String process instance variables
ProcessInstance bInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b").putValue("var2", 14));
ProcessInstance bInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b").putValue("var2", 30));
ProcessInstance cInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c").putValue("var2", 50));
ProcessInstance cInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c").putValue("var2", 30));
ProcessInstance aInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a").putValue("var2", 14));
ProcessInstance aInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a").putValue("var2", 50));
// when I make a task query with variable primary ordering by var values
// and secondary ordering by var2 values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.desc()
.orderByProcessVariable("var2", ValueType.INTEGER)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = c; var2 = 30
assertEquals(cInstance2.getId(), tasks.get(0).getProcessInstanceId());
// var = c; var2 = 50
assertEquals(cInstance1.getId(), tasks.get(1).getProcessInstanceId());
// var = b; var2 = 14
assertEquals(bInstance1.getId(), tasks.get(2).getProcessInstanceId());
// var = b; var2 = 30
assertEquals(bInstance2.getId(), tasks.get(3).getProcessInstanceId());
// var = a; var2 = 14
assertEquals(aInstance1.getId(), tasks.get(4).getProcessInstanceId());
// var = a; var2 = 50
assertEquals(aInstance2.getId(), tasks.get(5).getProcessInstanceId());
// when I make a task query with variable primary ordering by var2 values
// and secondary ordering by var values
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var2", ValueType.INTEGER)
.desc()
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = a; var2 = 50
assertEquals(aInstance2.getId(), tasks.get(0).getProcessInstanceId());
// var = c; var2 = 50
assertEquals(cInstance1.getId(), tasks.get(1).getProcessInstanceId());
// var = b; var2 = 30
assertEquals(bInstance2.getId(), tasks.get(2).getProcessInstanceId());
// var = c; var2 = 30
assertEquals(cInstance2.getId(), tasks.get(3).getProcessInstanceId());
// var = a; var2 = 14
assertEquals(aInstance1.getId(), tasks.get(4).getProcessInstanceId());
// var = b; var2 = 14
assertEquals(bInstance1.getId(), tasks.get(5).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryResultOrderingByVariablesWithSecondaryOrderingByProcessInstanceId() {
// given three tasks with String process instance variables
ProcessInstance bInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b"));
ProcessInstance bInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "b"));
ProcessInstance cInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c"));
ProcessInstance cInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "c"));
ProcessInstance aInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a"));
ProcessInstance aInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", "a"));
// when I make a task query with variable ordering by String values
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.STRING)
.asc()
.orderByProcessInstanceId()
.asc()
.list();
// then the tasks are ordered correctly
assertEquals(6, tasks.size());
// var = a
verifyTasksSortedByProcessInstanceId(Arrays.asList(aInstance1, aInstance2),
tasks.subList(0, 2));
// var = b
verifyTasksSortedByProcessInstanceId(Arrays.asList(bInstance1, bInstance2),
tasks.subList(2, 4));
// var = c
verifyTasksSortedByProcessInstanceId(Arrays.asList(cInstance1, cInstance2),
tasks.subList(4, 6));
}
public void testQueryResultOrderingWithInvalidParameters() {
try {
taskService.createTaskQuery().orderByProcessVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByProcessVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByExecutionVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByExecutionVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByTaskVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByTaskVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseInstanceVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseInstanceVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseExecutionVariable(null, ValueType.STRING).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
try {
taskService.createTaskQuery().orderByCaseExecutionVariable("var", null).asc().list();
fail("should not succeed");
} catch (NullValueException e) {
// happy path
}
}
protected void verifyTasksSortedByProcessInstanceId(List<ProcessInstance> expectedProcessInstances,
List<Task> actualTasks) {
assertEquals(expectedProcessInstances.size(), actualTasks.size());
List<ProcessInstance> instances = new ArrayList<ProcessInstance>(expectedProcessInstances);
Collections.sort(instances, new Comparator<ProcessInstance>() {
public int compare(ProcessInstance p1, ProcessInstance p2) {
return p1.getId().compareTo(p2.getId());
}
});
for (int i = 0; i < instances.size(); i++) {
assertEquals(instances.get(i).getId(), actualTasks.get(i).getProcessInstanceId());
}
}
private void verifyQueryResults(TaskQuery query, int countExpected) {
assertEquals(countExpected, query.list().size());
assertEquals(countExpected, query.count());
if (countExpected == 1) {
assertNotNull(query.singleResult());
} else if (countExpected > 1){
verifySingleResultFails(query);
} else if (countExpected == 0) {
assertNull(query.singleResult());
}
}
private void verifySingleResultFails(TaskQuery query) {
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
@Deployment(resources={"org/camunda/bpm/engine/test/api/task/oneTaskWithFormKeyProcess.bpmn20.xml"})
public void testInitializeFormKeys() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testProcess");
// if initializeFormKeys
Task task = taskService.createTaskQuery()
.processInstanceId(processInstance.getId())
.initializeFormKeys()
.singleResult();
// then the form key is present
assertEquals("exampleFormKey", task.getFormKey());
// if NOT initializeFormKeys
task = taskService.createTaskQuery()
.processInstanceId(processInstance.getId())
.singleResult();
try {
// then the form key is not retrievable
task.getFormKey();
fail("exception expected.");
} catch (BadUserRequestException e) {
assertEquals("ENGINE-03052 The form key is not initialized. You must call initializeFormKeys() on the task query before you can retrieve the form key.", e.getMessage());
}
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryOrderByProcessVariableInteger() {
ProcessInstance instance500 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 500));
ProcessInstance instance1000 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 1000));
ProcessInstance instance250 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
Variables.createVariables().putValue("var", 250));
// asc
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.asc()
.list();
assertEquals(3, tasks.size());
assertEquals(instance250.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance500.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance1000.getId(), tasks.get(2).getProcessInstanceId());
// desc
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.desc()
.list();
assertEquals(3, tasks.size());
assertEquals(instance1000.getId(), tasks.get(0).getProcessInstanceId());
assertEquals(instance500.getId(), tasks.get(1).getProcessInstanceId());
assertEquals(instance250.getId(), tasks.get(2).getProcessInstanceId());
}
@Deployment(resources = "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml")
public void testQueryOrderByTaskVariableInteger() {
ProcessInstance instance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance instance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
ProcessInstance instance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Task task500 = taskService.createTaskQuery().processInstanceId(instance1.getId()).singleResult();
taskService.setVariableLocal(task500.getId(), "var", 500);
Task task250 = taskService.createTaskQuery().processInstanceId(instance2.getId()).singleResult();
taskService.setVariableLocal(task250.getId(), "var", 250);
Task task1000 = taskService.createTaskQuery().processInstanceId(instance3.getId()).singleResult();
taskService.setVariableLocal(task1000.getId(), "var", 1000);
// asc
List<Task> tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByTaskVariable("var", ValueType.INTEGER)
.asc()
.list();
assertEquals(3, tasks.size());
assertEquals(task250.getId(), tasks.get(0).getId());
assertEquals(task500.getId(), tasks.get(1).getId());
assertEquals(task1000.getId(), tasks.get(2).getId());
// desc
tasks = taskService.createTaskQuery()
.processDefinitionKey("oneTaskProcess")
.orderByProcessVariable("var", ValueType.INTEGER)
.desc()
.list();
assertEquals(3, tasks.size());
assertEquals(task1000.getId(), tasks.get(0).getId());
assertEquals(task500.getId(), tasks.get(1).getId());
assertEquals(task250.getId(), tasks.get(2).getId());
}
public void testQueryByParentTaskId() {
String parentTaskId = "parentTask";
Task parent = taskService.newTask(parentTaskId);
taskService.saveTask(parent);
Task sub1 = taskService.newTask("subTask1");
sub1.setParentTaskId(parentTaskId);
taskService.saveTask(sub1);
Task sub2 = taskService.newTask("subTask2");
sub2.setParentTaskId(parentTaskId);
taskService.saveTask(sub2);
TaskQuery query = taskService.createTaskQuery().taskParentTaskId(parentTaskId);
verifyQueryResults(query, 2);
taskService.deleteTask(parentTaskId, true);
}
public void testExtendTaskQueryList_ProcessDefinitionKeyIn() {
// given
String processDefinitionKey = "invoice";
TaskQuery query = taskService
.createTaskQuery()
.processDefinitionKeyIn(processDefinitionKey);
TaskQuery extendingQuery = taskService.createTaskQuery();
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] processDefinitionKeys = ((TaskQueryImpl) result).getProcessDefinitionKeys();
assertEquals(1, processDefinitionKeys.length);
assertEquals(processDefinitionKey, processDefinitionKeys[0]);
}
public void testExtendingTaskQueryList_ProcessDefinitionKeyIn() {
// given
String processDefinitionKey = "invoice";
TaskQuery query = taskService.createTaskQuery();
TaskQuery extendingQuery = taskService
.createTaskQuery()
.processDefinitionKeyIn(processDefinitionKey);
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] processDefinitionKeys = ((TaskQueryImpl) result).getProcessDefinitionKeys();
assertEquals(1, processDefinitionKeys.length);
assertEquals(processDefinitionKey, processDefinitionKeys[0]);
}
public void testExtendTaskQueryList_TaskDefinitionKeyIn() {
// given
String taskDefinitionKey = "assigneApprover";
TaskQuery query = taskService
.createTaskQuery()
.taskDefinitionKeyIn(taskDefinitionKey);
TaskQuery extendingQuery = taskService.createTaskQuery();
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] key = ((TaskQueryImpl) result).getKeys();
assertEquals(1, key.length);
assertEquals(taskDefinitionKey, key[0]);
}
public void testExtendingTaskQueryList_TaskDefinitionKeyIn() {
// given
String taskDefinitionKey = "assigneApprover";
TaskQuery query = taskService.createTaskQuery();
TaskQuery extendingQuery = taskService
.createTaskQuery()
.taskDefinitionKeyIn(taskDefinitionKey);
// when
TaskQuery result = ((TaskQueryImpl)query).extend(extendingQuery);
// then
String[] key = ((TaskQueryImpl) result).getKeys();
assertEquals(1, key.length);
assertEquals(taskDefinitionKey, key[0]);
}
/**
* Generates some test tasks.
* - 6 tasks where kermit is a candidate
* - 1 tasks where gonzo is assignee and kermit and gonzo are candidates
* - 2 tasks assigned to management group
* - 2 tasks assigned to accountancy group
* - 1 task assigned to fozzie and to both the management and accountancy group
*/
private List<String> generateTestTasks() throws Exception {
List<String> ids = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// 6 tasks for kermit
ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
for (int i = 0; i < 6; i++) {
Task task = taskService.newTask();
task.setName("testTask");
task.setDescription("testTask description");
task.setPriority(3);
taskService.saveTask(task);
ids.add(task.getId());
taskService.addCandidateUser(task.getId(), "kermit");
}
ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
// 1 task for gonzo
Task task = taskService.newTask();
task.setName("gonzoTask");
task.setDescription("gonzo description");
task.setPriority(4);
taskService.saveTask(task);
taskService.setAssignee(task.getId(), "gonzo");
taskService.setVariable(task.getId(), "testVar", "someVariable");
taskService.addCandidateUser(task.getId(), "kermit");
taskService.addCandidateUser(task.getId(), "gonzo");
ids.add(task.getId());
ClockUtil.setCurrentTime(sdf.parse("03/03/2003 03:03:03.000"));
// 2 tasks for management group
for (int i = 0; i < 2; i++) {
task = taskService.newTask();
task.setName("managementTask");
task.setPriority(10);
taskService.saveTask(task);
taskService.addCandidateGroup(task.getId(), "management");
ids.add(task.getId());
}
ClockUtil.setCurrentTime(sdf.parse("04/04/2004 04:04:04.000"));
// 2 tasks for accountancy group
for (int i = 0; i < 2; i++) {
task = taskService.newTask();
task.setName("accountancyTask");
task.setName("accountancy description");
taskService.saveTask(task);
taskService.addCandidateGroup(task.getId(), "accountancy");
ids.add(task.getId());
}
ClockUtil.setCurrentTime(sdf.parse("05/05/2005 05:05:05.000"));
// 1 task assigned to management and accountancy group
task = taskService.newTask();
task.setName("managementAndAccountancyTask");
taskService.saveTask(task);
taskService.setAssignee(task.getId(), "fozzie");
taskService.addCandidateGroup(task.getId(), "management");
taskService.addCandidateGroup(task.getId(), "accountancy");
ids.add(task.getId());
return ids;
}
}
| Revert: chor(engine): add test to verify multithreaded task query is working
| engine/src/test/java/org/camunda/bpm/engine/test/api/task/TaskQueryTest.java | Revert: chor(engine): add test to verify multithreaded task query is working |
|
Java | apache-2.0 | b6aba4ea010244bf5b10f4bdd716d6d3cad7890a | 0 | allotria/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,retomerz/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,consulo/consulo,fnouama/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,fnouama/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fnouama/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,holmes/intellij-community,caot/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,lucafavatella/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,kdwink/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ernestp/consulo,jagguli/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,da1z/intellij-community,asedunov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,robovm/robovm-studio,jagguli/intellij-community,fitermay/intellij-community,semonte/intellij-community,caot/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ernestp/consulo,pwoodworth/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,xfournet/intellij-community,da1z/intellij-community,Distrotech/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,FHannes/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,signed/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ibinti/intellij-community,vladmm/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,tmpgit/intellij-community,signed/intellij-community,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,kool79/intellij-community,fitermay/intellij-community,allotria/intellij-community,caot/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,holmes/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,kool79/intellij-community,xfournet/intellij-community,FHannes/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,signed/intellij-community,supersven/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,samthor/intellij-community,amith01994/intellij-community,izonder/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,holmes/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,kool79/intellij-community,signed/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,caot/intellij-community,ryano144/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,clumsy/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,da1z/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,amith01994/intellij-community,semonte/intellij-community,supersven/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ibinti/intellij-community,slisson/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,semonte/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,diorcety/intellij-community,kool79/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,blademainer/intellij-community,hurricup/intellij-community,supersven/intellij-community,blademainer/intellij-community,amith01994/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,slisson/intellij-community,fnouama/intellij-community,semonte/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,samthor/intellij-community,signed/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ernestp/consulo,slisson/intellij-community,semonte/intellij-community,samthor/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,caot/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,holmes/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,clumsy/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,vladmm/intellij-community,nicolargo/intellij-community,izonder/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ibinti/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,caot/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ernestp/consulo,hurricup/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,consulo/consulo,TangHao1987/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,da1z/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,semonte/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,hurricup/intellij-community,da1z/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,signed/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,retomerz/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fitermay/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,da1z/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,allotria/intellij-community,holmes/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,amith01994/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,semonte/intellij-community,samthor/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,signed/intellij-community,ernestp/consulo,asedunov/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,petteyg/intellij-community,Distrotech/intellij-community,samthor/intellij-community,adedayo/intellij-community,holmes/intellij-community,clumsy/intellij-community,dslomov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fnouama/intellij-community,dslomov/intellij-community,slisson/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,ryano144/intellij-community,holmes/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,dslomov/intellij-community,hurricup/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,adedayo/intellij-community,consulo/consulo,caot/intellij-community,adedayo/intellij-community,da1z/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,signed/intellij-community,supersven/intellij-community,diorcety/intellij-community,holmes/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,da1z/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,allotria/intellij-community,dslomov/intellij-community,samthor/intellij-community,slisson/intellij-community,izonder/intellij-community,Distrotech/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,petteyg/intellij-community,dslomov/intellij-community,robovm/robovm-studio,caot/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,consulo/consulo,FHannes/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,semonte/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ryano144/intellij-community,adedayo/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,FHannes/intellij-community,adedayo/intellij-community,izonder/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,jagguli/intellij-community,samthor/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,supersven/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,semonte/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,allotria/intellij-community,supersven/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,hurricup/intellij-community,izonder/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,slisson/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,consulo/consulo,fitermay/intellij-community,orekyuu/intellij-community,caot/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,robovm/robovm-studio,hurricup/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.platform.templates;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.module.ModuleTypeManager;
import com.intellij.openapi.util.ClearableLazyValue;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import com.intellij.util.ArrayUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.net.HttpConfigurable;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipInputStream;
/**
* @author Dmitry Avdeev
* Date: 11/14/12
*/
public class RemoteTemplatesFactory extends ProjectTemplatesFactory {
private static final String URL = "http://download.jetbrains.com/idea/project_templates/";
private static final String SAMPLES_GALLERY = "Samples Gallery";
private final ClearableLazyValue<MultiMap<String, ProjectTemplate>> myTemplates = new ClearableLazyValue<MultiMap<String, ProjectTemplate>>() {
@NotNull
@Override
protected MultiMap<String, ProjectTemplate> compute() {
return getTemplates();
}
};
@NotNull
@Override
public String[] getGroups() {
myTemplates.drop();
return ArrayUtil.toStringArray(myTemplates.getValue().keySet());
}
@NotNull
@Override
public ProjectTemplate[] createTemplates(String group, WizardContext context) {
Collection<ProjectTemplate> templates = myTemplates.getValue().get(group);
return templates.toArray(new ProjectTemplate[templates.size()]);
}
private static MultiMap<String, ProjectTemplate> getTemplates() {
InputStream stream = null;
HttpURLConnection connection = null;
String code = ApplicationInfo.getInstance().getBuild().getProductCode();
try {
connection = getConnection(code + "_templates.xml");
stream = connection.getInputStream();
String text = StreamUtil.readText(stream, TemplateModuleBuilder.UTF_8);
return createFromText(text);
}
catch (IOException ex) { // timeouts, lost connection etc
LOG.info(ex);
return MultiMap.emptyInstance();
}
catch (Exception e) {
LOG.error(e);
return MultiMap.emptyInstance();
}
finally {
StreamUtil.closeStream(stream);
if (connection != null) {
connection.disconnect();
}
}
}
@SuppressWarnings("unchecked")
public static MultiMap<String, ProjectTemplate> createFromText(String text) throws IOException, JDOMException {
Element rootElement = JDOMUtil.loadDocument(text).getRootElement();
List<Element> groups = rootElement.getChildren("group");
MultiMap<String, ProjectTemplate> map = new MultiMap<String, ProjectTemplate>();
if (groups.isEmpty()) { // sample gallery by default
map.put(SAMPLES_GALLERY, createGroupTemplates(rootElement));
}
else {
for (Element group : groups) {
map.put(group.getChildText("name"), createGroupTemplates(group));
}
}
return map;
}
@SuppressWarnings("unchecked")
private static List<ProjectTemplate> createGroupTemplates(Element groupElement) {
List<Element> elements = groupElement.getChildren("template");
return ContainerUtil.mapNotNull(elements, new NullableFunction<Element, ProjectTemplate>() {
@Override
public ProjectTemplate fun(final Element element) {
List<Element> plugins = element.getChildren("requiredPlugin");
for (Element plugin : plugins) {
String id = plugin.getTextTrim();
if (!PluginManager.isPluginInstalled(PluginId.getId(id))) {
return null;
}
}
String type = element.getChildText("moduleType");
final ModuleType moduleType = ModuleTypeManager.getInstance().findByID(type);
return new ArchivedProjectTemplate(element.getChildTextTrim("name")) {
@Override
protected ModuleType getModuleType() {
return moduleType;
}
@Override
public ZipInputStream getStream() throws IOException {
String path = element.getChildText("path");
final HttpURLConnection connection = getConnection(path);
return new ZipInputStream(connection.getInputStream()) {
@Override
public void close() throws IOException {
super.close();
connection.disconnect();
}
};
}
@Nullable
@Override
public String getDescription() {
return element.getChildTextTrim("description");
}
};
}
});
}
private static HttpURLConnection getConnection(String path) throws IOException {
HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(URL + path);
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
return connection;
}
private final static Logger LOG = Logger.getInstance(RemoteTemplatesFactory.class);
}
| java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.platform.templates;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.module.ModuleTypeManager;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.net.HttpConfigurable;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.zip.ZipInputStream;
/**
* @author Dmitry Avdeev
* Date: 11/14/12
*/
public class RemoteTemplatesFactory extends ProjectTemplatesFactory {
private static final String URL = "http://download.jetbrains.com/idea/project_templates/";
@NotNull
@Override
public String[] getGroups() {
return new String[] { "Samples Gallery"};
}
@NotNull
@Override
public ProjectTemplate[] createTemplates(String group, WizardContext context) {
InputStream stream = null;
HttpURLConnection connection = null;
String code = ApplicationInfo.getInstance().getBuild().getProductCode();
try {
connection = getConnection(code + "_templates.xml");
stream = connection.getInputStream();
String text = StreamUtil.readText(stream);
return createFromText(text);
}
catch (IOException ex) { // timeouts, lost connection etc
LOG.info(ex);
return ProjectTemplate.EMPTY_ARRAY;
}
catch (Exception e) {
LOG.error(e);
return ProjectTemplate.EMPTY_ARRAY;
}
finally {
StreamUtil.closeStream(stream);
if (connection != null) {
connection.disconnect();
}
}
}
@SuppressWarnings("unchecked")
public static ProjectTemplate[] createFromText(String text) throws IOException, JDOMException {
List<Element> elements = JDOMUtil.loadDocument(text).getRootElement().getChildren("template");
List<ProjectTemplate> templates = ContainerUtil.mapNotNull(elements, new NullableFunction<Element, ProjectTemplate>() {
@Override
public ProjectTemplate fun(final Element element) {
List<Element> plugins = element.getChildren("requiredPlugin");
for (Element plugin : plugins) {
String id = plugin.getTextTrim();
if (!PluginManager.isPluginInstalled(PluginId.getId(id))) {
return null;
}
}
String type = element.getChildText("moduleType");
final ModuleType moduleType = ModuleTypeManager.getInstance().findByID(type);
return new ArchivedProjectTemplate(element.getChildTextTrim("name")) {
@Override
protected ModuleType getModuleType() {
return moduleType;
}
@Override
public ZipInputStream getStream() throws IOException {
String path = element.getChildText("path");
final HttpURLConnection connection = getConnection(path);
return new ZipInputStream(connection.getInputStream()) {
@Override
public void close() throws IOException {
super.close();
connection.disconnect();
}
};
}
@Nullable
@Override
public String getDescription() {
return element.getChildTextTrim("description");
}
};
}
});
return templates.toArray(new ProjectTemplate[templates.size()]);
}
private static HttpURLConnection getConnection(String path) throws IOException {
HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(URL + path);
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
return connection;
}
private final static Logger LOG = Logger.getInstance(RemoteTemplatesFactory.class);
}
| support multiple remote groups
| java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java | support multiple remote groups |
|
Java | apache-2.0 | 277279864c933d8494918f6cde475c5d345c95ea | 0 | aldaris/wicket,selckin/wicket,AlienQueen/wicket,zwsong/wicket,mosoft521/wicket,dashorst/wicket,bitstorm/wicket,freiheit-com/wicket,freiheit-com/wicket,astrapi69/wicket,dashorst/wicket,martin-g/wicket-osgi,mosoft521/wicket,AlienQueen/wicket,apache/wicket,mafulafunk/wicket,selckin/wicket,zwsong/wicket,mafulafunk/wicket,klopfdreh/wicket,dashorst/wicket,dashorst/wicket,martin-g/wicket-osgi,klopfdreh/wicket,freiheit-com/wicket,astrapi69/wicket,bitstorm/wicket,topicusonderwijs/wicket,astrapi69/wicket,zwsong/wicket,Servoy/wicket,aldaris/wicket,klopfdreh/wicket,Servoy/wicket,topicusonderwijs/wicket,dashorst/wicket,bitstorm/wicket,AlienQueen/wicket,aldaris/wicket,freiheit-com/wicket,topicusonderwijs/wicket,AlienQueen/wicket,apache/wicket,klopfdreh/wicket,mosoft521/wicket,apache/wicket,AlienQueen/wicket,Servoy/wicket,topicusonderwijs/wicket,Servoy/wicket,freiheit-com/wicket,selckin/wicket,mafulafunk/wicket,bitstorm/wicket,mosoft521/wicket,zwsong/wicket,Servoy/wicket,martin-g/wicket-osgi,apache/wicket,mosoft521/wicket,selckin/wicket,selckin/wicket,aldaris/wicket,aldaris/wicket,bitstorm/wicket,klopfdreh/wicket,topicusonderwijs/wicket,apache/wicket,astrapi69/wicket | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.protocol.http.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.wicket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This filter can be used to make the Wicket
* {@link org.apache.wicket.protocol.http.WebSession} instances available to
* non-wicket servlets.
* </p>
* <p>
* The following example displays how you can make the Wicket session object of
* application SessionApplication, mapped on <code>/sessiontest/*</code>
* available for servlet WicketSessionServlet, mapped under
* <code>/servlet/sessiontest</code>:
*
* <pre>
* <filter>
* <filter-name>WicketSessionFilter</filter-name>
* <filter-class>org.apache.wicket.protocol.http.servlet.WicketSessionFilter</filter-class>
* <init-param>
* <param-name>servletPath</param-name>
* <param-value>sessiontest</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>WicketSessionFilter</filter-name>
* <url-pattern>/servlet/sessiontest</url-pattern>
* </filter-mapping>
*
* <servlet>
* <servlet-name>SessionApplication</servlet-name>
* <servlet-class>org.apache.wicket.protocol.http.WicketServlet</servlet-class>
* <init-param>
* <param-name>applicationClassName</param-name>
* <param-value>session.SessionApplication</param-value>
* </init-param>
* <load-on-startup>1</load-on-startup>
* </servlet>
*
* <servlet>
* <servlet-name>WicketSessionServlet</servlet-name>
* <servlet-class>session.WicketSessionServlet</servlet-class>
* <load-on-startup>1</load-on-startup>
* </servlet>
*
* <servlet-mapping>
* <servlet-name>SessionApplication</servlet-name>
* <url-pattern>/sessiontest/*</url-pattern>
* </servlet-mapping>
*
* <servlet-mapping>
* <servlet-name>WicketSessionServlet</servlet-name>
* <url-pattern>/servlet/sessiontest</url-pattern>
* </servlet-mapping>
* </pre>
*
* After that, you can get to the Wicket session in the usual fashion:
*
* <pre>
* org.apache.wicket.Session wicketSession = org.apache.wicket.Session.get();
* </pre>
*
* </p>
*
* @author Eelco Hillenius
*/
public class WicketSessionFilter implements Filter
{
/** log. */
private static final Logger log = LoggerFactory.getLogger(WicketSessionFilter.class);
private FilterConfig filterConfig;
/** the servlet path. */
private String servletPath;
/** the session key where the Wicket session should be stored. */
private String sessionKey;
/**
* Construct.
*/
public WicketSessionFilter()
{
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
servletPath = filterConfig.getInitParameter("servletPath");
if (servletPath == null)
{
throw new ServletException(
"you must provide init parameter servlet-path if you want to use " +
getClass().getName());
}
if (servletPath.charAt(0) != '/')
{
servletPath = '/' + servletPath;
}
if (log.isDebugEnabled())
{
log.debug("servlet path set to " + servletPath);
}
sessionKey = "wicket:" + servletPath + ":" + Session.SESSION_ATTRIBUTE_NAME;
if (log.isDebugEnabled())
{
log.debug("will use " + sessionKey + " as the session key to get the Wicket session");
}
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
HttpSession httpSession = httpServletRequest.getSession(false);
if (httpSession != null)
{
Session session = (Session)httpSession.getAttribute(sessionKey);
if (session != null)
{
// set the session's threadlocal
Session.set(session);
if (log.isDebugEnabled())
{
log.debug("session " + session + " set as current for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("could not set Wicket session: key " + sessionKey +
" not found in http session for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("could not set Wicket session: no http session was created yet for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
// go on with processing
chain.doFilter(request, response);
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy()
{
}
}
| jdk-1.4/wicket/src/main/java/org/apache/wicket/protocol/http/servlet/WicketSessionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.protocol.http.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.wicket.Application;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This filter can be used to make the Wicket
* {@link org.apache.wicket.protocol.http.WebSession} instances available to
* non-wicket servlets.
* </p>
* <p>
* The following example displays how you can make the Wicket session object of
* application SessionApplication, mapped on <code>/sessiontest/*</code>
* available for servlet WicketSessionServlet, mapped under
* <code>/servlet/sessiontest</code>:
*
* <pre>
* <filter>
* <filter-name>WicketSessionFilter</filter-name>
* <filter-class>org.apache.wicket.protocol.http.servlet.WicketSessionFilter</filter-class>
* <init-param>
* <param-name>servletPath</param-name>
* <param-value>sessiontest</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>WicketSessionFilter</filter-name>
* <url-pattern>/servlet/sessiontest</url-pattern>
* </filter-mapping>
*
* <servlet>
* <servlet-name>SessionApplication</servlet-name>
* <servlet-class>org.apache.wicket.protocol.http.WicketServlet</servlet-class>
* <init-param>
* <param-name>applicationClassName</param-name>
* <param-value>session.SessionApplication</param-value>
* </init-param>
* <load-on-startup>1</load-on-startup>
* </servlet>
*
* <servlet>
* <servlet-name>WicketSessionServlet</servlet-name>
* <servlet-class>session.WicketSessionServlet</servlet-class>
* <load-on-startup>1</load-on-startup>
* </servlet>
*
* <servlet-mapping>
* <servlet-name>SessionApplication</servlet-name>
* <url-pattern>/sessiontest/*</url-pattern>
* </servlet-mapping>
*
* <servlet-mapping>
* <servlet-name>WicketSessionServlet</servlet-name>
* <url-pattern>/servlet/sessiontest</url-pattern>
* </servlet-mapping>
* </pre>
*
* After that, you can get to the Wicket session in the usual fashion:
*
* <pre>
* org.apache.wicket.Session wicketSession = org.apache.wicket.Session.get();
* </pre>
*
* </p>
*
* @author Eelco Hillenius
*/
public class WicketSessionFilter implements Filter
{
/** log. */
private static final Logger log = LoggerFactory.getLogger(WicketSessionFilter.class);
private FilterConfig filterConfig;
/** the servlet path. */
private String servletPath;
/** the session key where the Wicket session should be stored. */
private String sessionKey;
/**
* Construct.
*/
public WicketSessionFilter()
{
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
servletPath = filterConfig.getInitParameter("servletPath");
if (servletPath == null)
{
throw new ServletException(
"you must provide init parameter servlet-path if you want to use " +
getClass().getName());
}
if (servletPath.charAt(0) != '/')
{
servletPath = '/' + servletPath;
}
if (log.isDebugEnabled())
{
log.debug("servlet path set to " + servletPath);
}
sessionKey = "wicket:" + servletPath + ":" + Session.SESSION_ATTRIBUTE_NAME;
if (log.isDebugEnabled())
{
log.debug("will use " + sessionKey + " as the session key to get the Wicket session");
}
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
// set application thread local regarless of whether we can find a
// session
WebApplication webApplication = (WebApplication)filterConfig.getServletContext()
.getAttribute(WebApplication.SERVLET_CONTEXT_APPLICATION_KEY);
if (webApplication != null)
{
Application.set(webApplication);
}
HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
HttpSession httpSession = httpServletRequest.getSession(false);
if (httpSession != null)
{
Session session = (Session)httpSession.getAttribute(sessionKey);
if (session != null)
{
// set the session's threadlocal
Session.set(session);
if (log.isDebugEnabled())
{
log.debug("session " + session + " set as current for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("could not set Wicket session: key " + sessionKey +
" not found in http session for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("could not set Wicket session: no http session was created yet for " +
httpServletRequest.getContextPath() + "," +
httpServletRequest.getServerName());
}
}
// go on with processing
chain.doFilter(request, response);
// clean up
Session.unset();
if (webApplication != null)
{
Application.unset();
}
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy()
{
}
}
| rolled back setting the application thread local. This filter can be improved to use the filter name for configuration. Not worth the effort right now, especially since it would break clients and no-one complained yet.
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@556700 13f79535-47bb-0310-9956-ffa450edef68
| jdk-1.4/wicket/src/main/java/org/apache/wicket/protocol/http/servlet/WicketSessionFilter.java | rolled back setting the application thread local. This filter can be improved to use the filter name for configuration. Not worth the effort right now, especially since it would break clients and no-one complained yet. |
|
Java | apache-2.0 | 6dc2f08918c9ae79e93f4694f8145b401d0677b2 | 0 | kyoren/https-github.com-h2oai-h2o-3,PawarPawan/h2o-v3,printedheart/h2o-3,bospetersen/h2o-3,weaver-viii/h2o-3,weaver-viii/h2o-3,datachand/h2o-3,h2oai/h2o-3,printedheart/h2o-3,junwucs/h2o-3,datachand/h2o-3,datachand/h2o-3,jangorecki/h2o-3,PawarPawan/h2o-v3,kyoren/https-github.com-h2oai-h2o-3,pchmieli/h2o-3,tarasane/h2o-3,tarasane/h2o-3,spennihana/h2o-3,YzPaul3/h2o-3,tarasane/h2o-3,h2oai/h2o-dev,nilbody/h2o-flow,nilbody/h2o-flow,h2oai/h2o-3,bospetersen/h2o-3,junwucs/h2o-3,michalkurka/h2o-3,printedheart/h2o-flow,michalkurka/h2o-3,PawarPawan/h2o-v3,bikash/h2o-dev,mrgloom/h2o-3,pchmieli/h2o-3,nilbody/h2o-3,mrgloom/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,junwucs/h2o-3,h2oai/h2o-dev,madmax983/h2o-3,printedheart/h2o-3,datachand/h2o-3,bospetersen/h2o-3,ChristosChristofidis/h2o-3,brightchen/h2o-3,jangorecki/h2o-3,PawarPawan/h2o-v3,mathemage/h2o-3,mrgloom/h2o-3,madmax983/h2o-3,h2oai/h2o-flow,nilbody/h2o-3,printedheart/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,bikash/h2o-dev,nilbody/h2o-3,madmax983/h2o-3,spennihana/h2o-3,YzPaul3/h2o-3,kyoren/https-github.com-h2oai-h2o-3,brightchen/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,kyoren/https-github.com-h2oai-h2o-3,weaver-viii/h2o-3,brightchen/h2o-3,h2oai/h2o-3,printedheart/h2o-3,h2oai/h2o-dev,mrgloom/h2o-3,h2oai/h2o-3,junwucs/h2o-3,ChristosChristofidis/h2o-3,spennihana/h2o-3,madmax983/h2o-3,h2oai/h2o-dev,weaver-viii/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,ChristosChristofidis/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,brightchen/h2o-3,printedheart/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,junwucs/h2o-3,pchmieli/h2o-3,bikash/h2o-dev,michalkurka/h2o-3,nilbody/h2o-3,mathemage/h2o-3,h2oai/h2o-3,weaver-viii/h2o-3,spennihana/h2o-3,bospetersen/h2o-3,printedheart/h2o-flow,madmax983/h2o-3,junwucs/h2o-flow,bospetersen/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,pchmieli/h2o-3,bikash/h2o-dev,tarasane/h2o-3,weaver-viii/h2o-3,mathemage/h2o-3,datachand/h2o-3,mathemage/h2o-3,h2oai/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,brightchen/h2o-3,madmax983/h2o-3,mathemage/h2o-3,ChristosChristofidis/h2o-3,spennihana/h2o-3,spennihana/h2o-3,kyoren/https-github.com-h2oai-h2o-3,PawarPawan/h2o-v3,PawarPawan/h2o-v3,mrgloom/h2o-3,weaver-viii/h2o-3,nilbody/h2o-3,pchmieli/h2o-3,printedheart/h2o-flow,h2oai/h2o-flow,junwucs/h2o-flow,mathemage/h2o-3,bikash/h2o-dev,nilbody/h2o-3,datachand/h2o-3,ChristosChristofidis/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,nilbody/h2o-flow,jangorecki/h2o-3,printedheart/h2o-3,tarasane/h2o-3,h2oai/h2o-3,h2oai/h2o-3,mrgloom/h2o-3,PawarPawan/h2o-v3,junwucs/h2o-3,tarasane/h2o-3,nilbody/h2o-3,datachand/h2o-3,junwucs/h2o-flow,jangorecki/h2o-3,brightchen/h2o-3,YzPaul3/h2o-3,bikash/h2o-dev,ChristosChristofidis/h2o-3,h2oai/h2o-dev,pchmieli/h2o-3,kyoren/https-github.com-h2oai-h2o-3,ChristosChristofidis/h2o-3,mrgloom/h2o-3,tarasane/h2o-3,pchmieli/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev | package water.api;
import static java.util.Arrays.sort;
import java.util.HashSet;
import water.ConfusionMatrix2;
import water.DKV;
import water.Iced;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.ArrayUtils;
public class AUC extends Iced {
// static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
// static private DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
// private static final String DOC_GET = "AUC";
//
// @API(help = "", required = true, filter = Default.class, json=true)
public Frame actual;
// @API(help="Column of the actual results (will display vertically)", required=true, filter=actualVecSelect.class, json=true)
public Vec vactual;
// class actualVecSelect extends VecClassSelect { actualVecSelect() { super("actual"); } }
// @API(help = "", required = true, filter = Default.class, json=true)
public Frame predict;
// @API(help="Column of the predicted results (will display horizontally)", required=true, filter=predictVecSelect.class, json=true)
public Vec vpredict;
// class predictVecSelect extends VecClassSelect { predictVecSelect() { super("predict"); } }
// @API(help = "Thresholds (optional, e.g. 0:1:0.01 or 0.0,0.2,0.4,0.6,0.8,1.0).", required = false, filter = Default.class, json = true)
private float[] thresholds;
// @API(help = "Threshold criterion", filter = Default.class, json = true)
public ThresholdCriterion threshold_criterion = ThresholdCriterion.maximum_F1;
public enum ThresholdCriterion {
maximum_F1,
maximum_Accuracy,
maximum_Precision,
maximum_Recall,
maximum_Specificity,
minimizing_max_per_class_Error
}
// @API(help="domain of the actual response")
private String [] actual_domain;
// @API(help="AUC (ROC)")
public double AUC;
// @API(help="Gini")
private double Gini;
// @API(help = "Confusion Matrices for all thresholds")
private long[][][] confusion_matrices;
// @API(help = "F1 for all thresholds")
private float[] F1;
// @API(help = "Accuracy for all thresholds")
private float[] accuracy;
// @API(help = "Precision for all thresholds")
private float[] precision;
// @API(help = "Recall for all thresholds")
private float[] recall;
// @API(help = "Specificity for all thresholds")
private float[] specificity;
// @API(help = "Max per class error for all thresholds")
private float[] max_per_class_error;
// @API(help="Threshold criteria")
String[] threshold_criteria;
// @API(help="Optimal thresholds for criteria")
private float[] threshold_for_criteria;
// @API(help="F1 for threshold criteria")
private float[] F1_for_criteria;
// @API(help="Accuracy for threshold criteria")
private float[] accuracy_for_criteria;
// @API(help="Precision for threshold criteria")
private float[] precision_for_criteria;
// @API(help="Recall for threshold criteria")
private float[] recall_for_criteria;
// @API(help="Specificity for threshold criteria")
private float[] specificity_for_criteria;
// @API(help="Maximum per class Error for threshold criteria")
private float[] max_per_class_error_for_criteria;
// @API(help="Confusion Matrices for threshold criteria")
private long[][][] confusion_matrix_for_criteria;
/**
* Clean out large JSON fields. Only keep AUC and Gini. Useful for models that score often.
*/
private void clear() {
actual_domain = null;
threshold_criteria = null;
thresholds = null;
confusion_matrices = null;
F1 = null;
accuracy = null;
precision = null;
recall = null;
specificity = null;
max_per_class_error = null;
threshold_for_criteria = null;
F1_for_criteria = null;
accuracy_for_criteria = null;
precision_for_criteria = null;
recall_for_criteria = null;
specificity_for_criteria = null;
max_per_class_error_for_criteria = null;
confusion_matrix_for_criteria = null;
}
/* Independent on thresholds */
public double AUC() { return AUC; }
private double Gini() { return Gini; }
/* Return the metrics for given criterion */
private double F1(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].F1(); }
private double err(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].err(); }
private double precision(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].precision(); }
private double recall(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].recall(); }
private double specificity(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].specificity(); }
private double accuracy(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].accuracy(); }
private double max_per_class_error(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].max_per_class_error(); }
private float threshold(ThresholdCriterion criter) { return threshold_for_criteria[criter.ordinal()]; }
private long[][] cm(ThresholdCriterion criter) { return confusion_matrix_for_criteria[criter.ordinal()]; }
/* Return the metrics for chosen threshold criterion */
public double F1() { return F1(threshold_criterion); }
public double err() { return err(threshold_criterion); }
private double precision() { return precision(threshold_criterion); }
private double recall() { return recall(threshold_criterion); }
private double specificity() { return specificity(threshold_criterion); }
private double accuracy() { return accuracy(threshold_criterion); }
private double max_per_class_error() { return max_per_class_error(threshold_criterion); }
private float threshold() { return threshold(threshold_criterion); }
public long[][] cm() { return cm(threshold_criterion); }
private ConfusionMatrix2 CM() { return _cms[idxCriter[threshold_criterion.ordinal()]]; }
/* Return the best possible metrics */
private double bestF1() { return F1(ThresholdCriterion.maximum_F1); }
private double bestErr() { return err(ThresholdCriterion.maximum_Accuracy); }
/* Helpers */
private int[] idxCriter;
private double[] _tprs;
private double[] _fprs;
private ConfusionMatrix2[] _cms;
public AUC() {}
/**
* Constructor for algos that make their own CMs
* @param cms ConfusionMatrices
* @param thresh Thresholds
*/
private AUC(ConfusionMatrix2[] cms, float[] thresh) {
this(cms, thresh, null);
}
/**
* Constructor for algos that make their own CMs
* @param cms ConfusionMatrices
* @param thresh Thresholds
* @param domain Domain
*/
private AUC(ConfusionMatrix2[] cms, float[] thresh, String[] domain) {
_cms = cms;
thresholds = thresh;
actual_domain = domain;
assert(_cms.length == thresholds.length):("incompatible lengths of thresholds and confusion matrices: " + _cms.length + " != " + thresholds.length);
// compute AUC and best thresholds
computeAUC();
findBestThresholds();
computeMetrics();
}
// @Override
private void init() throws IllegalArgumentException {
// Input handling
if( vactual==null || vpredict==null )
throw new IllegalArgumentException("Missing vactual or vpredict!");
if (vactual.length() != vpredict.length())
throw new IllegalArgumentException("Both arguments must have the same length!");
if (!vactual.isInt())
throw new IllegalArgumentException("Actual column must be integer class labels!");
if (vpredict.isInt())
throw new IllegalArgumentException("Integer type for vactual. Must be a probability.");
}
// @Override
public void execImpl() {
init();
Vec va = null, vp;
try {
va = vactual.toEnum(); // always returns TransfVec
actual_domain = va.factors();
vp = vpredict;
// The vectors are from different groups => align them, but properly delete it after computation
if (!va.group().equals(vp.group())) {
vp = va.align(vp);
}
// compute thresholds, if not user-given
if (thresholds != null) {
if (_cms == null) sort(thresholds); //otherwise assume that thresholds and CMs are in the same order
if (ArrayUtils.minValue(thresholds) < 0) throw new IllegalArgumentException("Minimum threshold cannot be negative.");
if (ArrayUtils.maxValue(thresholds) > 1) throw new IllegalArgumentException("Maximum threshold cannot be greater than 1.");
} else {
HashSet hs = new HashSet();
final int bins = (int)Math.min(vpredict.length(), 200l);
final long stride = Math.max(vpredict.length() / bins, 1);
for( int i=0; i<bins; ++i) hs.add(new Float(vpredict.at(i*stride))); //data-driven thresholds TODO: use percentiles (from Summary2?)
for (int i=0;i<51;++i) hs.add(new Float(i/50.)); //always add 0.02-spaced thresholds from 0 to 1
// created sorted vector of unique thresholds
thresholds = new float[hs.size()];
int i=0;
for (Object h : hs) {thresholds[i++] = (Float)h; }
sort(thresholds);
}
// compute CMs
if (_cms != null) {
if (_cms.length != thresholds.length) throw new IllegalArgumentException("Number of thresholds differs from number of confusion matrices.");
} else {
AUCTask at = new AUCTask(thresholds).doAll(va,vp);
_cms = at.getCMs();
}
// compute AUC and best thresholds
computeAUC();
findBestThresholds();
computeMetrics();
} finally { // Delete adaptation vectors
if (va!=null) DKV.remove(va._key);
}
}
private static double trapezoid_area(double x1, double x2, double y1, double y2) { return Math.abs(x1-x2)*(y1+y2)/2.; }
private void computeAUC() {
_tprs = new double[_cms.length];
_fprs = new double[_cms.length];
double TPR_pre = 1;
double FPR_pre = 1;
AUC = 0;
for( int t = 0; t < _cms.length; ++t ) {
double TPR = 1 - _cms[t].classErr(1); // =TP/(TP+FN) = true-positive-rate
double FPR = _cms[t].classErr(0); // =FP/(FP+TN) = false-positive-rate
AUC += trapezoid_area(FPR_pre, FPR, TPR_pre, TPR);
TPR_pre = TPR;
FPR_pre = FPR;
_tprs[t] = TPR;
_fprs[t] = FPR;
}
AUC += trapezoid_area(FPR_pre, 0, TPR_pre, 0);
assert(AUC > -1e-5 && AUC < 1.+1e-5); //check numerical sanity
AUC = Math.max(0., Math.min(AUC, 1.)); //clamp to 0...1
Gini = 2*AUC-1;
}
/* return true if a is better than b with respect to criterion criter */
private boolean isBetter(ConfusionMatrix2 a, ConfusionMatrix2 b, ThresholdCriterion criter) {
if (criter == ThresholdCriterion.maximum_F1) {
return (!Double.isNaN(a.F1()) &&
(Double.isNaN(b.F1()) || a.F1() > b.F1()));
} else if (criter == ThresholdCriterion.maximum_Recall) {
return (!Double.isNaN(a.recall()) &&
(Double.isNaN(b.recall()) || a.recall() > b.recall()));
} else if (criter == ThresholdCriterion.maximum_Precision) {
return (!Double.isNaN(a.precision()) &&
(Double.isNaN(b.precision()) || a.precision() > b.precision()));
} else if (criter == ThresholdCriterion.maximum_Accuracy) {
return a.accuracy() > b.accuracy();
} else if (criter == ThresholdCriterion.minimizing_max_per_class_Error) {
return a.max_per_class_error() < b.max_per_class_error();
} else if (criter == ThresholdCriterion.maximum_Specificity) {
return (!Double.isNaN(a.specificity()) &&
(Double.isNaN(b.specificity()) || a.specificity() > b.specificity()));
}
else {
throw new IllegalArgumentException("Unknown threshold criterion.");
}
}
private void findBestThresholds() {
threshold_criteria = new String[ThresholdCriterion.values().length];
int i=0;
HashSet<ThresholdCriterion> hs = new HashSet<>();
for (ThresholdCriterion criter : ThresholdCriterion.values()) {
hs.add(criter);
threshold_criteria[i++] = criter.toString().replace("_", " ");
}
confusion_matrix_for_criteria = new long[hs.size()][][];
idxCriter = new int[hs.size()];
threshold_for_criteria = new float[hs.size()];
F1_for_criteria = new float[hs.size()];
accuracy_for_criteria = new float[hs.size()];
precision_for_criteria = new float[hs.size()];
recall_for_criteria = new float[hs.size()];
specificity_for_criteria = new float[hs.size()];
max_per_class_error_for_criteria = new float[hs.size()];
for (ThresholdCriterion criter : hs) {
final int id = criter.ordinal();
idxCriter[id] = 0;
threshold_for_criteria[id] = thresholds[0];
for(i = 1; i < _cms.length; ++i) {
if (isBetter(_cms[i], _cms[idxCriter[id]], criter)) {
idxCriter[id] = i;
threshold_for_criteria[id] = thresholds[i];
}
}
// Set members for JSON, float to save space
confusion_matrix_for_criteria[id] = _cms[idxCriter[id]]._arr;
F1_for_criteria[id] = (float)_cms[idxCriter[id]].F1();
accuracy_for_criteria[id] = (float)_cms[idxCriter[id]].accuracy();
precision_for_criteria[id] = (float)_cms[idxCriter[id]].precision();
recall_for_criteria[id] = (float)_cms[idxCriter[id]].recall();
specificity_for_criteria[id] = (float)_cms[idxCriter[id]].specificity();
max_per_class_error_for_criteria[id] = (float)_cms[idxCriter[id]].max_per_class_error();
}
}
/**
* Populate requested JSON fields
*/
private void computeMetrics() {
confusion_matrices = new long[_cms.length][][];
if (threshold_criterion == ThresholdCriterion.maximum_F1) F1 = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Accuracy) accuracy = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Precision) precision = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Recall) recall = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Specificity) specificity = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.minimizing_max_per_class_Error) max_per_class_error = new float[_cms.length];
for(int i=0;i<_cms.length;++i) {
confusion_matrices[i] = _cms[i]._arr;
if (threshold_criterion == ThresholdCriterion.maximum_F1) F1[i] = (float)_cms[i].F1();
if (threshold_criterion == ThresholdCriterion.maximum_Accuracy) accuracy[i] = (float)_cms[i].accuracy();
if (threshold_criterion == ThresholdCriterion.maximum_Precision) precision[i] = (float)_cms[i].precision();
if (threshold_criterion == ThresholdCriterion.maximum_Recall) recall[i] = (float)_cms[i].recall();
if (threshold_criterion == ThresholdCriterion.maximum_Specificity) specificity[i] = (float)_cms[i].specificity();
if (threshold_criterion == ThresholdCriterion.minimizing_max_per_class_Error) max_per_class_error[i] = (float)_cms[i].max_per_class_error();
}
}
//@Override private boolean toHTML( StringBuilder sb ) {
// try {
// if (actual_domain == null) actual_domain = new String[]{"false","true"};
// // make local copies to avoid getting clear()'ed out in the middle of printing (can happen for DeepLearning, for example)
// String[] my_actual_domain = actual_domain.clone();
// String[] my_threshold_criteria = threshold_criteria.clone();
// float[] my_threshold_for_criteria = threshold_for_criteria.clone();
// float[] my_thresholds = thresholds.clone();
// ConfusionMatrix2[] my_cms = _cms.clone();
//
// if (my_thresholds == null) return false;
// if (my_threshold_criteria == null) return false;
// if (my_cms == null) return false;
// if (idxCriter == null) return false;
//
// sb.append("<div>");
// DocGen.HTML.section(sb, "Scoring for Binary Classification");
//
// // data for JS
// sb.append("\n<script type=\"text/javascript\">");//</script>");
// sb.append("var cms = [\n");
// for (ConfusionMatrix2 cm : _cms) {
// StringBuilder tmp = new StringBuilder();
// cm.toHTML(tmp, my_actual_domain);
//// sb.append("\t'" + StringEscapeUtils.escapeJavaScript(tmp.toString()) + "',\n"); //FIXME: import org.apache.commons.lang;
// }
// sb.append("];\n");
// sb.append("var criterion = " + threshold_criterion.ordinal() + ";\n"); //which one
// sb.append("var criteria = [");
// for (String c : my_threshold_criteria) sb.append("\"" + c + "\",");
// sb.append(" ];\n");
// sb.append("var thresholds = [");
// for (double t : my_threshold_for_criteria) sb.append((float) t + ",");
// sb.append(" ];\n");
// sb.append("var F1_values = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.F1() + ",");
// sb.append(" ];\n");
// sb.append("var accuracy = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.accuracy() + ",");
// sb.append(" ];\n");
// sb.append("var precision = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.precision() + ",");
// sb.append(" ];\n");
// sb.append("var recall = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.recall() + ",");
// sb.append(" ];\n");
// sb.append("var specificity = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.specificity() + ",");
// sb.append(" ];\n");
// sb.append("var max_per_class_error = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.max_per_class_error() + ",");
// sb.append(" ];\n");
// sb.append("var idxCriter = [");
// for (int i : idxCriter) sb.append(i + ",");
// sb.append(" ];\n");
// sb.append("</script>\n");
//
// // Selection of threshold criterion
// sb.append("\n<div><b>Threshold criterion:</b></div><select id='threshold_select' onchange='set_criterion(this.value, idxCriter[this.value])'>\n");
// for (int i = 0; i < my_threshold_criteria.length; ++i)
// sb.append("\t<option value='" + i + "'" + (i == threshold_criterion.ordinal() ? "selected='selected'" : "") + ">" + my_threshold_criteria[i] + "</option>\n");
// sb.append("</select>\n");
// sb.append("</div>");
//
// DocGen.HTML.arrayHead(sb);
// sb.append("<th>AUC</th>");
// sb.append("<th>Gini</th>");
// sb.append("<th id='threshold_criterion'>Threshold for " + threshold_criterion.toString().replace("_", " ") + "</th>");
// sb.append("<th>F1 </th>");
// sb.append("<th>Accuracy </th>");
// sb.append("<th>Precision </th>");
// sb.append("<th>Recall </th>");
// sb.append("<th>Specificity</th>");
// sb.append("<th>Max per class Error</th>");
// sb.append("<tr class='warning'>");
// sb.append("<td>" + String.format("%.5f", AUC()) + "</td>"
// + "<td>" + String.format("%.5f", Gini()) + "</td>"
// + "<td id='threshold'>" + String.format("%g", threshold()) + "</td>"
// + "<td id='F1_value'>" + String.format("%.7f", F1()) + "</td>"
// + "<td id='accuracy'>" + String.format("%.7f", accuracy()) + "</td>"
// + "<td id='precision'>" + String.format("%.7f", precision()) + "</td>"
// + "<td id='recall'>" + String.format("%.7f", recall()) + "</td>"
// + "<td id='specificity'>" + String.format("%.7f", specificity()) + "</td>"
// + "<td id='max_per_class_error'>" + String.format("%.7f", max_per_class_error()) + "</td>"
// );
// DocGen.HTML.arrayTail(sb);
//// sb.append("<div id='BestConfusionMatrix'>");
//// CM().toHTML(sb, actual_domain);
//// sb.append("</div>");
//
// sb.append("<table><tr><td>");
// plotROC(sb);
// sb.append("</td><td id='ConfusionMatrix'>");
// CM().toHTML(sb, my_actual_domain);
// sb.append("</td></tr>");
// sb.append("<tr><td><h5>Threshold:</h5></div><select id=\"select\" onchange='show_cm(this.value)'>\n");
// for (int i = 0; i < my_cms.length; ++i)
// sb.append("\t<option value='" + i + "'" + (my_thresholds[i] == threshold() ? "selected='selected'" : "") + ">" + my_thresholds[i] + "</option>\n");
// sb.append("</select></td></tr>");
// sb.append("</table>");
//
//
// sb.append("\n<script type=\"text/javascript\">");
// sb.append("function show_cm(i){\n");
// sb.append("\t" + "document.getElementById('ConfusionMatrix').innerHTML = cms[i];\n");
// sb.append("\t" + "document.getElementById('F1_value').innerHTML = F1_values[i];\n");
// sb.append("\t" + "document.getElementById('accuracy').innerHTML = accuracy[i];\n");
// sb.append("\t" + "document.getElementById('precision').innerHTML = precision[i];\n");
// sb.append("\t" + "document.getElementById('recall').innerHTML = recall[i];\n");
// sb.append("\t" + "document.getElementById('specificity').innerHTML = specificity[i];\n");
// sb.append("\t" + "document.getElementById('max_per_class_error').innerHTML = max_per_class_error[i];\n");
// sb.append("\t" + "update(dataset);\n");
// sb.append("}\n");
// sb.append("function set_criterion(i, idx){\n");
// sb.append("\t" + "criterion = i;\n");
//// sb.append("\t" + "document.getElementById('BestConfusionMatrix').innerHTML = cms[idx];\n");
// sb.append("\t" + "document.getElementById('threshold_criterion').innerHTML = \" Threshold for \" + criteria[i];\n");
// sb.append("\t" + "document.getElementById('threshold').innerHTML = thresholds[i];\n");
// sb.append("\t" + "show_cm(idx);\n");
// sb.append("\t" + "document.getElementById(\"select\").selectedIndex = idx;\n");
// sb.append("\t" + "update(dataset);\n");
// sb.append("}\n");
// sb.append("</script>\n");
// return true;
// } catch (Exception ex) {
// return false;
// }
//}
public void toASCII( StringBuilder sb ) {
sb.append(CM().toString());
sb.append("AUC: " + String.format("%.5f", AUC()));
sb.append(", Gini: " + String.format("%.5f", Gini()));
sb.append(", F1: " + String.format("%.5f", F1()));
sb.append(", Accuracy: " + String.format("%.5f", accuracy()));
sb.append(", Precision: " + String.format("%.5f", precision()));
sb.append(", Recall: " + String.format("%.5f", recall()));
sb.append(", Specificity: " + String.format("%.5f", specificity()));
sb.append(", Threshold for " + threshold_criterion.toString().replace("_", " ") + ": " + String.format("%g", threshold()));
sb.append("\n");
}
void plotROC(StringBuilder sb) {
sb.append("<script type=\"text/javascript\" src='/h2o/js/d3.v3.min.js'></script>");
sb.append("<div id=\"ROC\">");
sb.append("<style type=\"text/css\">");
sb.append(".axis path," +
".axis line {\n" +
"fill: none;\n" +
"stroke: black;\n" +
"shape-rendering: crispEdges;\n" +
"}\n" +
".axis text {\n" +
"font-family: sans-serif;\n" +
"font-size: 11px;\n" +
"}\n");
sb.append("</style>");
sb.append("<div id=\"rocCurve\" style=\"display:inline;\">");
sb.append("<script type=\"text/javascript\">");
sb.append("//Width and height\n");
sb.append("var w = 500;\n"+
"var h = 300;\n"+
"var padding = 40;\n"
);
sb.append("var dataset = [");
for(int c = 0; c < _fprs.length; c++) {
assert(_tprs.length == _fprs.length);
if (c == 0) {
sb.append("["+String.valueOf(_fprs[c])+",").append(String.valueOf(_tprs[c])).append("]");
}
sb.append(", ["+String.valueOf(_fprs[c])+",").append(String.valueOf(_tprs[c])).append("]");
}
//diagonal
for(int c = 0; c < 200; c++) {
sb.append(", ["+String.valueOf(c/200.)+",").append(String.valueOf(c/200.)).append("]");
}
sb.append("];\n");
sb.append(
"//Create scale functions\n"+
"var xScale = d3.scale.linear()\n"+
".domain([0, d3.max(dataset, function(d) { return d[0]; })])\n"+
".range([padding, w - padding * 2]);\n"+
"var yScale = d3.scale.linear()"+
".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+
".range([h - padding, padding]);\n"+
"var rScale = d3.scale.linear()"+
".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+
".range([2, 5]);\n"+
"//Define X axis\n"+
"var xAxis = d3.svg.axis()\n"+
".scale(xScale)\n"+
".orient(\"bottom\")\n"+
".ticks(5);\n"+
"//Define Y axis\n"+
"var yAxis = d3.svg.axis()\n"+
".scale(yScale)\n"+
".orient(\"left\")\n"+
".ticks(5);\n"+
"//Create SVG element\n"+
"var svg = d3.select(\"#rocCurve\")\n"+
".append(\"svg\")\n"+
".attr(\"width\", w)\n"+
".attr(\"height\", h);\n"+
"/*"+
"//Create labels\n"+
"svg.selectAll(\"text\")"+
".data(dataset)"+
".enter()"+
".append(\"text\")"+
".text(function(d) {"+
"return d[0] + \",\" + d[1];"+
"})"+
".attr(\"x\", function(d) {"+
"return xScale(d[0]);"+
"})"+
".attr(\"y\", function(d) {"+
"return yScale(d[1]);"+
"})"+
".attr(\"font-family\", \"sans-serif\")"+
".attr(\"font-size\", \"11px\")"+
".attr(\"fill\", \"red\");"+
"*/\n"+
"//Create X axis\n"+
"svg.append(\"g\")"+
".attr(\"class\", \"axis\")"+
".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+
".call(xAxis);\n"+
"//X axis label\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",w/2)"+
".attr(\"y\",h - 5)"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"False Positive Rate\");\n"+
"//Create Y axis\n"+
"svg.append(\"g\")"+
".attr(\"class\", \"axis\")"+
".attr(\"transform\", \"translate(\" + padding + \",0)\")"+
".call(yAxis);\n"+
"//Y axis label\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",150)"+
".attr(\"y\",-5)"+
".attr(\"transform\", \"rotate(90)\")"+
//".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"True Positive Rate\");\n"+
"//Title\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",w/2)"+
".attr(\"y\",padding - 20)"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"ROC\");\n" +
"function update(dataset) {" +
"svg.selectAll(\"circle\").remove();" +
"//Create circles\n"+
"var data = svg.selectAll(\"circle\")"+
".data(dataset);\n"+
"var activeIdx = idxCriter[criterion];\n" +
"data.enter()\n"+
".append(\"circle\")\n"+
".attr(\"cx\", function(d) {\n"+
"return xScale(d[0]);\n"+
"})\n"+
".attr(\"cy\", function(d) {\n"+
"return yScale(d[1]);\n"+
"})\n"+
".attr(\"fill\", function(d,i) {\n"+
" if (document.getElementById(\"select\") != null && i == document.getElementById(\"select\").selectedIndex && i != activeIdx) {\n" +
" return \"blue\"\n" +
" }\n" +
" else if (i == activeIdx) {\n"+
" return \"green\"\n"+
" }\n" +
" else if (d[0] != d[1] || d[0] == 0 || d[1] == 0) {\n"+
" return \"blue\"\n"+
" }\n" +
" else {\n"+
" return \"red\"\n"+
" }\n"+
"})\n"+
".attr(\"r\", function(d,i) {\n"+
" if (document.getElementById(\"select\") != null && i == document.getElementById(\"select\").selectedIndex && i != activeIdx) {\n" +
" return 4\n" +
" }\n" +
" else if (i == activeIdx) {\n"+
" return 6\n"+
" }\n" +
" else if (d[0] != d[1] || d[0] == 0 || d[1] == 0) {\n"+
" return 1.5\n"+
" }\n"+
" else {\n"+
" return 1\n"+
" }\n" +
"})\n" +
".on(\"mouseover\", function(d,i){\n" +
" if(i < " + _fprs.length + ") {" +
" document.getElementById(\"select\").selectedIndex = i\n" +
" show_cm(i)\n" +
" }\n" +
"});\n"+
"data.exit().remove();" +
"}\n" +
"update(dataset);");
sb.append("</script>");
sb.append("</div>");
}
// Compute CMs for different thresholds via MRTask2
private static class AUCTask extends MRTask<AUCTask> {
/* @OUT CMs */ private final ConfusionMatrix2[] getCMs() { return _cms; }
private ConfusionMatrix2[] _cms;
/* IN thresholds */ final private float[] _thresh;
AUCTask(float[] thresh) {
_thresh = thresh.clone();
}
@Override public void map( Chunk ca, Chunk cp ) {
_cms = new ConfusionMatrix2[_thresh.length];
for (int i=0;i<_cms.length;++i)
_cms[i] = new ConfusionMatrix2(2);
final int len = Math.min(ca.len(), cp.len());
for( int i=0; i < len; i++ ) {
if (ca.isNA0(i))
throw new UnsupportedOperationException("Actual class label cannot be a missing value!");
final int a = (int)ca.at80(i); //would be a 0 if double was NaN
assert (a == 0 || a == 1) : "Invalid vactual: must be binary (0 or 1).";
if (cp.isNA0(i)) {
// Log.warn("Skipping predicted NaN."); //some models predict NaN!
continue;
}
for( int t=0; t < _cms.length; t++ ) {
final int p = cp.at0(i)>=_thresh[t]?1:0;
_cms[t].add(a, p);
}
}
}
@Override public void reduce( AUCTask other ) {
for( int i=0; i<_cms.length; ++i) {
_cms[i].add(other._cms[i]);
}
}
}
}
| h2o-core/src/main/java/water/api/AUC.java | package water.api;
import static java.util.Arrays.sort;
import java.util.HashSet;
import water.ConfusionMatrix2;
import water.DKV;
import water.Iced;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.ArrayUtils;
public class AUC extends Iced {
// static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
// static private DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
// private static final String DOC_GET = "AUC";
//
// @API(help = "", required = true, filter = Default.class, json=true)
public Frame actual;
// @API(help="Column of the actual results (will display vertically)", required=true, filter=actualVecSelect.class, json=true)
public Vec vactual;
// class actualVecSelect extends VecClassSelect { actualVecSelect() { super("actual"); } }
// @API(help = "", required = true, filter = Default.class, json=true)
public Frame predict;
// @API(help="Column of the predicted results (will display horizontally)", required=true, filter=predictVecSelect.class, json=true)
public Vec vpredict;
// class predictVecSelect extends VecClassSelect { predictVecSelect() { super("predict"); } }
// @API(help = "Thresholds (optional, e.g. 0:1:0.01 or 0.0,0.2,0.4,0.6,0.8,1.0).", required = false, filter = Default.class, json = true)
private float[] thresholds;
// @API(help = "Threshold criterion", filter = Default.class, json = true)
public ThresholdCriterion threshold_criterion = ThresholdCriterion.maximum_F1;
public enum ThresholdCriterion {
maximum_F1,
maximum_Accuracy,
maximum_Precision,
maximum_Recall,
maximum_Specificity,
minimizing_max_per_class_Error
}
// @API(help="domain of the actual response")
private String [] actual_domain;
// @API(help="AUC (ROC)")
public double AUC;
// @API(help="Gini")
private double Gini;
// @API(help = "Confusion Matrices for all thresholds")
private long[][][] confusion_matrices;
// @API(help = "F1 for all thresholds")
private float[] F1;
// @API(help = "Accuracy for all thresholds")
private float[] accuracy;
// @API(help = "Precision for all thresholds")
private float[] precision;
// @API(help = "Recall for all thresholds")
private float[] recall;
// @API(help = "Specificity for all thresholds")
private float[] specificity;
// @API(help = "Max per class error for all thresholds")
private float[] max_per_class_error;
// @API(help="Threshold criteria")
String[] threshold_criteria;
// @API(help="Optimal thresholds for criteria")
private float[] threshold_for_criteria;
// @API(help="F1 for threshold criteria")
private float[] F1_for_criteria;
// @API(help="Accuracy for threshold criteria")
private float[] accuracy_for_criteria;
// @API(help="Precision for threshold criteria")
private float[] precision_for_criteria;
// @API(help="Recall for threshold criteria")
private float[] recall_for_criteria;
// @API(help="Specificity for threshold criteria")
private float[] specificity_for_criteria;
// @API(help="Maximum per class Error for threshold criteria")
private float[] max_per_class_error_for_criteria;
// @API(help="Confusion Matrices for threshold criteria")
private long[][][] confusion_matrix_for_criteria;
/**
* Clean out large JSON fields. Only keep AUC and Gini. Useful for models that score often.
*/
private void clear() {
actual_domain = null;
threshold_criteria = null;
thresholds = null;
confusion_matrices = null;
F1 = null;
accuracy = null;
precision = null;
recall = null;
specificity = null;
max_per_class_error = null;
threshold_for_criteria = null;
F1_for_criteria = null;
accuracy_for_criteria = null;
precision_for_criteria = null;
recall_for_criteria = null;
specificity_for_criteria = null;
max_per_class_error_for_criteria = null;
confusion_matrix_for_criteria = null;
}
/* Independent on thresholds */
public double AUC() { return AUC; }
private double Gini() { return Gini; }
/* Return the metrics for given criterion */
private double F1(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].F1(); }
private double err(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].err(); }
private double precision(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].precision(); }
private double recall(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].recall(); }
private double specificity(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].specificity(); }
private double accuracy(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].accuracy(); }
private double max_per_class_error(ThresholdCriterion criter) { return _cms[idxCriter[criter.ordinal()]].max_per_class_error(); }
private float threshold(ThresholdCriterion criter) { return threshold_for_criteria[criter.ordinal()]; }
private long[][] cm(ThresholdCriterion criter) { return confusion_matrix_for_criteria[criter.ordinal()]; }
/* Return the metrics for chosen threshold criterion */
public double F1() { return F1(threshold_criterion); }
public double err() { return err(threshold_criterion); }
private double precision() { return precision(threshold_criterion); }
private double recall() { return recall(threshold_criterion); }
private double specificity() { return specificity(threshold_criterion); }
private double accuracy() { return accuracy(threshold_criterion); }
private double max_per_class_error() { return max_per_class_error(threshold_criterion); }
private float threshold() { return threshold(threshold_criterion); }
public long[][] cm() { return cm(threshold_criterion); }
private ConfusionMatrix2 CM() { return _cms[idxCriter[threshold_criterion.ordinal()]]; }
/* Return the best possible metrics */
private double bestF1() { return F1(ThresholdCriterion.maximum_F1); }
private double bestErr() { return err(ThresholdCriterion.maximum_Accuracy); }
/* Helpers */
private int[] idxCriter;
private double[] _tprs;
private double[] _fprs;
private ConfusionMatrix2[] _cms;
public AUC() {}
/**
* Constructor for algos that make their own CMs
* @param cms ConfusionMatrices
* @param thresh Thresholds
*/
private AUC(ConfusionMatrix2[] cms, float[] thresh) {
this(cms, thresh, null);
}
/**
* Constructor for algos that make their own CMs
* @param cms ConfusionMatrices
* @param thresh Thresholds
* @param domain Domain
*/
private AUC(ConfusionMatrix2[] cms, float[] thresh, String[] domain) {
_cms = cms;
thresholds = thresh;
actual_domain = domain;
assert(_cms.length == thresholds.length):("incompatible lengths of thresholds and confusion matrices: " + _cms.length + " != " + thresholds.length);
// compute AUC and best thresholds
computeAUC();
findBestThresholds();
computeMetrics();
}
// @Override
private void init() throws IllegalArgumentException {
// Input handling
if( vactual==null || vpredict==null )
throw new IllegalArgumentException("Missing vactual or vpredict!");
if (vactual.length() != vpredict.length())
throw new IllegalArgumentException("Both arguments must have the same length!");
if (!vactual.isInt())
throw new IllegalArgumentException("Actual column must be integer class labels!");
}
// @Override
public void execImpl() {
init();
Vec va = null, vp;
try {
va = vactual.toEnum(); // always returns TransfVec
actual_domain = va.factors();
vp = vpredict;
// The vectors are from different groups => align them, but properly delete it after computation
if (!va.group().equals(vp.group())) {
vp = va.align(vp);
}
// compute thresholds, if not user-given
if (thresholds != null) {
if (_cms == null) sort(thresholds); //otherwise assume that thresholds and CMs are in the same order
if (ArrayUtils.minValue(thresholds) < 0) throw new IllegalArgumentException("Minimum threshold cannot be negative.");
if (ArrayUtils.maxValue(thresholds) > 1) throw new IllegalArgumentException("Maximum threshold cannot be greater than 1.");
} else {
HashSet hs = new HashSet();
final int bins = (int)Math.min(vpredict.length(), 200l);
final long stride = Math.max(vpredict.length() / bins, 1);
for( int i=0; i<bins; ++i) hs.add(new Float(vpredict.at(i*stride))); //data-driven thresholds TODO: use percentiles (from Summary2?)
for (int i=0;i<51;++i) hs.add(new Float(i/50.)); //always add 0.02-spaced thresholds from 0 to 1
// created sorted vector of unique thresholds
thresholds = new float[hs.size()];
int i=0;
for (Object h : hs) {thresholds[i++] = (Float)h; }
sort(thresholds);
}
// compute CMs
if (_cms != null) {
if (_cms.length != thresholds.length) throw new IllegalArgumentException("Number of thresholds differs from number of confusion matrices.");
} else {
AUCTask at = new AUCTask(thresholds).doAll(va,vp);
_cms = at.getCMs();
}
// compute AUC and best thresholds
computeAUC();
findBestThresholds();
computeMetrics();
} finally { // Delete adaptation vectors
if (va!=null) DKV.remove(va._key);
}
}
private static double trapezoid_area(double x1, double x2, double y1, double y2) { return Math.abs(x1-x2)*(y1+y2)/2.; }
private void computeAUC() {
_tprs = new double[_cms.length];
_fprs = new double[_cms.length];
double TPR_pre = 1;
double FPR_pre = 1;
AUC = 0;
for( int t = 0; t < _cms.length; ++t ) {
double TPR = 1 - _cms[t].classErr(1); // =TP/(TP+FN) = true-positive-rate
double FPR = _cms[t].classErr(0); // =FP/(FP+TN) = false-positive-rate
AUC += trapezoid_area(FPR_pre, FPR, TPR_pre, TPR);
TPR_pre = TPR;
FPR_pre = FPR;
_tprs[t] = TPR;
_fprs[t] = FPR;
}
AUC += trapezoid_area(FPR_pre, 0, TPR_pre, 0);
assert(AUC > -1e-5 && AUC < 1.+1e-5); //check numerical sanity
AUC = Math.max(0., Math.min(AUC, 1.)); //clamp to 0...1
Gini = 2*AUC-1;
}
/* return true if a is better than b with respect to criterion criter */
private boolean isBetter(ConfusionMatrix2 a, ConfusionMatrix2 b, ThresholdCriterion criter) {
if (criter == ThresholdCriterion.maximum_F1) {
return (!Double.isNaN(a.F1()) &&
(Double.isNaN(b.F1()) || a.F1() > b.F1()));
} else if (criter == ThresholdCriterion.maximum_Recall) {
return (!Double.isNaN(a.recall()) &&
(Double.isNaN(b.recall()) || a.recall() > b.recall()));
} else if (criter == ThresholdCriterion.maximum_Precision) {
return (!Double.isNaN(a.precision()) &&
(Double.isNaN(b.precision()) || a.precision() > b.precision()));
} else if (criter == ThresholdCriterion.maximum_Accuracy) {
return a.accuracy() > b.accuracy();
} else if (criter == ThresholdCriterion.minimizing_max_per_class_Error) {
return a.max_per_class_error() < b.max_per_class_error();
} else if (criter == ThresholdCriterion.maximum_Specificity) {
return (!Double.isNaN(a.specificity()) &&
(Double.isNaN(b.specificity()) || a.specificity() > b.specificity()));
}
else {
throw new IllegalArgumentException("Unknown threshold criterion.");
}
}
private void findBestThresholds() {
threshold_criteria = new String[ThresholdCriterion.values().length];
int i=0;
HashSet<ThresholdCriterion> hs = new HashSet<>();
for (ThresholdCriterion criter : ThresholdCriterion.values()) {
hs.add(criter);
threshold_criteria[i++] = criter.toString().replace("_", " ");
}
confusion_matrix_for_criteria = new long[hs.size()][][];
idxCriter = new int[hs.size()];
threshold_for_criteria = new float[hs.size()];
F1_for_criteria = new float[hs.size()];
accuracy_for_criteria = new float[hs.size()];
precision_for_criteria = new float[hs.size()];
recall_for_criteria = new float[hs.size()];
specificity_for_criteria = new float[hs.size()];
max_per_class_error_for_criteria = new float[hs.size()];
for (ThresholdCriterion criter : hs) {
final int id = criter.ordinal();
idxCriter[id] = 0;
threshold_for_criteria[id] = thresholds[0];
for(i = 1; i < _cms.length; ++i) {
if (isBetter(_cms[i], _cms[idxCriter[id]], criter)) {
idxCriter[id] = i;
threshold_for_criteria[id] = thresholds[i];
}
}
// Set members for JSON, float to save space
confusion_matrix_for_criteria[id] = _cms[idxCriter[id]]._arr;
F1_for_criteria[id] = (float)_cms[idxCriter[id]].F1();
accuracy_for_criteria[id] = (float)_cms[idxCriter[id]].accuracy();
precision_for_criteria[id] = (float)_cms[idxCriter[id]].precision();
recall_for_criteria[id] = (float)_cms[idxCriter[id]].recall();
specificity_for_criteria[id] = (float)_cms[idxCriter[id]].specificity();
max_per_class_error_for_criteria[id] = (float)_cms[idxCriter[id]].max_per_class_error();
}
}
/**
* Populate requested JSON fields
*/
private void computeMetrics() {
confusion_matrices = new long[_cms.length][][];
if (threshold_criterion == ThresholdCriterion.maximum_F1) F1 = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Accuracy) accuracy = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Precision) precision = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Recall) recall = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.maximum_Specificity) specificity = new float[_cms.length];
if (threshold_criterion == ThresholdCriterion.minimizing_max_per_class_Error) max_per_class_error = new float[_cms.length];
for(int i=0;i<_cms.length;++i) {
confusion_matrices[i] = _cms[i]._arr;
if (threshold_criterion == ThresholdCriterion.maximum_F1) F1[i] = (float)_cms[i].F1();
if (threshold_criterion == ThresholdCriterion.maximum_Accuracy) accuracy[i] = (float)_cms[i].accuracy();
if (threshold_criterion == ThresholdCriterion.maximum_Precision) precision[i] = (float)_cms[i].precision();
if (threshold_criterion == ThresholdCriterion.maximum_Recall) recall[i] = (float)_cms[i].recall();
if (threshold_criterion == ThresholdCriterion.maximum_Specificity) specificity[i] = (float)_cms[i].specificity();
if (threshold_criterion == ThresholdCriterion.minimizing_max_per_class_Error) max_per_class_error[i] = (float)_cms[i].max_per_class_error();
}
}
//@Override private boolean toHTML( StringBuilder sb ) {
// try {
// if (actual_domain == null) actual_domain = new String[]{"false","true"};
// // make local copies to avoid getting clear()'ed out in the middle of printing (can happen for DeepLearning, for example)
// String[] my_actual_domain = actual_domain.clone();
// String[] my_threshold_criteria = threshold_criteria.clone();
// float[] my_threshold_for_criteria = threshold_for_criteria.clone();
// float[] my_thresholds = thresholds.clone();
// ConfusionMatrix2[] my_cms = _cms.clone();
//
// if (my_thresholds == null) return false;
// if (my_threshold_criteria == null) return false;
// if (my_cms == null) return false;
// if (idxCriter == null) return false;
//
// sb.append("<div>");
// DocGen.HTML.section(sb, "Scoring for Binary Classification");
//
// // data for JS
// sb.append("\n<script type=\"text/javascript\">");//</script>");
// sb.append("var cms = [\n");
// for (ConfusionMatrix2 cm : _cms) {
// StringBuilder tmp = new StringBuilder();
// cm.toHTML(tmp, my_actual_domain);
//// sb.append("\t'" + StringEscapeUtils.escapeJavaScript(tmp.toString()) + "',\n"); //FIXME: import org.apache.commons.lang;
// }
// sb.append("];\n");
// sb.append("var criterion = " + threshold_criterion.ordinal() + ";\n"); //which one
// sb.append("var criteria = [");
// for (String c : my_threshold_criteria) sb.append("\"" + c + "\",");
// sb.append(" ];\n");
// sb.append("var thresholds = [");
// for (double t : my_threshold_for_criteria) sb.append((float) t + ",");
// sb.append(" ];\n");
// sb.append("var F1_values = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.F1() + ",");
// sb.append(" ];\n");
// sb.append("var accuracy = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.accuracy() + ",");
// sb.append(" ];\n");
// sb.append("var precision = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.precision() + ",");
// sb.append(" ];\n");
// sb.append("var recall = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.recall() + ",");
// sb.append(" ];\n");
// sb.append("var specificity = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.specificity() + ",");
// sb.append(" ];\n");
// sb.append("var max_per_class_error = [");
// for (ConfusionMatrix2 my_cm : my_cms) sb.append((float) my_cm.max_per_class_error() + ",");
// sb.append(" ];\n");
// sb.append("var idxCriter = [");
// for (int i : idxCriter) sb.append(i + ",");
// sb.append(" ];\n");
// sb.append("</script>\n");
//
// // Selection of threshold criterion
// sb.append("\n<div><b>Threshold criterion:</b></div><select id='threshold_select' onchange='set_criterion(this.value, idxCriter[this.value])'>\n");
// for (int i = 0; i < my_threshold_criteria.length; ++i)
// sb.append("\t<option value='" + i + "'" + (i == threshold_criterion.ordinal() ? "selected='selected'" : "") + ">" + my_threshold_criteria[i] + "</option>\n");
// sb.append("</select>\n");
// sb.append("</div>");
//
// DocGen.HTML.arrayHead(sb);
// sb.append("<th>AUC</th>");
// sb.append("<th>Gini</th>");
// sb.append("<th id='threshold_criterion'>Threshold for " + threshold_criterion.toString().replace("_", " ") + "</th>");
// sb.append("<th>F1 </th>");
// sb.append("<th>Accuracy </th>");
// sb.append("<th>Precision </th>");
// sb.append("<th>Recall </th>");
// sb.append("<th>Specificity</th>");
// sb.append("<th>Max per class Error</th>");
// sb.append("<tr class='warning'>");
// sb.append("<td>" + String.format("%.5f", AUC()) + "</td>"
// + "<td>" + String.format("%.5f", Gini()) + "</td>"
// + "<td id='threshold'>" + String.format("%g", threshold()) + "</td>"
// + "<td id='F1_value'>" + String.format("%.7f", F1()) + "</td>"
// + "<td id='accuracy'>" + String.format("%.7f", accuracy()) + "</td>"
// + "<td id='precision'>" + String.format("%.7f", precision()) + "</td>"
// + "<td id='recall'>" + String.format("%.7f", recall()) + "</td>"
// + "<td id='specificity'>" + String.format("%.7f", specificity()) + "</td>"
// + "<td id='max_per_class_error'>" + String.format("%.7f", max_per_class_error()) + "</td>"
// );
// DocGen.HTML.arrayTail(sb);
//// sb.append("<div id='BestConfusionMatrix'>");
//// CM().toHTML(sb, actual_domain);
//// sb.append("</div>");
//
// sb.append("<table><tr><td>");
// plotROC(sb);
// sb.append("</td><td id='ConfusionMatrix'>");
// CM().toHTML(sb, my_actual_domain);
// sb.append("</td></tr>");
// sb.append("<tr><td><h5>Threshold:</h5></div><select id=\"select\" onchange='show_cm(this.value)'>\n");
// for (int i = 0; i < my_cms.length; ++i)
// sb.append("\t<option value='" + i + "'" + (my_thresholds[i] == threshold() ? "selected='selected'" : "") + ">" + my_thresholds[i] + "</option>\n");
// sb.append("</select></td></tr>");
// sb.append("</table>");
//
//
// sb.append("\n<script type=\"text/javascript\">");
// sb.append("function show_cm(i){\n");
// sb.append("\t" + "document.getElementById('ConfusionMatrix').innerHTML = cms[i];\n");
// sb.append("\t" + "document.getElementById('F1_value').innerHTML = F1_values[i];\n");
// sb.append("\t" + "document.getElementById('accuracy').innerHTML = accuracy[i];\n");
// sb.append("\t" + "document.getElementById('precision').innerHTML = precision[i];\n");
// sb.append("\t" + "document.getElementById('recall').innerHTML = recall[i];\n");
// sb.append("\t" + "document.getElementById('specificity').innerHTML = specificity[i];\n");
// sb.append("\t" + "document.getElementById('max_per_class_error').innerHTML = max_per_class_error[i];\n");
// sb.append("\t" + "update(dataset);\n");
// sb.append("}\n");
// sb.append("function set_criterion(i, idx){\n");
// sb.append("\t" + "criterion = i;\n");
//// sb.append("\t" + "document.getElementById('BestConfusionMatrix').innerHTML = cms[idx];\n");
// sb.append("\t" + "document.getElementById('threshold_criterion').innerHTML = \" Threshold for \" + criteria[i];\n");
// sb.append("\t" + "document.getElementById('threshold').innerHTML = thresholds[i];\n");
// sb.append("\t" + "show_cm(idx);\n");
// sb.append("\t" + "document.getElementById(\"select\").selectedIndex = idx;\n");
// sb.append("\t" + "update(dataset);\n");
// sb.append("}\n");
// sb.append("</script>\n");
// return true;
// } catch (Exception ex) {
// return false;
// }
//}
public void toASCII( StringBuilder sb ) {
sb.append(CM().toString());
sb.append("AUC: " + String.format("%.5f", AUC()));
sb.append(", Gini: " + String.format("%.5f", Gini()));
sb.append(", F1: " + String.format("%.5f", F1()));
sb.append(", Accuracy: " + String.format("%.5f", accuracy()));
sb.append(", Precision: " + String.format("%.5f", precision()));
sb.append(", Recall: " + String.format("%.5f", recall()));
sb.append(", Specificity: " + String.format("%.5f", specificity()));
sb.append(", Threshold for " + threshold_criterion.toString().replace("_", " ") + ": " + String.format("%g", threshold()));
sb.append("\n");
}
void plotROC(StringBuilder sb) {
sb.append("<script type=\"text/javascript\" src='/h2o/js/d3.v3.min.js'></script>");
sb.append("<div id=\"ROC\">");
sb.append("<style type=\"text/css\">");
sb.append(".axis path," +
".axis line {\n" +
"fill: none;\n" +
"stroke: black;\n" +
"shape-rendering: crispEdges;\n" +
"}\n" +
".axis text {\n" +
"font-family: sans-serif;\n" +
"font-size: 11px;\n" +
"}\n");
sb.append("</style>");
sb.append("<div id=\"rocCurve\" style=\"display:inline;\">");
sb.append("<script type=\"text/javascript\">");
sb.append("//Width and height\n");
sb.append("var w = 500;\n"+
"var h = 300;\n"+
"var padding = 40;\n"
);
sb.append("var dataset = [");
for(int c = 0; c < _fprs.length; c++) {
assert(_tprs.length == _fprs.length);
if (c == 0) {
sb.append("["+String.valueOf(_fprs[c])+",").append(String.valueOf(_tprs[c])).append("]");
}
sb.append(", ["+String.valueOf(_fprs[c])+",").append(String.valueOf(_tprs[c])).append("]");
}
//diagonal
for(int c = 0; c < 200; c++) {
sb.append(", ["+String.valueOf(c/200.)+",").append(String.valueOf(c/200.)).append("]");
}
sb.append("];\n");
sb.append(
"//Create scale functions\n"+
"var xScale = d3.scale.linear()\n"+
".domain([0, d3.max(dataset, function(d) { return d[0]; })])\n"+
".range([padding, w - padding * 2]);\n"+
"var yScale = d3.scale.linear()"+
".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+
".range([h - padding, padding]);\n"+
"var rScale = d3.scale.linear()"+
".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+
".range([2, 5]);\n"+
"//Define X axis\n"+
"var xAxis = d3.svg.axis()\n"+
".scale(xScale)\n"+
".orient(\"bottom\")\n"+
".ticks(5);\n"+
"//Define Y axis\n"+
"var yAxis = d3.svg.axis()\n"+
".scale(yScale)\n"+
".orient(\"left\")\n"+
".ticks(5);\n"+
"//Create SVG element\n"+
"var svg = d3.select(\"#rocCurve\")\n"+
".append(\"svg\")\n"+
".attr(\"width\", w)\n"+
".attr(\"height\", h);\n"+
"/*"+
"//Create labels\n"+
"svg.selectAll(\"text\")"+
".data(dataset)"+
".enter()"+
".append(\"text\")"+
".text(function(d) {"+
"return d[0] + \",\" + d[1];"+
"})"+
".attr(\"x\", function(d) {"+
"return xScale(d[0]);"+
"})"+
".attr(\"y\", function(d) {"+
"return yScale(d[1]);"+
"})"+
".attr(\"font-family\", \"sans-serif\")"+
".attr(\"font-size\", \"11px\")"+
".attr(\"fill\", \"red\");"+
"*/\n"+
"//Create X axis\n"+
"svg.append(\"g\")"+
".attr(\"class\", \"axis\")"+
".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+
".call(xAxis);\n"+
"//X axis label\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",w/2)"+
".attr(\"y\",h - 5)"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"False Positive Rate\");\n"+
"//Create Y axis\n"+
"svg.append(\"g\")"+
".attr(\"class\", \"axis\")"+
".attr(\"transform\", \"translate(\" + padding + \",0)\")"+
".call(yAxis);\n"+
"//Y axis label\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",150)"+
".attr(\"y\",-5)"+
".attr(\"transform\", \"rotate(90)\")"+
//".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"True Positive Rate\");\n"+
"//Title\n"+
"d3.select('#rocCurve svg')"+
".append(\"text\")"+
".attr(\"x\",w/2)"+
".attr(\"y\",padding - 20)"+
".attr(\"text-anchor\", \"middle\")"+
".text(\"ROC\");\n" +
"function update(dataset) {" +
"svg.selectAll(\"circle\").remove();" +
"//Create circles\n"+
"var data = svg.selectAll(\"circle\")"+
".data(dataset);\n"+
"var activeIdx = idxCriter[criterion];\n" +
"data.enter()\n"+
".append(\"circle\")\n"+
".attr(\"cx\", function(d) {\n"+
"return xScale(d[0]);\n"+
"})\n"+
".attr(\"cy\", function(d) {\n"+
"return yScale(d[1]);\n"+
"})\n"+
".attr(\"fill\", function(d,i) {\n"+
" if (document.getElementById(\"select\") != null && i == document.getElementById(\"select\").selectedIndex && i != activeIdx) {\n" +
" return \"blue\"\n" +
" }\n" +
" else if (i == activeIdx) {\n"+
" return \"green\"\n"+
" }\n" +
" else if (d[0] != d[1] || d[0] == 0 || d[1] == 0) {\n"+
" return \"blue\"\n"+
" }\n" +
" else {\n"+
" return \"red\"\n"+
" }\n"+
"})\n"+
".attr(\"r\", function(d,i) {\n"+
" if (document.getElementById(\"select\") != null && i == document.getElementById(\"select\").selectedIndex && i != activeIdx) {\n" +
" return 4\n" +
" }\n" +
" else if (i == activeIdx) {\n"+
" return 6\n"+
" }\n" +
" else if (d[0] != d[1] || d[0] == 0 || d[1] == 0) {\n"+
" return 1.5\n"+
" }\n"+
" else {\n"+
" return 1\n"+
" }\n" +
"})\n" +
".on(\"mouseover\", function(d,i){\n" +
" if(i < " + _fprs.length + ") {" +
" document.getElementById(\"select\").selectedIndex = i\n" +
" show_cm(i)\n" +
" }\n" +
"});\n"+
"data.exit().remove();" +
"}\n" +
"update(dataset);");
sb.append("</script>");
sb.append("</div>");
}
// Compute CMs for different thresholds via MRTask2
private static class AUCTask extends MRTask<AUCTask> {
/* @OUT CMs */ private final ConfusionMatrix2[] getCMs() { return _cms; }
private ConfusionMatrix2[] _cms;
/* IN thresholds */ final private float[] _thresh;
AUCTask(float[] thresh) {
_thresh = thresh.clone();
}
@Override public void map( Chunk ca, Chunk cp ) {
_cms = new ConfusionMatrix2[_thresh.length];
for (int i=0;i<_cms.length;++i)
_cms[i] = new ConfusionMatrix2(2);
final int len = Math.min(ca.len(), cp.len());
for( int i=0; i < len; i++ ) {
if (ca.isNA0(i))
throw new UnsupportedOperationException("Actual class label cannot be a missing value!");
final int a = (int)ca.at80(i); //would be a 0 if double was NaN
assert (a == 0 || a == 1) : "Invalid vactual: must be binary (0 or 1).";
if (cp.isNA0(i)) {
// Log.warn("Skipping predicted NaN."); //some models predict NaN!
continue;
}
for( int t=0; t < _cms.length; t++ ) {
final int p = cp.at0(i)>=_thresh[t]?1:0;
_cms[t].add(a, p);
}
}
}
@Override public void reduce( AUCTask other ) {
for( int i=0; i<_cms.length; ++i) {
_cms[i].add(other._cms[i]);
}
}
}
}
| Check that AUC isn't given a label instead of a probability.
| h2o-core/src/main/java/water/api/AUC.java | Check that AUC isn't given a label instead of a probability. |
|
Java | apache-2.0 | e3e8e2c1a0cf82d54e6c655b992e806d84eb2f30 | 0 | domesticmouse/google-maps-services-java,googlemaps/google-maps-services-java | /*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.google.maps.model;
import com.google.maps.internal.StringJoin.UrlValue;
/**
* The Address types. Please see <a
* href="https://developers.google.com/maps/documentation/geocoding/intro#Types">Address Types and
* Address Component Types</a> for more detail. Some addresses contain additional place categories.
* Please see <a href="https://developers.google.com/places/supported_types">Place Types</a> for
* more detail.
*/
public enum AddressType implements UrlValue {
/** A precise street address. */
STREET_ADDRESS("street_address"),
/** A named route (such as "US 101"). */
ROUTE("route"),
/** A major intersection, usually of two major roads. */
INTERSECTION("intersection"),
/** A political entity. Usually, this type indicates a polygon of some civil administration. */
POLITICAL("political"),
/** The national political entity, typically the highest order type returned by the Geocoder. */
COUNTRY("country"),
/**
* A first-order civil entity below the country level. Within the United States, these
* administrative levels are states. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_1("administrative_area_level_1"),
/**
* A second-order civil entity below the country level. Within the United States, these
* administrative levels are counties. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_2("administrative_area_level_2"),
/**
* A third-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_3("administrative_area_level_3"),
/**
* A fourth-order civil entity below the country level. This type indicates a minor civil
* division. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_4("administrative_area_level_4"),
/**
* A fifth-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_5("administrative_area_level_5"),
/** A commonly-used alternative name for the entity. */
COLLOQUIAL_AREA("colloquial_area"),
/** An incorporated city or town political entity. */
LOCALITY("locality"),
/**
* A specific type of Japanese locality, used to facilitate distinction between multiple locality
* components within a Japanese address.
*/
WARD("ward"),
/**
* A first-order civil entity below a locality. Some locations may receive one of the additional
* types: {@code SUBLOCALITY_LEVEL_1} to {@code SUBLOCALITY_LEVEL_5}. Each sublocality level is a
* civil entity. Larger numbers indicate a smaller geographic area.
*/
SUBLOCALITY("sublocality"),
SUBLOCALITY_LEVEL_1("sublocality_level_1"),
SUBLOCALITY_LEVEL_2("sublocality_level_2"),
SUBLOCALITY_LEVEL_3("sublocality_level_3"),
SUBLOCALITY_LEVEL_4("sublocality_level_4"),
SUBLOCALITY_LEVEL_5("sublocality_level_5"),
/** A named neighborhood. */
NEIGHBORHOOD("neighborhood"),
/** A named location, usually a building or collection of buildings with a common name. */
PREMISE("premise"),
/**
* A first-order entity below a named location, usually a singular building within a collection of
* buildings with a common name.
*/
SUBPREMISE("subpremise"),
/** A postal code as used to address postal mail within the country. */
POSTAL_CODE("postal_code"),
/** A postal code prefix as used to address postal mail within the country. */
POSTAL_CODE_PREFIX("postal_code_prefix"),
/** A prominent natural feature. */
NATURAL_FEATURE("natural_feature"),
/** An airport. */
AIRPORT("airport"),
/** A university. */
UNIVERSITY("university"),
/** A named park. */
PARK("park"),
/**
* A named point of interest. Typically, these "POI"s are prominent local entities that don't
* easily fit in another category, such as "Empire State Building" or "Statue of Liberty."
*/
POINT_OF_INTEREST("point_of_interest"),
/** A place that has not yet been categorized. */
ESTABLISHMENT("establishment"),
/** The location of a bus stop. */
BUS_STATION("bus_station"),
/** The location of a train station. */
TRAIN_STATION("train_station"),
/** The location of a subway station. */
SUBWAY_STATION("subway_station"),
/** The location of a transit station. */
TRANSIT_STATION("transit_station"),
/** The location of a light rail station. */
LIGHT_RAIL_STATION("light_rail_station"),
/** The location of a church. */
CHURCH("church"),
/** The location of a finance institute. */
FINANCE("finance"),
/** The location of a post office. */
POST_OFFICE("post_office"),
/** The location of a place of worship. */
PLACE_OF_WORSHIP("place_of_worship"),
/**
* A grouping of geographic areas, such as locality and sublocality, used for mailing addresses in
* some countries.
*/
POSTAL_TOWN("postal_town"),
/** Currently not a documented return type. */
SYNAGOGUE("synagogue"),
/** Currently not a documented return type. */
FOOD("food"),
/** Currently not a documented return type. */
GROCERY_OR_SUPERMARKET("grocery_or_supermarket"),
/** Currently not a documented return type. */
STORE("store"),
/** Currently not a documented return type. */
LAWYER("lawyer"),
/** Currently not a documented return type. */
HEALTH("health"),
/** Currently not a documented return type. */
INSURANCE_AGENCY("insurance_agency"),
/** Currently not a documented return type. */
GAS_STATION("gas_station"),
/** Currently not a documented return type. */
CAR_DEALER("car_dealer"),
/** Currently not a documented return type. */
CAR_REPAIR("car_repair"),
/** Currently not a documented return type. */
MEAL_TAKEAWAY("meal_takeaway"),
/** Currently not a documented return type. */
FURNITURE_STORE("furniture_store"),
/** Currently not a documented return type. */
HOME_GOODS_STORE("home_goods_store"),
/** Currently not a documented return type. */
SHOPPING_MALL("shopping_mall"),
/** Currently not a documented return type. */
GYM("gym"),
/** Currently not a documented return type. */
ACCOUNTING("accounting"),
/** Currently not a documented return type. */
MOVING_COMPANY("moving_company"),
/** Currently not a documented return type. */
LODGING("lodging"),
/** Currently not a documented return type. */
STORAGE("storage"),
/** Currently not a documented return type. */
CASINO("casino"),
/** Currently not a documented return type. */
PARKING("parking"),
/** Currently not a documented return type. */
STADIUM("stadium"),
/** Currently not a documented return type. */
BEAUTY_SALON("beauty_salon"),
/** Currently not a documented return type. */
HAIR_CARE("hair_care"),
/** Currently not a documented return type. */
SPA("spa"),
/** Currently not a documented return type. */
BAKERY("bakery"),
/** Currently not a documented return type. */
PHARMACY("pharmacy"),
/** Currently not a documented return type. */
SCHOOL("school"),
/** Currently not a documented return type. */
BOOK_STORE("book_store"),
/** Currently not a documented return type. */
DEPARTMENT_STORE("department_store"),
/** Currently not a documented return type. */
RESTAURANT("restaurant"),
/** Currently not a documented return type. */
REAL_ESTATE_AGENCY("real_estate_agency"),
/** Currently not a documented return type. */
BAR("bar"),
/** Currently not a documented return type. */
DOCTOR("doctor"),
/** Currently not a documented return type. */
HOSPITAL("hospital"),
/** Currently not a documented return type. */
FIRE_STATION("fire_station"),
/** Currently not a documented return type. */
SUPERMARKET("supermarket"),
/**
* Indicates an unknown address type returned by the server. The Java Client for Google Maps
* Services should be updated to support the new value.
*/
UNKNOWN("unknown");
private final String addressType;
AddressType(final String addressType) {
this.addressType = addressType;
}
@Override
public String toString() {
return addressType;
}
public String toCanonicalLiteral() {
return toString();
}
@Override
public String toUrlValue() {
if (this == UNKNOWN) {
throw new UnsupportedOperationException("Shouldn't use AddressType.UNKNOWN in a request.");
}
return addressType;
}
}
| src/main/java/com/google/maps/model/AddressType.java | /*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.google.maps.model;
import com.google.maps.internal.StringJoin.UrlValue;
/**
* The Address types. Please see <a
* href="https://developers.google.com/maps/documentation/geocoding/intro#Types">Address Types and
* Address Component Types</a> for more detail. Some addresses contain additional place categories.
* Please see <a href="https://developers.google.com/places/supported_types">Place Types</a> for
* more detail.
*/
public enum AddressType implements UrlValue {
/** A precise street address. */
STREET_ADDRESS("street_address"),
/** A named route (such as "US 101"). */
ROUTE("route"),
/** A major intersection, usually of two major roads. */
INTERSECTION("intersection"),
/** A political entity. Usually, this type indicates a polygon of some civil administration. */
POLITICAL("political"),
/** The national political entity, typically the highest order type returned by the Geocoder. */
COUNTRY("country"),
/**
* A first-order civil entity below the country level. Within the United States, these
* administrative levels are states. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_1("administrative_area_level_1"),
/**
* A second-order civil entity below the country level. Within the United States, these
* administrative levels are counties. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_2("administrative_area_level_2"),
/**
* A third-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_3("administrative_area_level_3"),
/**
* A fourth-order civil entity below the country level. This type indicates a minor civil
* division. Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_4("administrative_area_level_4"),
/**
* A fifth-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
ADMINISTRATIVE_AREA_LEVEL_5("administrative_area_level_5"),
/** A commonly-used alternative name for the entity. */
COLLOQUIAL_AREA("colloquial_area"),
/** An incorporated city or town political entity. */
LOCALITY("locality"),
/**
* A specific type of Japanese locality, used to facilitate distinction between multiple locality
* components within a Japanese address.
*/
WARD("ward"),
/**
* A first-order civil entity below a locality. Some locations may receive one of the additional
* types: {@code SUBLOCALITY_LEVEL_1} to {@code SUBLOCALITY_LEVEL_5}. Each sublocality level is a
* civil entity. Larger numbers indicate a smaller geographic area.
*/
SUBLOCALITY("sublocality"),
SUBLOCALITY_LEVEL_1("sublocality_level_1"),
SUBLOCALITY_LEVEL_2("sublocality_level_2"),
SUBLOCALITY_LEVEL_3("sublocality_level_3"),
SUBLOCALITY_LEVEL_4("sublocality_level_4"),
SUBLOCALITY_LEVEL_5("sublocality_level_5"),
/** A named neighborhood. */
NEIGHBORHOOD("neighborhood"),
/** A named location, usually a building or collection of buildings with a common name. */
PREMISE("premise"),
/**
* A first-order entity below a named location, usually a singular building within a collection of
* buildings with a common name.
*/
SUBPREMISE("subpremise"),
/** A postal code as used to address postal mail within the country. */
POSTAL_CODE("postal_code"),
/** A postal code prefix as used to address postal mail within the country. */
POSTAL_CODE_PREFIX("postal_code_prefix"),
/** A prominent natural feature. */
NATURAL_FEATURE("natural_feature"),
/** An airport. */
AIRPORT("airport"),
/** A university. */
UNIVERSITY("university"),
/** A named park. */
PARK("park"),
/**
* A named point of interest. Typically, these "POI"s are prominent local entities that don't
* easily fit in another category, such as "Empire State Building" or "Statue of Liberty."
*/
POINT_OF_INTEREST("point_of_interest"),
/** A place that has not yet been categorized. */
ESTABLISHMENT("establishment"),
/** The location of a bus stop. */
BUS_STATION("bus_station"),
/** The location of a train station. */
TRAIN_STATION("train_station"),
/** The location of a subway station. */
SUBWAY_STATION("subway_station"),
/** The location of a transit station. */
TRANSIT_STATION("transit_station"),
/** The location of a light rail station. */
LIGHT_RAIL_STATION("light_rail_station"),
/** The location of a church. */
CHURCH("church"),
/** The location of a finance institute. */
FINANCE("finance"),
/** The location of a post office. */
POST_OFFICE("post_office"),
/** The location of a place of worship. */
PLACE_OF_WORSHIP("place_of_worship"),
/**
* A grouping of geographic areas, such as locality and sublocality, used for mailing addresses in
* some countries.
*/
POSTAL_TOWN("postal_town"),
/** Currently not a documented return type. */
SYNAGOGUE("synagogue"),
/** Currently not a documented return type. */
FOOD("food"),
/** Currently not a documented return type. */
GROCERY_OR_SUPERMARKET("grocery_or_supermarket"),
/** Currently not a documented return type. */
STORE("store"),
/** Currently not a documented return type. */
LAWYER("lawyer"),
/** Currently not a documented return type. */
HEALTH("health"),
/** Currently not a documented return type. */
INSURANCE_AGENCY("insurance_agency"),
/** Currently not a documented return type. */
GAS_STATION("gas_station"),
/** Currently not a documented return type. */
CAR_DEALER("car_dealer"),
/** Currently not a documented return type. */
CAR_REPAIR("car_repair"),
/** Currently not a documented return type. */
MEAL_TAKEAWAY("meal_takeaway"),
/** Currently not a documented return type. */
FURNITURE_STORE("furniture_store"),
/** Currently not a documented return type. */
HOME_GOODS_STORE("home_goods_store"),
/** Currently not a documented return type. */
SHOPPING_MALL("shopping_mall"),
/** Currently not a documented return type. */
GYM("gym"),
/** Currently not a documented return type. */
ACCOUNTING("accounting"),
/** Currently not a documented return type. */
MOVING_COMPANY("moving_company"),
/** Currently not a documented return type. */
LODGING("lodging"),
/** Currently not a documented return type. */
STORAGE("storage"),
/** Currently not a documented return type. */
CASINO("casino"),
/** Currently not a documented return type. */
PARKING("parking"),
/** Currently not a documented return type. */
STADIUM("stadium"),
/** Currently not a documented return type. */
BEAUTY_SALON("beauty_salon"),
/** Currently not a documented return type. */
HAIR_CARE("hair_care"),
/** Currently not a documented return type. */
SPA("spa"),
/**
* Indicates an unknown address type returned by the server. The Java Client for Google Maps
* Services should be updated to support the new value.
*/
UNKNOWN("unknown");
private final String addressType;
AddressType(final String addressType) {
this.addressType = addressType;
}
@Override
public String toString() {
return addressType;
}
public String toCanonicalLiteral() {
return toString();
}
@Override
public String toUrlValue() {
if (this == UNKNOWN) {
throw new UnsupportedOperationException("Shouldn't use AddressType.UNKNOWN in a request.");
}
return addressType;
}
}
| AddressType: add more types observed by steveetl
| src/main/java/com/google/maps/model/AddressType.java | AddressType: add more types observed by steveetl |
|
Java | apache-2.0 | aebd56d1cbcf296fdde923b057e3c38ee51aa4b7 | 0 | muntasirsyed/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,samthor/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,kool79/intellij-community,petteyg/intellij-community,kool79/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,fnouama/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,da1z/intellij-community,xfournet/intellij-community,kdwink/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,signed/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,fnouama/intellij-community,hurricup/intellij-community,robovm/robovm-studio,hurricup/intellij-community,asedunov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ernestp/consulo,clumsy/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,semonte/intellij-community,nicolargo/intellij-community,signed/intellij-community,holmes/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,hurricup/intellij-community,caot/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,supersven/intellij-community,signed/intellij-community,hurricup/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,slisson/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,amith01994/intellij-community,petteyg/intellij-community,fnouama/intellij-community,fitermay/intellij-community,hurricup/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,holmes/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,slisson/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ibinti/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,robovm/robovm-studio,allotria/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ryano144/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,consulo/consulo,apixandru/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,asedunov/intellij-community,allotria/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,da1z/intellij-community,ryano144/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,caot/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,signed/intellij-community,youdonghai/intellij-community,caot/intellij-community,kdwink/intellij-community,consulo/consulo,michaelgallacher/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,samthor/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,samthor/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,consulo/consulo,ahb0327/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,semonte/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,supersven/intellij-community,samthor/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,da1z/intellij-community,allotria/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,joewalnes/idea-community,izonder/intellij-community,ibinti/intellij-community,jagguli/intellij-community,retomerz/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,supersven/intellij-community,holmes/intellij-community,gnuhub/intellij-community,semonte/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ryano144/intellij-community,izonder/intellij-community,clumsy/intellij-community,semonte/intellij-community,signed/intellij-community,hurricup/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ernestp/consulo,ahb0327/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,clumsy/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,slisson/intellij-community,allotria/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,holmes/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,kool79/intellij-community,blademainer/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,kool79/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,vladmm/intellij-community,signed/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ftomassetti/intellij-community,vladmm/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,robovm/robovm-studio,robovm/robovm-studio,SerCeMan/intellij-community,ibinti/intellij-community,joewalnes/idea-community,ernestp/consulo,signed/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,slisson/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,robovm/robovm-studio,pwoodworth/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,caot/intellij-community,xfournet/intellij-community,petteyg/intellij-community,adedayo/intellij-community,fitermay/intellij-community,joewalnes/idea-community,dslomov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,signed/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,Lekanich/intellij-community,signed/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,diorcety/intellij-community,robovm/robovm-studio,da1z/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,asedunov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,fnouama/intellij-community,caot/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,amith01994/intellij-community,adedayo/intellij-community,caot/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,caot/intellij-community,kool79/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,samthor/intellij-community,supersven/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,da1z/intellij-community,slisson/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ryano144/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,asedunov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,semonte/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,holmes/intellij-community,petteyg/intellij-community,semonte/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,da1z/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,consulo/consulo,idea4bsd/idea4bsd,suncycheng/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,amith01994/intellij-community,slisson/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,signed/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,kool79/intellij-community,ryano144/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,kool79/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,izonder/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,supersven/intellij-community,kool79/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,izonder/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,diorcety/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,holmes/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ernestp/consulo,youdonghai/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,joewalnes/idea-community,diorcety/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,semonte/intellij-community,caot/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,petteyg/intellij-community,holmes/intellij-community,FHannes/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,semonte/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,kool79/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,izonder/intellij-community,samthor/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,samthor/intellij-community,fnouama/intellij-community,dslomov/intellij-community,vladmm/intellij-community,FHannes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,signed/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,izonder/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,consulo/consulo,muntasirsyed/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,holmes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ernestp/consulo,diorcety/intellij-community,amith01994/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.template.impl;
import com.intellij.application.options.ExportSchemeAction;
import com.intellij.application.options.SchemesToImportPopup;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.CheckboxTree;
import com.intellij.ui.CheckedTreeNode;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.Alarm;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
class TemplateListPanel extends JPanel {
private CheckboxTree myTree;
private JButton myCopyButton;
private JButton myEditButton;
private JButton myRemoveButton;
private JButton myExportButton;
private JButton myImportButton;
private Editor myEditor;
private final List<TemplateGroup> myTemplateGroups = new ArrayList<TemplateGroup>();
private JComboBox myExpandByCombo;
private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");
private CheckedTreeNode myTreeRoot = new CheckedTreeNode(null);
private final Alarm myAlarm = new Alarm();
private boolean myUpdateNeeded = false;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.impl.TemplateListPanel");
private final Map<Integer, Map<TemplateOptionalProcessor, Boolean>> myTemplateOptions = new LinkedHashMap<Integer, Map<TemplateOptionalProcessor, Boolean>>();
private final Map<Integer, Map<TemplateContextType, Boolean>> myTemplateContext = new LinkedHashMap<Integer, Map<TemplateContextType, Boolean>>();
public TemplateListPanel() {
setLayout(new BorderLayout());
fillPanel(this);
}
public void dispose() {
EditorFactory.getInstance().releaseEditor(myEditor);
myAlarm.cancelAllRequests();
}
public void reset() {
myTemplateOptions.clear();
myTemplateContext.clear();
TemplateSettings templateSettings = TemplateSettings.getInstance();
List<TemplateGroup> groups = new ArrayList<TemplateGroup>(templateSettings.getTemplateGroups());
Collections.sort(groups, new Comparator<TemplateGroup>(){
public int compare(final TemplateGroup o1, final TemplateGroup o2) {
return o1.getName().compareTo(o2.getName());
}
});
initTemplates(groups, templateSettings.getLastSelectedTemplateKey());
if (templateSettings.getDefaultShortcutChar() == TemplateSettings.TAB_CHAR) {
myExpandByCombo.setSelectedItem(TAB);
}
else if (templateSettings.getDefaultShortcutChar() == TemplateSettings.ENTER_CHAR) {
myExpandByCombo.setSelectedItem(ENTER);
}
else {
myExpandByCombo.setSelectedItem(SPACE);
}
UiNotifyConnector.doWhenFirstShown(this, new Runnable() {
public void run() {
updateTemplateText();
}
});
myUpdateNeeded = true;
}
public void apply() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
List<TemplateGroup> templateGroups = getTemplateGroups();
for (TemplateGroup templateGroup : templateGroups) {
for (TemplateImpl template : templateGroup.getElements()) {
template.applyOptions(getOptions(template));
template.applyContext(getContext(template));
}
}
templateSettings.setTemplates(templateGroups);
templateSettings.setDefaultShortcutChar(getDefaultShortcutChar());
reset();
}
public boolean isModified() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
if (templateSettings.getDefaultShortcutChar() != getDefaultShortcutChar()) {
return true;
}
List<TemplateGroup> originalGroups = templateSettings.getTemplateGroups();
List<TemplateGroup> newGroups = getTemplateGroups();
return !checkAreEqual(collectTemplates(originalGroups), collectTemplates(newGroups));
}
private static List<TemplateImpl> collectTemplates(final List<TemplateGroup> groups) {
ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
for (TemplateGroup group : groups) {
result.addAll(group.getElements());
}
Collections.sort(result, new Comparator<TemplateImpl>(){
public int compare(final TemplateImpl o1, final TemplateImpl o2) {
final int groupsEqual = o1.getGroupName().compareTo(o2.getGroupName());
if (groupsEqual != 0) {
return groupsEqual;
}
return o1.getKey().compareTo(o2.getKey());
}
});
return result;
}
private boolean checkAreEqual(final List<TemplateImpl> originalGroup, final List<TemplateImpl> newGroup) {
if (originalGroup.size() != newGroup.size()) return false;
for (int i = 0; i < newGroup.size(); i++) {
TemplateImpl newTemplate = newGroup.get(i);
newTemplate.parseSegments();
TemplateImpl originalTemplate = originalGroup.get(i);
originalTemplate.parseSegments();
if (!originalTemplate.equals(newTemplate)) {
return false;
}
if (originalTemplate.isDeactivated() != newTemplate.isDeactivated()) {
return false;
}
if (!areOptionsEqual(newTemplate, originalTemplate)) {
return false;
}
if (!areContextsEqual(newTemplate, originalTemplate)) {
return false;
}
}
return true;
}
private boolean areContextsEqual(final TemplateImpl newTemplate, final TemplateImpl originalTemplate) {
Map<TemplateContextType, Boolean> templateContext = getTemplateContext(newTemplate);
for (TemplateContextType processor : templateContext.keySet()) {
if (originalTemplate.getTemplateContext().isEnabled(processor) != templateContext.get(processor).booleanValue())
return false;
}
return true;
}
private boolean areOptionsEqual(final TemplateImpl newTemplate, final TemplateImpl originalTemplate) {
Map<TemplateOptionalProcessor, Boolean> templateOptions = getTemplateOptions(newTemplate);
for (TemplateOptionalProcessor processor : templateOptions.keySet()) {
if (processor.isEnabled(originalTemplate) != templateOptions.get(processor).booleanValue()) return false;
}
return true;
}
private Map<TemplateContextType, Boolean> getTemplateContext(final TemplateImpl newTemplate) {
return myTemplateContext.get(getKey(newTemplate));
}
private Map<TemplateOptionalProcessor, Boolean> getTemplateOptions(final TemplateImpl newTemplate) {
return myTemplateOptions.get(getKey(newTemplate));
}
private char getDefaultShortcutChar() {
Object selectedItem = myExpandByCombo.getSelectedItem();
if (TAB.equals(selectedItem)) {
return TemplateSettings.TAB_CHAR;
}
else if (ENTER.equals(selectedItem)) {
return TemplateSettings.ENTER_CHAR;
}
else {
return TemplateSettings.SPACE_CHAR;
}
}
private List<TemplateGroup> getTemplateGroups() {
return myTemplateGroups;
}
private void fillPanel(JPanel optionsPanel) {
JPanel tablePanel = new JPanel();
tablePanel.setBorder(BorderFactory.createLineBorder(Color.gray));
tablePanel.setLayout(new BorderLayout());
tablePanel.add(createTable(), BorderLayout.CENTER);
JPanel tableButtonsPanel = new JPanel();
tableButtonsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tableButtonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.insets = new Insets(0, 0, 4, 0);
final JButton addButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.add"));
addButton.setEnabled(true);
myCopyButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.copy"));
myEditButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.edit"));
myRemoveButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.remove"));
if (getSchemesManager().isExportAvailable()) {
myExportButton = createButton(tableButtonsPanel, gbConstraints, "Share...");
myEditButton.setMnemonic('S');
myExportButton.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e) {
exportCurrentGroup();
}
});
}
if (getSchemesManager().isImportAvailable()) {
myImportButton = createButton(tableButtonsPanel, gbConstraints, "Import Shared...");
myImportButton.setMnemonic('I');
myImportButton.setEnabled(true);
myImportButton.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e) {
new SchemesToImportPopup<TemplateGroup, TemplateGroup>(TemplateListPanel.this){
protected void onSchemeSelected(final TemplateGroup scheme) {
for (TemplateImpl newTemplate : scheme.getElements()) {
for (TemplateImpl existingTemplate : collectAllTemplates()) {
if (existingTemplate.getKey().equals(newTemplate.getKey())) {
Messages.showMessageDialog(
TemplateListPanel.this,
CodeInsightBundle.message("dialog.edit.template.error.already.exists", existingTemplate.getKey(), existingTemplate.getGroupName()),
CodeInsightBundle.message("dialog.edit.template.error.title"),
Messages.getErrorIcon()
);
return;
}
}
}
insertNewGroup(scheme);
for (TemplateImpl template : scheme.getElements()) {
addTemplate(template);
}
}
}.show(getSchemesManager(), myTemplateGroups);
}
});
}
gbConstraints.weighty = 1;
tableButtonsPanel.add(new JPanel(), gbConstraints);
tablePanel.add(tableButtonsPanel, BorderLayout.EAST);
optionsPanel.add(tablePanel, BorderLayout.CENTER);
JPanel textPanel = new JPanel(new BorderLayout());
textPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
myEditor = TemplateEditorUtil.createEditor(true, "");
textPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
textPanel.add(createExpandByPanel(), BorderLayout.SOUTH);
textPanel.setPreferredSize(new Dimension(100, myEditor.getLineHeight() * 12));
optionsPanel.add(textPanel, BorderLayout.SOUTH);
addButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
}
);
myCopyButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
copyRow();
}
}
);
myEditButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
edit();
}
}
);
myRemoveButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
}
);
}
private Iterable<? extends TemplateImpl> collectAllTemplates() {
ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
for (TemplateGroup templateGroup : myTemplateGroups) {
result.addAll(templateGroup.getElements());
}
return result;
}
private void exportCurrentGroup() {
int selected = getSelectedIndex();
if (selected < 0) return;
ExportSchemeAction.doExport(getGroup(selected), getSchemesManager());
}
private static SchemesManager<TemplateGroup, TemplateGroup> getSchemesManager() {
return (TemplateSettings.getInstance()).getSchemesManager();
}
private static JButton createButton(final JPanel tableButtonsPanel, final GridBagConstraints gbConstraints, final String message) {
JButton button = new JButton(message);
button.setEnabled(false);
//button.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(button, gbConstraints);
return button;
}
private JPanel createExpandByPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.weighty = 0;
gbConstraints.insets = new Insets(4, 0, 0, 0);
gbConstraints.weightx = 0;
gbConstraints.gridy = 0;
// panel.add(createLabel("By default expand with "), gbConstraints);
panel.add(new JLabel(CodeInsightBundle.message("templates.dialog.shortcut.chooser.label")), gbConstraints);
gbConstraints.gridx = 1;
myExpandByCombo = new JComboBox();
myExpandByCombo.addItem(SPACE);
myExpandByCombo.addItem(TAB);
myExpandByCombo.addItem(ENTER);
panel.add(myExpandByCombo, gbConstraints);
gbConstraints.gridx = 2;
gbConstraints.weightx = 1;
panel.add(new JPanel(), gbConstraints);
return panel;
}
@Nullable
private TemplateKey getTemplateKey(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateImpl) {
return new TemplateKey((TemplateImpl)node.getUserObject());
}
}
return null;
}
@Nullable
private TemplateImpl getTemplate(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateImpl) {
return (TemplateImpl)node.getUserObject();
}
}
return null;
}
@Nullable
private TemplateGroup getGroup(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateGroup) {
return (TemplateGroup)node.getUserObject();
}
}
return null;
}
private void edit() {
int selected = getSelectedIndex();
if (selected < 0) return;
TemplateImpl template = getTemplate(selected);
DefaultMutableTreeNode oldTemplateNode = getNode(selected);
if (template == null) return;
String oldGroupName = template.getGroupName();
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.edit.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
TemplateGroup group = getTemplateGroup(template.getGroupName());
LOG.assertTrue(group != null, template.getGroupName());
dialog.apply();
if (!oldGroupName.equals(template.getGroupName())) {
TemplateGroup oldGroup = getTemplateGroup(oldGroupName);
if (oldGroup != null) {
oldGroup.removeElement(template);
}
template.setId(null);//To make it not equal with default template with the same name
JTree tree = myTree;
if (oldTemplateNode != null) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)oldTemplateNode.getParent();
removeNodeFromParent(oldTemplateNode);
if (parent.getChildCount() == 0) removeNodeFromParent(parent);
}
DefaultMutableTreeNode templateNode = addTemplate(template);
if (templateNode != null) {
TreePath newTemplatePath = new TreePath(templateNode.getPath());
tree.expandPath(newTemplatePath);
selected = tree.getRowForPath(newTemplatePath);
}
((DefaultTreeModel)myTree.getModel()).nodeStructureChanged(myTreeRoot);
}
myTree.setSelectionInterval(selected, selected);
updateTemplateTextArea();
}
private Map<TemplateOptionalProcessor, Boolean> getOptions(final TemplateImpl template) {
return getTemplateOptions(template);
}
@Nullable
private DefaultMutableTreeNode getNode(final int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
return (DefaultMutableTreeNode)path.getLastPathComponent();
}
return null;
}
@Nullable
private TemplateGroup getTemplateGroup(final String groupName) {
for (TemplateGroup group : myTemplateGroups) {
if (group.getName().equals(groupName)) return group;
}
return null;
}
private void addRow() {
int selected = getSelectedIndex();
String defaultGroup = TemplateSettings.USER_GROUP_NAME;
final DefaultMutableTreeNode node = getNode(selected);
if (node != null) {
if (node.getUserObject() instanceof TemplateImpl) {
defaultGroup = ((TemplateImpl) node.getUserObject()).getGroupName();
}
else if (node.getUserObject() instanceof TemplateGroup) {
defaultGroup = ((TemplateGroup) node.getUserObject()).getName();
}
}
TemplateImpl template = new TemplateImpl("", "", defaultGroup);
myTemplateOptions.put(getKey(template), template.createOptions());
myTemplateContext.put(getKey(template), template.createContext());
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.add.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
}
private static int getKey(final TemplateImpl template) {
return System.identityHashCode(template);
}
private void copyRow() {
int selected = getSelectedIndex();
if (selected < 0) return;
TemplateImpl orTemplate = getTemplate(selected);
LOG.assertTrue(orTemplate != null);
TemplateImpl template = orTemplate.copy();
myTemplateOptions.put(getKey(template), getOptions(orTemplate));
myTemplateContext.put(getKey(template), getContext(orTemplate));
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.copy.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
}
private Map<TemplateContextType, Boolean> getContext(final TemplateImpl template) {
return getTemplateContext(template);
}
private int getSelectedIndex() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null) {
return -1;
}
else {
return myTree.getRowForPath(selectionPath);
}
}
private void removeRow() {
int selected = getSelectedIndex(); // TODO
if (selected < 0) return;
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey != null) {
int result = Messages.showOkCancelDialog(this, CodeInsightBundle.message("template.delete.confirmation.text"),
CodeInsightBundle.message("template.delete.confirmation.title"),
Messages.getQuestionIcon());
if (result != DialogWrapper.OK_EXIT_CODE) return;
removeTemplateAt(selected);
}
else {
TemplateGroup group = getGroup(selected);
if (group != null) {
int result = Messages.showOkCancelDialog(this, CodeInsightBundle.message("template.delete.group.confirmation.text"),
CodeInsightBundle.message("template.delete.confirmation.title"),
Messages.getQuestionIcon());
if (result != DialogWrapper.OK_EXIT_CODE) return;
JTree tree = myTree;
TreePath path = tree.getPathForRow(selected);
myTemplateGroups.remove(group);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
removeNodeFromParent(node);
}
}
}
private JScrollPane createTable() {
myTreeRoot = new CheckedTreeNode(null);
myTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer(){
public void customizeCellRenderer(final JTree tree,
Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
value = ((DefaultMutableTreeNode)value).getUserObject();
if (value instanceof TemplateImpl) {
//getTextRenderer().setIcon(TEMPLATE_ICON);
getTextRenderer().append (((TemplateImpl)value).getKey(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
String description = ((TemplateImpl)value).getDescription();
if (description != null && description.length() > 0) {
getTextRenderer().append (" (" + description + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
else if (value instanceof TemplateGroup) {
//getTextRenderer().setIcon(TEMPLATE_GROUP_ICON);
getTextRenderer().append (((TemplateGroup)value).getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
}
}, myTreeRoot) {
@Override
protected void onNodeStateChanged(final CheckedTreeNode node) {
Object obj = node.getUserObject();
if (obj instanceof TemplateImpl) {
((TemplateImpl)obj).setDeactivated(!node.isChecked());
}
}
};
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
DefaultTreeSelectionModel selModel = new DefaultTreeSelectionModel();
myTree.setSelectionModel(selModel);
selModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(final TreeSelectionEvent e) {
boolean enableEditButton = false;
boolean enableRemoveButton = false;
boolean enableCopyButton = false;
boolean enableExportButton = false;
int selected = getSelectedIndex();
if (selected >= 0 && selected < myTree.getRowCount()) {
TemplateSettings templateSettings = TemplateSettings.getInstance();
TemplateImpl template = getTemplate(selected);
if (template != null) {
templateSettings.setLastSelectedTemplateKey(template.getKey());
} else {
templateSettings.setLastSelectedTemplateKey(null);
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getPathForRow(selected).getLastPathComponent();
enableExportButton = false;
enableEditButton = false;
enableCopyButton = false;
if (node.getUserObject() instanceof TemplateImpl) {
enableCopyButton = true;
if (template != null) {
TemplateGroup group = getTemplateGroup(template.getGroupName());
if (group != null && !getSchemesManager().isShared(group)) {
enableEditButton = true;
enableRemoveButton = true;
}
}
}
if (node.getUserObject() instanceof TemplateGroup) {
enableRemoveButton = true;
TemplateGroup group = (TemplateGroup)node.getUserObject();
enableExportButton = !getSchemesManager().isShared(group);
}
}
updateTemplateTextArea();
myEditor.getComponent().setEnabled(enableEditButton);
if (myCopyButton != null) {
myCopyButton.setEnabled(enableCopyButton);
myEditButton.setEnabled(enableEditButton);
myRemoveButton.setEnabled(enableRemoveButton);
}
if (myExportButton != null) {
myExportButton.setEnabled(enableExportButton);
}
if (myImportButton != null) {
myImportButton.setEnabled(true);
}
}
});
myTree.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
JComponent.WHEN_FOCUSED
);
myTree.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
JComponent.WHEN_FOCUSED
);
myTree.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
edit();
}
}
}
);
JScrollPane scrollpane = ScrollPaneFactory.createScrollPane(myTree);
if (myTemplateGroups.size() > 0) {
myTree.setSelectionInterval(0, 0);
}
scrollpane.setPreferredSize(new Dimension(600, 400));
return scrollpane;
}
private void updateTemplateTextArea() {
if (!myUpdateNeeded) return;
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
updateTemplateText();
}
}, 100);
}
private void updateTemplateText() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
int selected = getSelectedIndex();
if (selected < 0) {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
else {
TemplateImpl template = getTemplate(selected);
if (template != null) {
String text = template.getString();
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), text);
TemplateEditorUtil.setHighlighter(myEditor, template.getTemplateContext());
} else {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
}
}
});
}
@Nullable
private DefaultMutableTreeNode addTemplate(TemplateImpl template) {
TemplateGroup newGroup = getTemplateGroup(template.getGroupName());
if (newGroup == null) {
newGroup = new TemplateGroup(template.getGroupName());
insertNewGroup(newGroup);
}
if (!newGroup.contains(template)) {
newGroup.addElement(template);
}
CheckedTreeNode node = new CheckedTreeNode(template);
node.setChecked(!template.isDeactivated());
if (myTreeRoot.getChildCount() > 0) {
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)myTreeRoot.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)myTreeRoot.getChildAfter(child)) {
if (((TemplateGroup)child.getUserObject()).getName().equals(template.getGroupName())) {
int index = getIndexToInsert (child, template.getKey());
child.insert(node, index);
((DefaultTreeModel)myTree.getModel()).nodesWereInserted(child, new int[]{index});
setSelectedNode(node);
return node;
}
}
}
return null;
}
private void insertNewGroup(final TemplateGroup newGroup) {
myTemplateGroups.add(newGroup);
int index = getIndexToInsert(myTreeRoot, newGroup.getName());
DefaultMutableTreeNode groupNode = new CheckedTreeNode(newGroup);
myTreeRoot.insert(groupNode, index);
((DefaultTreeModel)myTree.getModel()).nodesWereInserted(myTreeRoot, new int[]{index});
}
private static int getIndexToInsert(DefaultMutableTreeNode parent, String key) {
if (parent.getChildCount() == 0) return 0;
int res = 0;
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)parent.getChildAfter(child)) {
Object o = child.getUserObject();
String key1 = o instanceof TemplateImpl ? ((TemplateImpl)o).getKey() : ((TemplateGroup)o).getName();
if (key1.compareTo(key) > 0) return res;
res++;
}
return res;
}
private void setSelectedNode(DefaultMutableTreeNode node) {
JTree tree = myTree;
TreePath path = new TreePath(node.getPath());
tree.expandPath(path.getParentPath());
int row = tree.getRowForPath(path);
myTree.setSelectionInterval(row, row);
//myTree.scrollRectToVisible(myTree.getR(row, 0, true)); TODO
}
private void removeTemplateAt(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
LOG.assertTrue(node.getUserObject() instanceof TemplateImpl);
TemplateImpl template = (TemplateImpl)node.getUserObject();
TemplateGroup templateGroup = getTemplateGroup(template.getGroupName());
if (templateGroup != null) {
templateGroup.removeElement(template);
}
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
TreePath treePathToSelect = (parent.getChildAfter(node) != null || parent.getChildCount() == 1 ?
tree.getPathForRow(row + 1) :
tree.getPathForRow(row - 1));
DefaultMutableTreeNode toSelect = treePathToSelect != null ? (DefaultMutableTreeNode)treePathToSelect.getLastPathComponent() : null;
removeNodeFromParent(node);
if (parent.getChildCount() == 0) {
myTemplateGroups.remove(parent.getUserObject());
removeNodeFromParent(parent);
}
if (toSelect != null) {
setSelectedNode(toSelect);
}
}
private void removeNodeFromParent(DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
int idx = parent.getIndex(node);
node.removeFromParent();
((DefaultTreeModel)myTree.getModel()).nodesWereRemoved(parent, new int[]{idx}, new TreeNode[]{node});
}
private void initTemplates(List<TemplateGroup> groups, String lastSelectedKey) {
myTreeRoot.removeAllChildren();
myTemplateGroups.clear();
for (TemplateGroup group : groups) {
myTemplateGroups.add((TemplateGroup)group.copy());
}
DefaultMutableTreeNode nodeToSelect = null;
for (TemplateGroup group : myTemplateGroups) {
CheckedTreeNode groupNode = new CheckedTreeNode(group);
List<TemplateImpl> templates = new ArrayList<TemplateImpl>(group.getElements());
Collections.sort(templates, new Comparator<TemplateImpl>(){
public int compare(final TemplateImpl o1, final TemplateImpl o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
for (final Object groupTemplate : templates) {
TemplateImpl template = (TemplateImpl)groupTemplate;
myTemplateOptions.put(getKey(template), template.createOptions());
myTemplateContext.put(getKey(template), template.createContext());
CheckedTreeNode node = new CheckedTreeNode(template);
node.setChecked(!template.isDeactivated());
groupNode.add(node);
if (lastSelectedKey != null && lastSelectedKey.equals(template.getKey())) {
nodeToSelect = node;
}
}
myTreeRoot.add(groupNode);
}
((DefaultTreeModel)myTree.getModel()).nodeStructureChanged(myTreeRoot);
if (nodeToSelect != null) {
JTree tree = myTree;
TreePath path = new TreePath(nodeToSelect.getPath());
tree.expandPath(path.getParentPath());
int rowToSelect = tree.getRowForPath(path);
myTree.setSelectionInterval(rowToSelect, rowToSelect);
/* TODO
final Rectangle rect = myTreeTable.getCellRect(rowToSelect, 0, true);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
myTreeTable.scrollRectToVisible(rect);
}
});*/
}
}
private static class TemplateKey implements Comparable {
private final String myKey;
private final String myGroupName;
public TemplateKey(TemplateImpl template) {
String key = template.getKey();
if (key == null) {
key = "";
}
myKey = key;
String groupName = template.getGroupName();
if (groupName == null) {
groupName = "";
}
myGroupName =groupName;
}
public boolean equals(Object obj) {
if (!(obj instanceof TemplateKey)) {
return false;
}
TemplateKey templateKey = (TemplateKey)obj;
return (myGroupName.compareTo(templateKey.myGroupName) == 0) &&
(myKey.compareTo(templateKey.myKey) == 0);
}
public int compareTo(Object obj) {
if (!(obj instanceof TemplateKey)) {
return 1;
}
TemplateKey templateKey = (TemplateKey)obj;
int result = myGroupName.compareTo(templateKey.myGroupName);
return result != 0 ? result : myKey.compareTo(templateKey.myKey);
}
}
class ActivationStateColumnInfo extends ColumnInfo {
public ActivationStateColumnInfo(String name) {
super(name);
}
public boolean isCellEditable(Object o) {
return o != null;
}
public void setValue(Object obj, Object aValue) {
obj = ((DefaultMutableTreeNode)obj).getUserObject();
if (obj instanceof TemplateImpl) {
TemplateImpl template = (TemplateImpl)obj;
boolean state = !((Boolean)aValue).booleanValue();
if (state != template.isDeactivated()) {
template.setDeactivated(!((Boolean)aValue).booleanValue());
}
}
}
public Class getColumnClass() {
return Boolean.class;
}
public Object valueOf(Object object) {
object = ((DefaultMutableTreeNode)object).getUserObject();
if (object instanceof TemplateImpl) {
return ((TemplateImpl)object).isDeactivated() ? Boolean.FALSE : Boolean.TRUE;
}
else {
return null;
}
}
}
}
| platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.template.impl;
import com.intellij.application.options.ExportSchemeAction;
import com.intellij.application.options.SchemesToImportPopup;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.CheckboxTree;
import com.intellij.ui.CheckedTreeNode;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.Alarm;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
class TemplateListPanel extends JPanel {
private CheckboxTree myTree;
private JButton myCopyButton;
private JButton myEditButton;
private JButton myRemoveButton;
private JButton myExportButton;
private JButton myImportButton;
private Editor myEditor;
private final List<TemplateGroup> myTemplateGroups = new ArrayList<TemplateGroup>();
private JComboBox myExpandByCombo;
private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");
private CheckedTreeNode myTreeRoot = new CheckedTreeNode(null);
private final Alarm myAlarm = new Alarm();
private boolean myUpdateNeeded = false;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.impl.TemplateListPanel");
private final Map<Integer, Map<TemplateOptionalProcessor, Boolean>> myTemplateOptions = new LinkedHashMap<Integer, Map<TemplateOptionalProcessor, Boolean>>();
private final Map<Integer, Map<TemplateContextType, Boolean>> myTemplateContext = new LinkedHashMap<Integer, Map<TemplateContextType, Boolean>>();
public TemplateListPanel() {
setLayout(new BorderLayout());
fillPanel(this);
}
public void dispose() {
EditorFactory.getInstance().releaseEditor(myEditor);
myAlarm.cancelAllRequests();
}
public void reset() {
myTemplateOptions.clear();
myTemplateContext.clear();
TemplateSettings templateSettings = TemplateSettings.getInstance();
List<TemplateGroup> groups = new ArrayList<TemplateGroup>(templateSettings.getTemplateGroups());
Collections.sort(groups, new Comparator<TemplateGroup>(){
public int compare(final TemplateGroup o1, final TemplateGroup o2) {
return o1.getName().compareTo(o2.getName());
}
});
initTemplates(groups, templateSettings.getLastSelectedTemplateKey());
if (templateSettings.getDefaultShortcutChar() == TemplateSettings.TAB_CHAR) {
myExpandByCombo.setSelectedItem(TAB);
}
else if (templateSettings.getDefaultShortcutChar() == TemplateSettings.ENTER_CHAR) {
myExpandByCombo.setSelectedItem(ENTER);
}
else {
myExpandByCombo.setSelectedItem(SPACE);
}
UiNotifyConnector.doWhenFirstShown(this, new Runnable() {
public void run() {
updateTemplateText();
}
});
myUpdateNeeded = true;
}
public void apply() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
List<TemplateGroup> templateGroups = getTemplateGroups();
for (TemplateGroup templateGroup : templateGroups) {
for (TemplateImpl template : templateGroup.getElements()) {
template.applyOptions(getOptions(template));
template.applyContext(getContext(template));
}
}
templateSettings.setTemplates(templateGroups);
templateSettings.setDefaultShortcutChar(getDefaultShortcutChar());
reset();
}
public boolean isModified() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
if (templateSettings.getDefaultShortcutChar() != getDefaultShortcutChar()) {
return true;
}
List<TemplateGroup> originalGroups = templateSettings.getTemplateGroups();
List<TemplateGroup> newGroups = getTemplateGroups();
return !checkAreEqual(collectTemplates(originalGroups), collectTemplates(newGroups));
}
private static List<TemplateImpl> collectTemplates(final List<TemplateGroup> groups) {
ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
for (TemplateGroup group : groups) {
result.addAll(group.getElements());
}
Collections.sort(result, new Comparator<TemplateImpl>(){
public int compare(final TemplateImpl o1, final TemplateImpl o2) {
final int groupsEqual = o1.getGroupName().compareTo(o2.getGroupName());
if (groupsEqual != 0) {
return groupsEqual;
}
return o1.getKey().compareTo(o2.getKey());
}
});
return result;
}
private boolean checkAreEqual(final List<TemplateImpl> originalGroup, final List<TemplateImpl> newGroup) {
if (originalGroup.size() != newGroup.size()) return false;
for (int i = 0; i < newGroup.size(); i++) {
TemplateImpl newTemplate = newGroup.get(i);
newTemplate.parseSegments();
TemplateImpl originalTemplate = originalGroup.get(i);
originalTemplate.parseSegments();
if (!originalTemplate.equals(newTemplate)) {
return false;
}
if (originalTemplate.isDeactivated() != newTemplate.isDeactivated()) {
return false;
}
if (!areOptionsEqual(newTemplate, originalTemplate)) {
return false;
}
if (!areContextsEqual(newTemplate, originalTemplate)) {
return false;
}
}
return true;
}
private boolean areContextsEqual(final TemplateImpl newTemplate, final TemplateImpl originalTemplate) {
Map<TemplateContextType, Boolean> templateContext = getTemplateContext(newTemplate);
for (TemplateContextType processor : templateContext.keySet()) {
if (originalTemplate.getTemplateContext().isEnabled(processor) != templateContext.get(processor).booleanValue())
return false;
}
return true;
}
private boolean areOptionsEqual(final TemplateImpl newTemplate, final TemplateImpl originalTemplate) {
Map<TemplateOptionalProcessor, Boolean> templateOptions = getTemplateOptions(newTemplate);
for (TemplateOptionalProcessor processor : templateOptions.keySet()) {
if (processor.isEnabled(originalTemplate) != templateOptions.get(processor).booleanValue()) return false;
}
return true;
}
private Map<TemplateContextType, Boolean> getTemplateContext(final TemplateImpl newTemplate) {
return myTemplateContext.get(getKey(newTemplate));
}
private Map<TemplateOptionalProcessor, Boolean> getTemplateOptions(final TemplateImpl newTemplate) {
return myTemplateOptions.get(getKey(newTemplate));
}
private char getDefaultShortcutChar() {
Object selectedItem = myExpandByCombo.getSelectedItem();
if (TAB.equals(selectedItem)) {
return TemplateSettings.TAB_CHAR;
}
else if (ENTER.equals(selectedItem)) {
return TemplateSettings.ENTER_CHAR;
}
else {
return TemplateSettings.SPACE_CHAR;
}
}
private List<TemplateGroup> getTemplateGroups() {
return myTemplateGroups;
}
private void fillPanel(JPanel optionsPanel) {
JPanel tablePanel = new JPanel();
tablePanel.setBorder(BorderFactory.createLineBorder(Color.gray));
tablePanel.setLayout(new BorderLayout());
tablePanel.add(createTable(), BorderLayout.CENTER);
JPanel tableButtonsPanel = new JPanel();
tableButtonsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tableButtonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.insets = new Insets(0, 0, 4, 0);
final JButton addButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.add"));
addButton.setEnabled(true);
myCopyButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.copy"));
myEditButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.edit"));
myRemoveButton = createButton(tableButtonsPanel, gbConstraints, CodeInsightBundle.message("templates.dialog.table.action.remove"));
if (getSchemesManager().isExportAvailable()) {
myExportButton = createButton(tableButtonsPanel, gbConstraints, "Share...");
myEditButton.setMnemonic('S');
myExportButton.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e) {
exportCurrentGroup();
}
});
}
if (getSchemesManager().isImportAvailable()) {
myImportButton = createButton(tableButtonsPanel, gbConstraints, "Import Shared...");
myImportButton.setMnemonic('I');
myImportButton.setEnabled(true);
myImportButton.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e) {
new SchemesToImportPopup<TemplateGroup, TemplateGroup>(TemplateListPanel.this){
protected void onSchemeSelected(final TemplateGroup scheme) {
for (TemplateImpl newTemplate : scheme.getElements()) {
for (TemplateImpl existingTemplate : collectAllTemplates()) {
if (existingTemplate.getKey().equals(newTemplate.getKey())) {
Messages.showMessageDialog(
TemplateListPanel.this,
CodeInsightBundle.message("dialog.edit.template.error.already.exists", existingTemplate.getKey(), existingTemplate.getGroupName()),
CodeInsightBundle.message("dialog.edit.template.error.title"),
Messages.getErrorIcon()
);
return;
}
}
}
insertNewGroup(scheme);
for (TemplateImpl template : scheme.getElements()) {
addTemplate(template);
}
}
}.show(getSchemesManager(), myTemplateGroups);
}
});
}
gbConstraints.weighty = 1;
tableButtonsPanel.add(new JPanel(), gbConstraints);
tablePanel.add(tableButtonsPanel, BorderLayout.EAST);
optionsPanel.add(tablePanel, BorderLayout.CENTER);
JPanel textPanel = new JPanel(new BorderLayout());
textPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
myEditor = TemplateEditorUtil.createEditor(true, "");
textPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
textPanel.add(createExpandByPanel(), BorderLayout.SOUTH);
textPanel.setPreferredSize(new Dimension(100, myEditor.getLineHeight() * 12));
optionsPanel.add(textPanel, BorderLayout.SOUTH);
addButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
}
);
myCopyButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
copyRow();
}
}
);
myEditButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
edit();
}
}
);
myRemoveButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
}
);
}
private Iterable<? extends TemplateImpl> collectAllTemplates() {
ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
for (TemplateGroup templateGroup : myTemplateGroups) {
result.addAll(templateGroup.getElements());
}
return result;
}
private void exportCurrentGroup() {
int selected = getSelectedIndex();
if (selected < 0) return;
ExportSchemeAction.doExport(getGroup(selected), getSchemesManager());
}
private static SchemesManager<TemplateGroup, TemplateGroup> getSchemesManager() {
return (TemplateSettings.getInstance()).getSchemesManager();
}
private static JButton createButton(final JPanel tableButtonsPanel, final GridBagConstraints gbConstraints, final String message) {
JButton button = new JButton(message);
button.setEnabled(false);
//button.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(button, gbConstraints);
return button;
}
private JPanel createExpandByPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.weighty = 0;
gbConstraints.insets = new Insets(4, 0, 0, 0);
gbConstraints.weightx = 0;
gbConstraints.gridy = 0;
// panel.add(createLabel("By default expand with "), gbConstraints);
panel.add(new JLabel(CodeInsightBundle.message("templates.dialog.shortcut.chooser.label")), gbConstraints);
gbConstraints.gridx = 1;
myExpandByCombo = new JComboBox();
myExpandByCombo.addItem(SPACE);
myExpandByCombo.addItem(TAB);
myExpandByCombo.addItem(ENTER);
panel.add(myExpandByCombo, gbConstraints);
gbConstraints.gridx = 2;
gbConstraints.weightx = 1;
panel.add(new JPanel(), gbConstraints);
return panel;
}
@Nullable
private TemplateKey getTemplateKey(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateImpl) {
return new TemplateKey((TemplateImpl)node.getUserObject());
}
}
return null;
}
@Nullable
private TemplateImpl getTemplate(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateImpl) {
return (TemplateImpl)node.getUserObject();
}
}
return null;
}
@Nullable
private TemplateGroup getGroup(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateGroup) {
return (TemplateGroup)node.getUserObject();
}
}
return null;
}
private void edit() {
int selected = getSelectedIndex();
if (selected < 0) return;
TemplateImpl template = getTemplate(selected);
DefaultMutableTreeNode oldTemplateNode = getNode(selected);
if (template == null) return;
String oldGroupName = template.getGroupName();
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.edit.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
TemplateGroup group = getTemplateGroup(template.getGroupName());
LOG.assertTrue(group != null, template.getGroupName());
dialog.apply();
if (!oldGroupName.equals(template.getGroupName())) {
TemplateGroup oldGroup = getTemplateGroup(oldGroupName);
if (oldGroup != null) {
oldGroup.removeElement(template);
}
template.setId(null);//To make it not equal with default template with the same name
JTree tree = myTree;
if (oldTemplateNode != null) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)oldTemplateNode.getParent();
removeNodeFromParent(oldTemplateNode);
if (parent.getChildCount() == 0) removeNodeFromParent(parent);
}
DefaultMutableTreeNode templateNode = addTemplate(template);
if (templateNode != null) {
TreePath newTemplatePath = new TreePath(templateNode.getPath());
tree.expandPath(newTemplatePath);
selected = tree.getRowForPath(newTemplatePath);
}
((DefaultTreeModel)myTree.getModel()).nodeStructureChanged(myTreeRoot);
}
myTree.setSelectionInterval(selected, selected);
updateTemplateTextArea();
}
private Map<TemplateOptionalProcessor, Boolean> getOptions(final TemplateImpl template) {
return getTemplateOptions(template);
}
@Nullable
private DefaultMutableTreeNode getNode(final int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
if (path != null) {
return (DefaultMutableTreeNode)path.getLastPathComponent();
}
return null;
}
@Nullable
private TemplateGroup getTemplateGroup(final String groupName) {
for (TemplateGroup group : myTemplateGroups) {
if (group.getName().equals(groupName)) return group;
}
return null;
}
private void addRow() {
TemplateImpl template = new TemplateImpl("", "", TemplateSettings.USER_GROUP_NAME);
myTemplateOptions.put(getKey(template), template.createOptions());
myTemplateContext.put(getKey(template), template.createContext());
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.add.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
}
private static int getKey(final TemplateImpl template) {
return System.identityHashCode(template);
}
private void copyRow() {
int selected = getSelectedIndex();
if (selected < 0) return;
TemplateImpl orTemplate = getTemplate(selected);
LOG.assertTrue(orTemplate != null);
TemplateImpl template = orTemplate.copy();
myTemplateOptions.put(getKey(template), getOptions(orTemplate));
myTemplateContext.put(getKey(template), getContext(orTemplate));
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.copy.live.template.title"), template, getTemplateGroups(),
(String)myExpandByCombo.getSelectedItem(), getOptions(template), getContext(template));
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
}
private Map<TemplateContextType, Boolean> getContext(final TemplateImpl template) {
return getTemplateContext(template);
}
private int getSelectedIndex() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null) {
return -1;
}
else {
return myTree.getRowForPath(selectionPath);
}
}
private void removeRow() {
int selected = getSelectedIndex(); // TODO
if (selected < 0) return;
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey != null) {
int result = Messages.showOkCancelDialog(this, CodeInsightBundle.message("template.delete.confirmation.text"),
CodeInsightBundle.message("template.delete.confirmation.title"),
Messages.getQuestionIcon());
if (result != DialogWrapper.OK_EXIT_CODE) return;
removeTemplateAt(selected);
}
else {
TemplateGroup group = getGroup(selected);
if (group != null) {
int result = Messages.showOkCancelDialog(this, CodeInsightBundle.message("template.delete.group.confirmation.text"),
CodeInsightBundle.message("template.delete.confirmation.title"),
Messages.getQuestionIcon());
if (result != DialogWrapper.OK_EXIT_CODE) return;
JTree tree = myTree;
TreePath path = tree.getPathForRow(selected);
myTemplateGroups.remove(group);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
removeNodeFromParent(node);
}
}
}
private JScrollPane createTable() {
myTreeRoot = new CheckedTreeNode(null);
myTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer(){
public void customizeCellRenderer(final JTree tree,
Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
value = ((DefaultMutableTreeNode)value).getUserObject();
if (value instanceof TemplateImpl) {
//getTextRenderer().setIcon(TEMPLATE_ICON);
getTextRenderer().append (((TemplateImpl)value).getKey(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
String description = ((TemplateImpl)value).getDescription();
if (description != null && description.length() > 0) {
getTextRenderer().append (" (" + description + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
else if (value instanceof TemplateGroup) {
//getTextRenderer().setIcon(TEMPLATE_GROUP_ICON);
getTextRenderer().append (((TemplateGroup)value).getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
}
}, myTreeRoot) {
@Override
protected void onNodeStateChanged(final CheckedTreeNode node) {
Object obj = node.getUserObject();
if (obj instanceof TemplateImpl) {
((TemplateImpl)obj).setDeactivated(!node.isChecked());
}
}
};
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
DefaultTreeSelectionModel selModel = new DefaultTreeSelectionModel();
myTree.setSelectionModel(selModel);
selModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(final TreeSelectionEvent e) {
boolean enableEditButton = false;
boolean enableRemoveButton = false;
boolean enableCopyButton = false;
boolean enableExportButton = false;
int selected = getSelectedIndex();
if (selected >= 0 && selected < myTree.getRowCount()) {
TemplateSettings templateSettings = TemplateSettings.getInstance();
TemplateImpl template = getTemplate(selected);
if (template != null) {
templateSettings.setLastSelectedTemplateKey(template.getKey());
} else {
templateSettings.setLastSelectedTemplateKey(null);
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getPathForRow(selected).getLastPathComponent();
enableExportButton = false;
enableEditButton = false;
enableCopyButton = false;
if (node.getUserObject() instanceof TemplateImpl) {
enableCopyButton = true;
if (template != null) {
TemplateGroup group = getTemplateGroup(template.getGroupName());
if (group != null && !getSchemesManager().isShared(group)) {
enableEditButton = true;
enableRemoveButton = true;
}
}
}
if (node.getUserObject() instanceof TemplateGroup) {
enableRemoveButton = true;
TemplateGroup group = (TemplateGroup)node.getUserObject();
enableExportButton = !getSchemesManager().isShared(group);
}
}
updateTemplateTextArea();
myEditor.getComponent().setEnabled(enableEditButton);
if (myCopyButton != null) {
myCopyButton.setEnabled(enableCopyButton);
myEditButton.setEnabled(enableEditButton);
myRemoveButton.setEnabled(enableRemoveButton);
}
if (myExportButton != null) {
myExportButton.setEnabled(enableExportButton);
}
if (myImportButton != null) {
myImportButton.setEnabled(true);
}
}
});
myTree.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
JComponent.WHEN_FOCUSED
);
myTree.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
JComponent.WHEN_FOCUSED
);
myTree.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
edit();
}
}
}
);
JScrollPane scrollpane = ScrollPaneFactory.createScrollPane(myTree);
if (myTemplateGroups.size() > 0) {
myTree.setSelectionInterval(0, 0);
}
scrollpane.setPreferredSize(new Dimension(600, 400));
return scrollpane;
}
private void updateTemplateTextArea() {
if (!myUpdateNeeded) return;
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
updateTemplateText();
}
}, 100);
}
private void updateTemplateText() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
int selected = getSelectedIndex();
if (selected < 0) {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
else {
TemplateImpl template = getTemplate(selected);
if (template != null) {
String text = template.getString();
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), text);
TemplateEditorUtil.setHighlighter(myEditor, template.getTemplateContext());
} else {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
}
}
});
}
@Nullable
private DefaultMutableTreeNode addTemplate(TemplateImpl template) {
TemplateGroup newGroup = getTemplateGroup(template.getGroupName());
if (newGroup == null) {
newGroup = new TemplateGroup(template.getGroupName());
insertNewGroup(newGroup);
}
if (!newGroup.contains(template)) {
newGroup.addElement(template);
}
CheckedTreeNode node = new CheckedTreeNode(template);
node.setChecked(!template.isDeactivated());
if (myTreeRoot.getChildCount() > 0) {
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)myTreeRoot.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)myTreeRoot.getChildAfter(child)) {
if (((TemplateGroup)child.getUserObject()).getName().equals(template.getGroupName())) {
int index = getIndexToInsert (child, template.getKey());
child.insert(node, index);
((DefaultTreeModel)myTree.getModel()).nodesWereInserted(child, new int[]{index});
setSelectedNode(node);
return node;
}
}
}
return null;
}
private void insertNewGroup(final TemplateGroup newGroup) {
myTemplateGroups.add(newGroup);
int index = getIndexToInsert(myTreeRoot, newGroup.getName());
DefaultMutableTreeNode groupNode = new CheckedTreeNode(newGroup);
myTreeRoot.insert(groupNode, index);
((DefaultTreeModel)myTree.getModel()).nodesWereInserted(myTreeRoot, new int[]{index});
}
private static int getIndexToInsert(DefaultMutableTreeNode parent, String key) {
if (parent.getChildCount() == 0) return 0;
int res = 0;
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)parent.getChildAfter(child)) {
Object o = child.getUserObject();
String key1 = o instanceof TemplateImpl ? ((TemplateImpl)o).getKey() : ((TemplateGroup)o).getName();
if (key1.compareTo(key) > 0) return res;
res++;
}
return res;
}
private void setSelectedNode(DefaultMutableTreeNode node) {
JTree tree = myTree;
TreePath path = new TreePath(node.getPath());
tree.expandPath(path.getParentPath());
int row = tree.getRowForPath(path);
myTree.setSelectionInterval(row, row);
//myTree.scrollRectToVisible(myTree.getR(row, 0, true)); TODO
}
private void removeTemplateAt(int row) {
JTree tree = myTree;
TreePath path = tree.getPathForRow(row);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
LOG.assertTrue(node.getUserObject() instanceof TemplateImpl);
TemplateImpl template = (TemplateImpl)node.getUserObject();
TemplateGroup templateGroup = getTemplateGroup(template.getGroupName());
if (templateGroup != null) {
templateGroup.removeElement(template);
}
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
TreePath treePathToSelect = (parent.getChildAfter(node) != null || parent.getChildCount() == 1 ?
tree.getPathForRow(row + 1) :
tree.getPathForRow(row - 1));
DefaultMutableTreeNode toSelect = treePathToSelect != null ? (DefaultMutableTreeNode)treePathToSelect.getLastPathComponent() : null;
removeNodeFromParent(node);
if (parent.getChildCount() == 0) {
myTemplateGroups.remove(parent.getUserObject());
removeNodeFromParent(parent);
}
if (toSelect != null) {
setSelectedNode(toSelect);
}
}
private void removeNodeFromParent(DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
int idx = parent.getIndex(node);
node.removeFromParent();
((DefaultTreeModel)myTree.getModel()).nodesWereRemoved(parent, new int[]{idx}, new TreeNode[]{node});
}
private void initTemplates(List<TemplateGroup> groups, String lastSelectedKey) {
myTreeRoot.removeAllChildren();
myTemplateGroups.clear();
for (TemplateGroup group : groups) {
myTemplateGroups.add((TemplateGroup)group.copy());
}
DefaultMutableTreeNode nodeToSelect = null;
for (TemplateGroup group : myTemplateGroups) {
CheckedTreeNode groupNode = new CheckedTreeNode(group);
List<TemplateImpl> templates = new ArrayList<TemplateImpl>(group.getElements());
Collections.sort(templates, new Comparator<TemplateImpl>(){
public int compare(final TemplateImpl o1, final TemplateImpl o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
for (final Object groupTemplate : templates) {
TemplateImpl template = (TemplateImpl)groupTemplate;
myTemplateOptions.put(getKey(template), template.createOptions());
myTemplateContext.put(getKey(template), template.createContext());
CheckedTreeNode node = new CheckedTreeNode(template);
node.setChecked(!template.isDeactivated());
groupNode.add(node);
if (lastSelectedKey != null && lastSelectedKey.equals(template.getKey())) {
nodeToSelect = node;
}
}
myTreeRoot.add(groupNode);
}
((DefaultTreeModel)myTree.getModel()).nodeStructureChanged(myTreeRoot);
if (nodeToSelect != null) {
JTree tree = myTree;
TreePath path = new TreePath(nodeToSelect.getPath());
tree.expandPath(path.getParentPath());
int rowToSelect = tree.getRowForPath(path);
myTree.setSelectionInterval(rowToSelect, rowToSelect);
/* TODO
final Rectangle rect = myTreeTable.getCellRect(rowToSelect, 0, true);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
myTreeTable.scrollRectToVisible(rect);
}
});*/
}
}
private static class TemplateKey implements Comparable {
private final String myKey;
private final String myGroupName;
public TemplateKey(TemplateImpl template) {
String key = template.getKey();
if (key == null) {
key = "";
}
myKey = key;
String groupName = template.getGroupName();
if (groupName == null) {
groupName = "";
}
myGroupName =groupName;
}
public boolean equals(Object obj) {
if (!(obj instanceof TemplateKey)) {
return false;
}
TemplateKey templateKey = (TemplateKey)obj;
return (myGroupName.compareTo(templateKey.myGroupName) == 0) &&
(myKey.compareTo(templateKey.myKey) == 0);
}
public int compareTo(Object obj) {
if (!(obj instanceof TemplateKey)) {
return 1;
}
TemplateKey templateKey = (TemplateKey)obj;
int result = myGroupName.compareTo(templateKey.myGroupName);
return result != 0 ? result : myKey.compareTo(templateKey.myKey);
}
}
class ActivationStateColumnInfo extends ColumnInfo {
public ActivationStateColumnInfo(String name) {
super(name);
}
public boolean isCellEditable(Object o) {
return o != null;
}
public void setValue(Object obj, Object aValue) {
obj = ((DefaultMutableTreeNode)obj).getUserObject();
if (obj instanceof TemplateImpl) {
TemplateImpl template = (TemplateImpl)obj;
boolean state = !((Boolean)aValue).booleanValue();
if (state != template.isDeactivated()) {
template.setDeactivated(!((Boolean)aValue).booleanValue());
}
}
}
public Class getColumnClass() {
return Boolean.class;
}
public Object valueOf(Object object) {
object = ((DefaultMutableTreeNode)object).getUserObject();
if (object instanceof TemplateImpl) {
return ((TemplateImpl)object).isDeactivated() ? Boolean.FALSE : Boolean.TRUE;
}
else {
return null;
}
}
}
}
| Preselect selected live template group when adding new template (IDEA-26128)
| platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java | Preselect selected live template group when adding new template (IDEA-26128) |
|
Java | apache-2.0 | bd8d1462061b349fcc3c44f4a86c2070296180c0 | 0 | doortts/forked-for-history,Limseunghwan/oss,violetag/demo,doortts/fork-yobi,brainagenet/yobi,yona-projects/yona,oolso/yobi,ahb0327/yobi,doortts/forked-for-history,Limseunghwan/oss,doortts/fork-yobi,ahb0327/yobi,bloodybear/yona,oolso/yobi,ahb0327/yobi,brainagenet/yobi,yona-projects/yona,bloodybear/yona,ihoneymon/yobi,brainagenet/yobi,bloodybear/yona,ihoneymon/yobi,oolso/yobi,naver/yobi,doortts/fork-yobi,ihoneymon/yobi,naver/yobi,bloodybear/yona,naver/yobi,doortts/forked-for-history,yona-projects/yona,yona-projects/yona,Limseunghwan/oss,violetag/demo,doortts/fork-yobi | /**
* Yobi, Project Hosting SW
*
* Copyright 2012 NAVER Corp.
* http://yobi.io
*
* @Author Sangcheol Hwang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package controllers;
import actions.AnonymousCheckAction;
import actions.DefaultProjectCheckAction;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Junction;
import com.avaje.ebean.Page;
import controllers.annotation.IsAllowed;
import info.schleichardt.play2.mailplugin.Mailer;
import models.*;
import models.enumeration.Operation;
import models.enumeration.ProjectScope;
import models.enumeration.RequestState;
import models.enumeration.ResourceType;
import models.enumeration.RoleType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.HtmlEmail;
import org.codehaus.jackson.node.ObjectNode;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.tmatesoft.svn.core.SVNException;
import play.Logger;
import play.data.Form;
import play.data.validation.ValidationError;
import play.db.ebean.Transactional;
import play.i18n.Messages;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import play.mvc.With;
import playRepository.Commit;
import playRepository.PlayRepository;
import playRepository.RepositoryService;
import scala.reflect.io.FileOperationException;
import utils.*;
import play.data.validation.Constraints.PatternValidator;
import validation.ExConstraints.RestrictedValidator;
import views.html.project.create;
import views.html.project.delete;
import views.html.project.home;
import views.html.project.setting;
import views.html.project.transfer;
import javax.servlet.ServletException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static play.data.Form.form;
import static play.libs.Json.toJson;
import static utils.LogoUtil.*;
import static utils.TemplateHelper.*;
public class ProjectApp extends Controller {
private static final int ISSUE_MENTION_SHOW_LIMIT = 2000;
private static final int MAX_FETCH_PROJECTS = 1000;
private static final int COMMIT_HISTORY_PAGE = 0;
private static final int COMMIT_HISTORY_SHOW_LIMIT = 10;
private static final int RECENLTY_ISSUE_SHOW_LIMIT = 10;
private static final int RECENLTY_POSTING_SHOW_LIMIT = 10;
private static final int RECENT_PULL_REQUEST_SHOW_LIMIT = 10;
private static final int PROJECT_COUNT_PER_PAGE = 10;
private static final String HTML = "text/html";
private static final String JSON = "application/json";
@With(AnonymousCheckAction.class)
@IsAllowed(Operation.UPDATE)
public static Result projectOverviewUpdate(String ownerId, String projectName){
Project targetProject = Project.findByOwnerAndProjectName(ownerId, projectName);
if (targetProject == null) {
return notFound(ErrorViews.NotFound.render("error.notfound"));
}
targetProject.overview = request().body().asJson().findPath("overview").getTextValue();
targetProject.save();
ObjectNode result = Json.newObject();
result.put("overview", targetProject.overview);
return ok(result);
}
@IsAllowed(Operation.READ)
public static Result project(String ownerId, String projectName)
throws IOException, ServletException, SVNException, GitAPIException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
List<History> histories = getProjectHistory(ownerId, project);
UserApp.currentUser().visits(project);
String tabId = StringUtils.defaultIfBlank(request().getQueryString("tabId"), "readme");
return ok(home.render(getTitleMessage(tabId), project, histories, tabId));
}
private static String getTitleMessage(String tabId) {
switch (tabId) {
case "history":
return "project.history.recent";
case "dashboard":
return "title.projectDashboard";
default:
case "readme":
return "title.projectHome";
}
}
private static List<History> getProjectHistory(String ownerId, Project project)
throws IOException, ServletException, SVNException, GitAPIException {
project.fixInvalidForkData();
PlayRepository repository = RepositoryService.getRepository(project);
List<Commit> commits = null;
try {
commits = repository.getHistory(COMMIT_HISTORY_PAGE, COMMIT_HISTORY_SHOW_LIMIT, null, null);
} catch (NoHeadException e) {
// NOOP
}
List<Issue> issues = Issue.findRecentlyCreated(project, RECENLTY_ISSUE_SHOW_LIMIT);
List<Posting> postings = Posting.findRecentlyCreated(project, RECENLTY_POSTING_SHOW_LIMIT);
List<PullRequest> pullRequests = PullRequest.findRecentlyReceived(project, RECENT_PULL_REQUEST_SHOW_LIMIT);
return History.makeHistory(ownerId, project, commits, issues, postings, pullRequests);
}
@With(AnonymousCheckAction.class)
public static Result newProjectForm() {
Form<Project> projectForm = form(Project.class).bindFromRequest("owner");
projectForm.discardErrors();
List<OrganizationUser> orgUserList = OrganizationUser.findByAdmin(UserApp.currentUser().id);
return ok(create.render("title.newProject", projectForm, orgUserList));
}
@IsAllowed(Operation.UPDATE)
public static Result settingForm(String ownerId, String projectName) throws Exception {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
PlayRepository repository = RepositoryService.getRepository(project);
return ok(setting.render("title.projectSetting", projectForm, project, repository.getBranches()));
}
@Transactional
public static Result newProject() throws Exception {
Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest();
String owner = filledNewProjectForm.field("owner").value();
User user = UserApp.currentUser();
Organization organization = Organization.findByName(owner);
if ((!AccessControl.isGlobalResourceCreatable(user))
|| (Organization.isNameExist(owner) && !OrganizationUser.isAdmin(organization.id, user.id))) {
return forbidden(ErrorViews.Forbidden.render("'" + user.name + "' has no permission"));
}
if (validateWhenNew(filledNewProjectForm)) {
return badRequest(create.render("title.newProject",
filledNewProjectForm, OrganizationUser.findByAdmin(user.id)));
}
Project project = filledNewProjectForm.get();
if (Organization.isNameExist(owner)) {
project.organization = organization;
}
ProjectUser.assignRole(user.id, Project.create(project), RoleType.MANAGER);
RepositoryService.createRepository(project);
saveProjectMenuSetting(project);
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
private static boolean validateWhenNew(Form<Project> newProjectForm) {
String owner = newProjectForm.field("owner").value();
String name = newProjectForm.field("name").value();
User user = User.findByLoginId(owner);
boolean ownerIsUser = User.isLoginIdExist(owner);
boolean ownerIsOrganization = Organization.isNameExist(owner);
if (!ownerIsUser && !ownerIsOrganization) {
newProjectForm.reject("owner", "project.owner.invalidate");
}
if (ownerIsUser && !UserApp.currentUser().id.equals(user.id)) {
newProjectForm.reject("owner", "project.owner.invalidate");
}
if (Project.exists(owner, name)) {
newProjectForm.reject("name", "project.name.duplicate");
}
ValidationError error = newProjectForm.error("name");
if (error != null) {
if (PatternValidator.message.equals(error.message())) {
newProjectForm.errors().remove("name");
newProjectForm.reject("name", "project.name.alert");
} else if (RestrictedValidator.message.equals(error.message())) {
newProjectForm.errors().remove("name");
newProjectForm.reject("name", "project.name.reserved.alert");
}
}
return newProjectForm.hasErrors();
}
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result settingProject(String ownerId, String projectName)
throws IOException, NoSuchAlgorithmException, UnsupportedOperationException, ServletException {
Form<Project> filledUpdatedProjectForm = form(Project.class).bindFromRequest();
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PlayRepository repository = RepositoryService.getRepository(project);
if (validateWhenUpdate(ownerId, filledUpdatedProjectForm)) {
return badRequest(setting.render("title.projectSetting",
filledUpdatedProjectForm, project, repository.getBranches()));
}
Project updatedProject = filledUpdatedProjectForm.get();
FilePart filePart = request().body().asMultipartFormData().getFile("logoPath");
if (!isEmptyFilePart(filePart)) {
Attachment.deleteAll(updatedProject.asResource());
new Attachment().store(filePart.getFile(), filePart.getFilename(), updatedProject.asResource());
}
Map<String, String[]> data = request().body().asMultipartFormData().asFormUrlEncoded();
String defaultBranch = HttpUtil.getFirstValueFromQuery(data, "defaultBranch");
if (StringUtils.isNotEmpty(defaultBranch)) {
repository.setDefaultBranch(defaultBranch);
}
if (!project.name.equals(updatedProject.name)) {
if (!repository.renameTo(updatedProject.name)) {
throw new FileOperationException("fail repository rename to " + project.owner + "/" + updatedProject.name);
}
}
updatedProject.update();
saveProjectMenuSetting(updatedProject);
return redirect(routes.ProjectApp.settingForm(ownerId, updatedProject.name));
}
private static void saveProjectMenuSetting(Project project) {
Form<ProjectMenuSetting> filledUpdatedProjectMenuSettingForm = form(ProjectMenuSetting.class).bindFromRequest();
ProjectMenuSetting updatedProjectMenuSetting = filledUpdatedProjectMenuSettingForm.get();
project.refresh();
updatedProjectMenuSetting.project = project;
if (project.menuSetting == null) {
updatedProjectMenuSetting.save();
} else {
updatedProjectMenuSetting.id = project.menuSetting.id;
updatedProjectMenuSetting.update();
}
}
private static boolean validateWhenUpdate(String loginId, Form<Project> updateProjectForm) {
Long id = Long.parseLong(updateProjectForm.field("id").value());
String name = updateProjectForm.field("name").value();
if (!Project.projectNameChangeable(id, loginId, name)) {
flash(Constants.WARNING, "project.name.duplicate");
updateProjectForm.reject("name", "project.name.duplicate");
}
FilePart filePart = request().body().asMultipartFormData().getFile("logoPath");
if (!isEmptyFilePart(filePart)) {
if (!isImageFile(filePart.getFilename())) {
flash(Constants.WARNING, "project.logo.alert");
updateProjectForm.reject("logoPath", "project.logo.alert");
} else if (filePart.getFile().length() > LOGO_FILE_LIMIT_SIZE) {
flash(Constants.WARNING, "project.logo.fileSizeAlert");
updateProjectForm.reject("logoPath", "project.logo.fileSizeAlert");
}
}
ValidationError error = updateProjectForm.error("name");
if (error != null) {
if (PatternValidator.message.equals(error.message())) {
flash(Constants.WARNING, "project.name.alert");
updateProjectForm.errors().remove("name");
updateProjectForm.reject("name", "project.name.alert");
} else if (RestrictedValidator.message.equals(error.message())) {
flash(Constants.WARNING, "project.name.reserved.alert");
updateProjectForm.errors().remove("name");
updateProjectForm.reject("name", "project.name.reserved.alert");
}
}
return updateProjectForm.hasErrors();
}
@IsAllowed(Operation.DELETE)
public static Result deleteForm(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
return ok(delete.render("title.projectDelete", projectForm, project));
}
@Transactional
@IsAllowed(Operation.DELETE)
public static Result deleteProject(String ownerId, String projectName) throws Exception {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
project.delete();
RepositoryService.deleteRepository(project);
if (HttpUtil.isRequestedWithXHR(request())){
response().setHeader("Location", routes.Application.index().toString());
return status(204);
}
return redirect(routes.Application.index());
}
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result members(String loginId, String projectName) {
Project project = Project.findByOwnerAndProjectName(loginId, projectName);
project.cleanEnrolledUsers();
return ok(views.html.project.members.render("title.projectMembers",
ProjectUser.findMemberListByProject(project.id), project,
Role.findProjectRoles()));
}
@IsAllowed(Operation.READ)
public static Result mentionList(String loginId, String projectName, Long number, String resourceType) {
String prefer = HttpUtil.getPreferType(request(), HTML, JSON);
if (prefer == null) {
return status(Http.Status.NOT_ACCEPTABLE);
} else {
response().setHeader("Vary", "Accept");
}
Project project = Project.findByOwnerAndProjectName(loginId, projectName);
List<User> userList = new ArrayList<>();
collectAuthorAndCommenter(project, number, userList, resourceType);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
private static List<Map<String, String>> getIssueList(Project project) {
List<Map<String, String>> mentionListOfIssues = new ArrayList<>();
collectedIssuesToMap(mentionListOfIssues, getMentionIssueList(project));
return mentionListOfIssues;
}
private static List<Map<String, String>> getUserList(Project project, List<User> userList) {
List<Map<String, String>> mentionListOfUser = new ArrayList<>();
collectedUsersToMentionList(mentionListOfUser, userList);
addProjectNameToMentionList(mentionListOfUser, project);
addOrganizationNameToMentionList(mentionListOfUser, project);
return mentionListOfUser;
}
private static void addProjectNameToMentionList(List<Map<String, String>> users, Project project) {
Map<String, String> projectUserMap = new HashMap<>();
if(project != null){
projectUserMap.put("loginid", project.owner+"/" + project.name);
projectUserMap.put("username", project.name );
projectUserMap.put("name", project.name);
projectUserMap.put("image", urlToProjectLogo(project).toString());
users.add(projectUserMap);
}
}
private static void addOrganizationNameToMentionList(List<Map<String, String>> users, Project project) {
Map<String, String> projectUserMap = new HashMap<>();
if(project != null && project.organization != null){
projectUserMap.put("loginid", project.organization.name);
projectUserMap.put("username", project.organization.name);
projectUserMap.put("name", project.organization.name);
projectUserMap.put("image", urlToOrganizationLogo(project.organization).toString());
users.add(projectUserMap);
}
}
private static void collectedIssuesToMap(List<Map<String, String>> mentionList,
List<Issue> issueList) {
for (Issue issue : issueList) {
Map<String, String> projectIssueMap = new HashMap<>();
projectIssueMap.put("name", issue.getNumber().toString() + issue.title);
projectIssueMap.put("issueNo", issue.getNumber().toString());
projectIssueMap.put("title", issue.title);
mentionList.add(projectIssueMap);
}
}
private static List<Issue> getMentionIssueList(Project project) {
return Issue.finder.where()
.eq("project.id", project.isForkedFromOrigin() ? project.originalProject.id : project.id)
.orderBy("createdDate desc")
.setMaxRows(ISSUE_MENTION_SHOW_LIMIT)
.findList();
}
@IsAllowed(Operation.READ)
public static Result mentionListAtCommitDiff(String ownerId, String projectName, String commitId, Long pullRequestId)
throws IOException, UnsupportedOperationException, ServletException, SVNException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PullRequest pullRequest;
Project fromProject = project;
if (pullRequestId != -1) {
pullRequest = PullRequest.findById(pullRequestId);
if (pullRequest != null) {
fromProject = pullRequest.fromProject;
}
}
Commit commit = RepositoryService.getRepository(fromProject).getCommit(commitId);
List<User> userList = new ArrayList<>();
addCommitAuthor(commit, userList);
addCodeCommenters(commitId, fromProject.id, userList);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
@IsAllowed(Operation.READ)
public static Result mentionListAtPullRequest(String ownerId, String projectName, String commitId, Long pullRequestId)
throws IOException, UnsupportedOperationException, ServletException, SVNException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PullRequest pullRequest = PullRequest.findById(pullRequestId);
List<User> userList = new ArrayList<>();
addCommentAuthors(pullRequestId, userList);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
if(!commitId.isEmpty()) {
addCommitAuthor(RepositoryService.getRepository(pullRequest.fromProject).getCommit(commitId), userList);
}
User contributor = pullRequest.contributor;
if(!userList.contains(contributor)) {
userList.add(contributor);
}
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
private static void addCommentAuthors(Long pullRequestId, List<User> userList) {
List<CommentThread> threads = PullRequest.findById(pullRequestId).commentThreads;
for (CommentThread thread : threads) {
for (ReviewComment comment : thread.reviewComments) {
final User commenter = User.findByLoginId(comment.author.loginId);
if(userList.contains(commenter)) {
userList.remove(commenter);
}
userList.add(commenter);
}
}
Collections.reverse(userList);
}
@IsAllowed(Operation.DELETE)
public static Result transferForm(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
return ok(transfer.render("title.projectTransfer", projectForm, project));
}
@Transactional
@IsAllowed(Operation.DELETE)
public static Result transferProject(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
String destination = request().getQueryString("owner");
User destOwner = User.findByLoginId(destination);
Organization destOrg = Organization.findByName(destination);
if (destOwner.isAnonymous() && destOrg == null) {
return badRequest(ErrorViews.BadRequest.render());
}
User projectOwner = User.findByLoginId(project.owner);
Organization projectOrg = Organization.findByName(project.owner);
if((destOwner != null && destOwner.equals(projectOwner)) || (projectOrg != null && projectOrg.equals(destOrg))) {
flash(Constants.INFO, "project.transfer.has.same.owner");
Form<Project> projectForm = form(Project.class).fill(project);
return ok(transfer.render("title.projectTransfer", projectForm, project));
}
ProjectTransfer pt = null;
// make a request to move to an user
if (!destOwner.isAnonymous()) {
pt = ProjectTransfer.requestNewTransfer(project, UserApp.currentUser(), destOwner.loginId);
}
// make a request to move to an group
if (destOrg != null) {
pt = ProjectTransfer.requestNewTransfer(project, UserApp.currentUser(), destOrg.name);
}
sendTransferRequestMail(pt);
flash(Constants.INFO, "project.transfer.is.requested");
// if the request is sent by XHR, response with 204 204 No Content and Location header.
String url = routes.ProjectApp.project(ownerId, projectName).url();
if (HttpUtil.isRequestedWithXHR(request())) {
response().setHeader("Location", url);
return status(204);
}
return redirect(url);
}
@Transactional
@With(AnonymousCheckAction.class)
public static synchronized Result acceptTransfer(Long id, String confirmKey) throws IOException, ServletException {
ProjectTransfer pt = ProjectTransfer.findValidOne(id);
if (pt == null) {
return notFound(ErrorViews.NotFound.render());
}
if (confirmKey == null || !pt.confirmKey.equals(confirmKey)) {
return badRequest(ErrorViews.BadRequest.render());
}
if (!AccessControl.isAllowed(UserApp.currentUser(), pt.asResource(), Operation.ACCEPT)) {
return forbidden(ErrorViews.Forbidden.render());
}
Project project = pt.project;
// Change the project's name and move the repository.
String newProjectName = Project.newProjectName(pt.destination, project.name);
PlayRepository repository = RepositoryService.getRepository(project);
repository.move(project.owner, project.name, pt.destination, newProjectName);
User newOwnerUser = User.findByLoginId(pt.destination);
Organization newOwnerOrg = Organization.findByName(pt.destination);
// Change the project's information.
project.owner = pt.destination;
project.name = newProjectName;
if (newOwnerOrg != null) {
project.organization = newOwnerOrg;
} else {
project.organization = null;
}
project.update();
// Change roles.
if (!newOwnerUser.isAnonymous()) {
ProjectUser.assignRole(newOwnerUser.id, project.id, RoleType.MANAGER);
}
if (ProjectUser.isManager(pt.sender.id, project.id)) {
ProjectUser.assignRole(pt.sender.id, project.id, RoleType.MEMBER);
}
// Change the tranfer's status to be accepted.
pt.newProjectName = newProjectName;
pt.accepted = true;
pt.update();
// If the opposite request is exists, delete it.
ProjectTransfer.deleteExisting(project, pt.sender, pt.destination);
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
private static void sendTransferRequestMail(ProjectTransfer pt) {
HtmlEmail email = new HtmlEmail();
try {
String acceptUrl = pt.getAcceptUrl();
String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n"
+ Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner, pt.destination) + "\n"
+ Messages.get("transfer.message.link") + "\n\n"
+ acceptUrl + "\n\n"
+ Messages.get("transfer.message.deadline") + "\n\n"
+ Messages.get("transfer.message.thank");
email.setFrom(Config.getEmailFromSmtp(), pt.sender.name);
email.addTo(Config.getEmailFromSmtp(), "Yobi");
User to = User.findByLoginId(pt.destination);
if (!to.isAnonymous()) {
email.addBcc(to.email, to.name);
}
Organization org = Organization.findByName(pt.destination);
if (org != null) {
List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org);
for(OrganizationUser admin : admins) {
email.addBcc(admin.user.email, admin.user.name);
}
}
email.setSubject(String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId));
email.setHtmlMsg(Markdown.render(message));
email.setTextMsg(message);
email.setCharset("utf-8");
email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">");
email.setSentDate(pt.requested);
Mailer.send(email);
String escapedTitle = email.getSubject().replace("\"", "\\\"");
String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
play.Logger.of("mail").info(logEntry);
} catch (Exception e) {
Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
}
}
private static void addCodeCommenters(String commitId, Long projectId, List<User> userList) {
Project project = Project.find.byId(projectId);
if (RepositoryService.VCS_GIT.equals(project.vcs)) {
List<ReviewComment> comments = ReviewComment.find
.fetch("thread")
.where()
.eq("thread.commitId",commitId)
.eq("thread.project", project)
.eq("thread.pullRequest", null).findList();
for (ReviewComment comment : comments) {
User commentAuthor = User.findByLoginId(comment.author.loginId);
if (userList.contains(commentAuthor)) {
userList.remove(commentAuthor);
}
userList.add(commentAuthor);
}
} else {
List<CommitComment> comments = CommitComment.find.where().eq("commitId",
commitId).eq("project.id", projectId).findList();
for (CommitComment codeComment : comments) {
User commentAuthor = User.findByLoginId(codeComment.authorLoginId);
if (userList.contains(commentAuthor)) {
userList.remove(commentAuthor);
}
userList.add(commentAuthor);
}
}
Collections.reverse(userList);
}
private static void addCommitAuthor(Commit commit, List<User> userList) {
if (!commit.getAuthor().isAnonymous() && !userList.contains(commit.getAuthor())) {
userList.add(commit.getAuthor());
}
//fallback: additional search by email id
if (commit.getAuthorEmail() != null) {
User authorByEmail = User.findByLoginId(commit.getAuthorEmail().substring(0, commit.getAuthorEmail().lastIndexOf("@")));
if (!authorByEmail.isAnonymous() && !userList.contains(authorByEmail)) {
userList.add(authorByEmail);
}
}
}
private static void collectAuthorAndCommenter(Project project, Long number, List<User> userList, String resourceType) {
AbstractPosting posting;
switch (ResourceType.getValue(resourceType)) {
case ISSUE_POST:
posting = AbstractPosting.findByNumber(Issue.finder, project, number);
break;
case BOARD_POST:
posting = AbstractPosting.findByNumber(Posting.finder, project, number);
break;
default:
return;
}
if (posting != null) {
for (Comment comment: posting.getComments()) {
User commentUser = User.findByLoginId(comment.authorLoginId);
if (userList.contains(commentUser)) {
userList.remove(commentUser);
}
userList.add(commentUser);
}
Collections.reverse(userList); // recent commenter first!
User postAuthor = User.findByLoginId(posting.authorLoginId);
if (!userList.contains(postAuthor)) {
userList.add(postAuthor);
}
}
}
private static void collectedUsersToMentionList(List<Map<String, String>> users, List<User> userList) {
for (User user: userList) {
Map<String, String> projectUserMap = new HashMap<>();
if (user != null && !user.loginId.equals(Constants.ADMIN_LOGIN_ID)) {
projectUserMap.put("loginid", user.loginId);
projectUserMap.put("username", user.name);
projectUserMap.put("name", user.name + user.loginId);
projectUserMap.put("image", user.avatarUrl());
users.add(projectUserMap);
}
}
}
private static void addProjectMemberList(Project project, List<User> userList) {
for (ProjectUser projectUser: project.projectUser) {
if (!userList.contains(projectUser.user)) {
userList.add(projectUser.user);
}
}
}
private static void addGroupMemberList(Project project, List<User> userList) {
if (!project.hasGroup()) {
return;
}
for (OrganizationUser organizationUser : project.organization.users) {
if (!userList.contains(organizationUser.user)) {
userList.add(organizationUser.user);
}
}
}
@Transactional
@With(DefaultProjectCheckAction.class)
@IsAllowed(Operation.UPDATE)
public static Result newMember(String ownerId, String projectName) {
Form<User> addMemberForm = form(User.class).bindFromRequest();
User newMember = User.findByLoginId(addMemberForm.field("loginId").value());
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (isErrorOnAddMemberForm(newMember, project, addMemberForm)) {
if(HttpUtil.isJSONPreferred(request())){
return badRequest(addMemberForm.errorsAsJson());
}
List<ValidationError> errors = addMemberForm.errors().get("loginId");
flash(Constants.WARNING, errors.get(errors.size() - 1).message());
return redirect(routes.ProjectApp.members(ownerId, projectName));
}
ProjectUser.assignRole(newMember.id, project.id, RoleType.MEMBER);
project.cleanEnrolledUsers();
NotificationEvent.afterMemberRequest(project, newMember, RequestState.ACCEPT);
if(HttpUtil.isJSONPreferred(request())){
return ok("{}");
}
return redirect(routes.ProjectApp.members(ownerId, projectName));
}
private static boolean isErrorOnAddMemberForm(User user, Project project, Form<User> addMemberForm) {
if (addMemberForm.hasErrors()) {
addMemberForm.reject("loginId", "project.members.addMember");
} else if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) {
addMemberForm.reject("loginId", "project.member.isManager");
} else if (user.isAnonymous()) {
addMemberForm.reject("loginId", "project.member.notExist");
} else if (ProjectUser.isMember(user.id, project.id)) {
addMemberForm.reject("loginId", "project.member.alreadyMember");
}
return addMemberForm.hasErrors();
}
/**
* Returns OK(200) with {@code location} which is represented as JSON .
*
* Since returning redirect response(3xx) to Ajax request causes unexpected result, this function returns OK(200) containing redirect location.
* The client will check {@code location} and have a page move to the location.
*
* @param location
* @return
*/
private static Result okWithLocation(String location) {
ObjectNode result = Json.newObject();
result.put("location", location);
return ok(result);
}
/**
* @param ownerId the user login id
* @param projectName the project name
* @param userId
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result deleteMember(String ownerId, String projectName, Long userId) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
User deleteMember = User.find.byId(userId);
if (!UserApp.currentUser().id.equals(userId)
&& !AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
if (project.isOwner(deleteMember)) {
return forbidden(ErrorViews.Forbidden.render("project.member.ownerCannotLeave", project));
}
ProjectUser.delete(userId, project.id);
if (UserApp.currentUser().id.equals(userId)) {
if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
return okWithLocation(routes.ProjectApp.project(project.owner, project.name).url());
} else {
return okWithLocation(routes.Application.index().url());
}
} else {
return okWithLocation(routes.ProjectApp.members(ownerId, projectName).url());
}
}
/**
* @param ownerId the user login id
* @param projectName the project name
* @param userId the user id
* @return
*/
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result editMember(String ownerId, String projectName, Long userId) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
User editMember = User.find.byId(userId);
if (project.isOwner(editMember)) {
return badRequest(ErrorViews.Forbidden.render("project.member.ownerMustBeAManager", project));
}
ProjectUser.assignRole(userId, project.id, form(Role.class).bindFromRequest().get().id);
return status(Http.Status.NO_CONTENT);
}
/**
* @param query the query
* @param pageNum the page num
* @return
*/
public static Result projects(String query, int pageNum) {
String prefer = HttpUtil.getPreferType(request(), HTML, JSON);
if (prefer == null) {
return status(Http.Status.NOT_ACCEPTABLE);
}
response().setHeader("Vary", "Accept");
if (prefer.equals(JSON)) {
return getProjectsToJSON(query);
} else {
return getPagingProjects(query, pageNum);
}
}
private static Result getPagingProjects(String query, int pageNum) {
ExpressionList<Project> el = createProjectSearchExpressionList(query);
Set<Long> labelIds = LabelSearchUtil.getLabelIds(request());
if (CollectionUtils.isNotEmpty(labelIds)) {
el.add(LabelSearchUtil.createLabelSearchExpression(el.query(), labelIds));
}
el.orderBy("createdDate desc");
Page<Project> projects = el.findPagingList(PROJECT_COUNT_PER_PAGE).getPage(pageNum - 1);
return ok(views.html.project.list.render("title.projectList", projects, query));
}
private static Result getProjectsToJSON(String query) {
ExpressionList<Project> el = createProjectSearchExpressionList(query);
int total = el.findRowCount();
if (total > MAX_FETCH_PROJECTS) {
el.setMaxRows(MAX_FETCH_PROJECTS);
response().setHeader("Content-Range", "items " + MAX_FETCH_PROJECTS + "/" + total);
}
List<String> projectNames = new ArrayList<>();
for (Project project: el.findList()) {
projectNames.add(project.owner + "/" + project.name);
}
return ok(toJson(projectNames));
}
private static ExpressionList<Project> createProjectSearchExpressionList(String query) {
ExpressionList<Project> el = Project.find.where();
if (StringUtils.isNotBlank(query)) {
Junction<Project> junction = el.disjunction();
junction.icontains("owner", query)
.icontains("name", query)
.icontains("overview", query);
List<Object> ids = Project.find.where().icontains("labels.name", query).findIds();
if (!ids.isEmpty()) {
junction.idIn(ids);
}
junction.endJunction();
}
if (!UserApp.currentUser().isSiteManager()) {
el.eq("projectScope", ProjectScope.PUBLIC);
}
return el;
}
/**
* @param ownerId the owner login id
* @param projectName the project name
* @return
*/
@IsAllowed(Operation.READ)
public static Result labels(String ownerId, String projectName) {
if (!request().accepts("application/json")) {
return status(Http.Status.NOT_ACCEPTABLE);
}
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Map<Long, Map<String, String>> labels = new HashMap<>();
for (Label label: project.labels) {
labels.put(label.id, convertToMap(label));
}
return ok(toJson(labels));
}
/**
* convert from some part of {@link models.Label} to {@link java.util.Map}
* @param label {@link models.Label} object
* @return label's map data
*/
private static Map<String, String> convertToMap(Label label) {
Map<String, String> tagMap = new HashMap<>();
tagMap.put("category", label.category);
tagMap.put("name", label.name);
return tagMap;
}
/**
* @param ownerId the owner name
* @param projectName the project name
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result attachLabel(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
// Get category and name from the request. Return 400 Bad Request if name is not given.
Map<String, String[]> data = request().body().asFormUrlEncoded();
String category = HttpUtil.getFirstValueFromQuery(data, "category");
String name = HttpUtil.getFirstValueFromQuery(data, "name");
if (StringUtils.isEmpty(name)) {
// A label must have its name.
return badRequest(ErrorViews.BadRequest.render("Label name is missing.", project));
}
Label label = Label.find
.where().eq("category", category).eq("name", name).findUnique();
boolean isCreated = false;
if (label == null) {
// Create new label if there is no label which has the given name.
label = new Label(category, name);
label.projects.add(project);
label.save();
isCreated = true;
}
Boolean isAttached = project.attachLabel(label);
if (!isCreated && !isAttached) {
// Something is wrong. This case is not possible.
play.Logger.warn(
"A label '" + label + "' is created but failed to attach to project '" + project + "'.");
}
if (isAttached) {
// Return the attached label. The return type is Map<Long, Map<String, String>>
// even if there is only one label, to unify the return type with
// ProjectApp.labels().
Map<Long, Map<String, String>> labels = new HashMap<>();
labels.put(label.id, convertToMap(label));
if (isCreated) {
return created(toJson(labels));
} else {
return ok(toJson(labels));
}
} else {
// Return 204 No Content if the label is already attached.
return status(Http.Status.NO_CONTENT);
}
}
/**
* @param ownerId the owner name
* @param projectName the project name
* @param id the id
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result detachLabel(String ownerId, String projectName, Long id) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
// _method must be 'delete'
Map<String, String[]> data = request().body().asFormUrlEncoded();
if (!HttpUtil.getFirstValueFromQuery(data, "_method").toLowerCase()
.equals("delete")) {
return badRequest(ErrorViews.BadRequest.render("_method must be 'delete'.", project));
}
Label tag = Label.find.byId(id);
if (tag == null) {
return notFound(ErrorViews.NotFound.render("error.notfound"));
}
project.detachLabel(tag);
return status(Http.Status.NO_CONTENT);
}
@Transactional
@With(AnonymousCheckAction.class)
@IsAllowed(Operation.DELETE)
public static Result deletePushedBranch(String ownerId, String projectName, Long id) {
PushedBranch pushedBranch = PushedBranch.find.byId(id);
if (pushedBranch != null) {
pushedBranch.delete();
}
return ok();
}
}
| app/controllers/ProjectApp.java | /**
* Yobi, Project Hosting SW
*
* Copyright 2012 NAVER Corp.
* http://yobi.io
*
* @Author Sangcheol Hwang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package controllers;
import actions.AnonymousCheckAction;
import actions.DefaultProjectCheckAction;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Junction;
import com.avaje.ebean.Page;
import controllers.annotation.IsAllowed;
import info.schleichardt.play2.mailplugin.Mailer;
import models.*;
import models.enumeration.Operation;
import models.enumeration.ProjectScope;
import models.enumeration.RequestState;
import models.enumeration.ResourceType;
import models.enumeration.RoleType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.HtmlEmail;
import org.codehaus.jackson.node.ObjectNode;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.tmatesoft.svn.core.SVNException;
import play.Logger;
import play.data.Form;
import play.data.validation.ValidationError;
import play.db.ebean.Transactional;
import play.i18n.Messages;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import play.mvc.With;
import playRepository.Commit;
import playRepository.PlayRepository;
import playRepository.RepositoryService;
import scala.reflect.io.FileOperationException;
import utils.*;
import play.data.validation.Constraints.PatternValidator;
import validation.ExConstraints.RestrictedValidator;
import views.html.project.create;
import views.html.project.delete;
import views.html.project.home;
import views.html.project.setting;
import views.html.project.transfer;
import javax.servlet.ServletException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static play.data.Form.form;
import static play.libs.Json.toJson;
import static utils.LogoUtil.*;
import static utils.TemplateHelper.*;
public class ProjectApp extends Controller {
private static final int ISSUE_MENTION_SHOW_LIMIT = 2000;
private static final int MAX_FETCH_PROJECTS = 1000;
private static final int COMMIT_HISTORY_PAGE = 0;
private static final int COMMIT_HISTORY_SHOW_LIMIT = 10;
private static final int RECENLTY_ISSUE_SHOW_LIMIT = 10;
private static final int RECENLTY_POSTING_SHOW_LIMIT = 10;
private static final int RECENT_PULL_REQUEST_SHOW_LIMIT = 10;
private static final int PROJECT_COUNT_PER_PAGE = 10;
private static final String HTML = "text/html";
private static final String JSON = "application/json";
@With(AnonymousCheckAction.class)
@IsAllowed(Operation.UPDATE)
public static Result projectOverviewUpdate(String ownerId, String projectName){
Project targetProject = Project.findByOwnerAndProjectName(ownerId, projectName);
if (targetProject == null) {
return notFound(ErrorViews.NotFound.render("error.notfound"));
}
targetProject.overview = request().body().asJson().findPath("overview").getTextValue();
targetProject.save();
ObjectNode result = Json.newObject();
result.put("overview", targetProject.overview);
return ok(result);
}
@IsAllowed(Operation.READ)
public static Result project(String ownerId, String projectName)
throws IOException, ServletException, SVNException, GitAPIException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
List<History> histories = getProjectHistory(ownerId, project);
UserApp.currentUser().visits(project);
String tabId = StringUtils.defaultIfBlank(request().getQueryString("tabId"), "readme");
return ok(home.render(getTitleMessage(tabId), project, histories, tabId));
}
private static String getTitleMessage(String tabId) {
switch (tabId) {
case "history":
return "project.history.recent";
case "dashboard":
return "title.projectDashboard";
default:
case "readme":
return "title.projectHome";
}
}
private static List<History> getProjectHistory(String ownerId, Project project)
throws IOException, ServletException, SVNException, GitAPIException {
project.fixInvalidForkData();
PlayRepository repository = RepositoryService.getRepository(project);
List<Commit> commits = null;
try {
commits = repository.getHistory(COMMIT_HISTORY_PAGE, COMMIT_HISTORY_SHOW_LIMIT, null, null);
} catch (NoHeadException e) {
// NOOP
}
List<Issue> issues = Issue.findRecentlyCreated(project, RECENLTY_ISSUE_SHOW_LIMIT);
List<Posting> postings = Posting.findRecentlyCreated(project, RECENLTY_POSTING_SHOW_LIMIT);
List<PullRequest> pullRequests = PullRequest.findRecentlyReceived(project, RECENT_PULL_REQUEST_SHOW_LIMIT);
return History.makeHistory(ownerId, project, commits, issues, postings, pullRequests);
}
@With(AnonymousCheckAction.class)
public static Result newProjectForm() {
Form<Project> projectForm = form(Project.class).bindFromRequest("owner");
projectForm.discardErrors();
List<OrganizationUser> orgUserList = OrganizationUser.findByAdmin(UserApp.currentUser().id);
return ok(create.render("title.newProject", projectForm, orgUserList));
}
@IsAllowed(Operation.UPDATE)
public static Result settingForm(String ownerId, String projectName) throws Exception {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
PlayRepository repository = RepositoryService.getRepository(project);
return ok(setting.render("title.projectSetting", projectForm, project, repository.getBranches()));
}
@Transactional
public static Result newProject() throws Exception {
Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest();
String owner = filledNewProjectForm.field("owner").value();
User user = UserApp.currentUser();
Organization organization = Organization.findByName(owner);
if ((!AccessControl.isGlobalResourceCreatable(user))
|| (Organization.isNameExist(owner) && !OrganizationUser.isAdmin(organization.id, user.id))) {
return forbidden(ErrorViews.Forbidden.render("'" + user.name + "' has no permission"));
}
if (validateWhenNew(filledNewProjectForm)) {
return badRequest(create.render("title.newProject",
filledNewProjectForm, OrganizationUser.findByAdmin(user.id)));
}
Project project = filledNewProjectForm.get();
if (Organization.isNameExist(owner)) {
project.organization = organization;
}
ProjectUser.assignRole(user.id, Project.create(project), RoleType.MANAGER);
RepositoryService.createRepository(project);
saveProjectMenuSetting(project);
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
private static boolean validateWhenNew(Form<Project> newProjectForm) {
String owner = newProjectForm.field("owner").value();
String name = newProjectForm.field("name").value();
User user = User.findByLoginId(owner);
boolean ownerIsUser = User.isLoginIdExist(owner);
boolean ownerIsOrganization = Organization.isNameExist(owner);
if (!ownerIsUser && !ownerIsOrganization) {
newProjectForm.reject("owner", "project.owner.invalidate");
}
if (ownerIsUser && !UserApp.currentUser().id.equals(user.id)) {
newProjectForm.reject("owner", "project.owner.invalidate");
}
if (Project.exists(owner, name)) {
newProjectForm.reject("name", "project.name.duplicate");
}
ValidationError error = newProjectForm.error("name");
if (error != null) {
if (PatternValidator.message.equals(error.message())) {
newProjectForm.errors().remove("name");
newProjectForm.reject("name", "project.name.alert");
} else if (RestrictedValidator.message.equals(error.message())) {
newProjectForm.errors().remove("name");
newProjectForm.reject("name", "project.name.reserved.alert");
}
}
return newProjectForm.hasErrors();
}
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result settingProject(String ownerId, String projectName)
throws IOException, NoSuchAlgorithmException, UnsupportedOperationException, ServletException {
Form<Project> filledUpdatedProjectForm = form(Project.class).bindFromRequest();
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PlayRepository repository = RepositoryService.getRepository(project);
if (validateWhenUpdate(ownerId, filledUpdatedProjectForm)) {
return badRequest(setting.render("title.projectSetting",
filledUpdatedProjectForm, project, repository.getBranches()));
}
Project updatedProject = filledUpdatedProjectForm.get();
FilePart filePart = request().body().asMultipartFormData().getFile("logoPath");
if (!isEmptyFilePart(filePart)) {
Attachment.deleteAll(updatedProject.asResource());
new Attachment().store(filePart.getFile(), filePart.getFilename(), updatedProject.asResource());
}
Map<String, String[]> data = request().body().asMultipartFormData().asFormUrlEncoded();
String defaultBranch = HttpUtil.getFirstValueFromQuery(data, "defaultBranch");
if (StringUtils.isNotEmpty(defaultBranch)) {
repository.setDefaultBranch(defaultBranch);
}
if (!project.name.equals(updatedProject.name)) {
if (!repository.renameTo(updatedProject.name)) {
throw new FileOperationException("fail repository rename to " + project.owner + "/" + updatedProject.name);
}
}
updatedProject.update();
saveProjectMenuSetting(updatedProject);
return redirect(routes.ProjectApp.settingForm(ownerId, updatedProject.name));
}
private static void saveProjectMenuSetting(Project project) {
Form<ProjectMenuSetting> filledUpdatedProjectMenuSettingForm = form(ProjectMenuSetting.class).bindFromRequest();
ProjectMenuSetting updatedProjectMenuSetting = filledUpdatedProjectMenuSettingForm.get();
project.refresh();
updatedProjectMenuSetting.project = project;
if (project.menuSetting == null) {
updatedProjectMenuSetting.save();
} else {
updatedProjectMenuSetting.id = project.menuSetting.id;
updatedProjectMenuSetting.update();
}
}
private static boolean validateWhenUpdate(String loginId, Form<Project> updateProjectForm) {
Long id = Long.parseLong(updateProjectForm.field("id").value());
String name = updateProjectForm.field("name").value();
if (!Project.projectNameChangeable(id, loginId, name)) {
flash(Constants.WARNING, "project.name.duplicate");
updateProjectForm.reject("name", "project.name.duplicate");
}
FilePart filePart = request().body().asMultipartFormData().getFile("logoPath");
if (!isEmptyFilePart(filePart)) {
if (!isImageFile(filePart.getFilename())) {
flash(Constants.WARNING, "project.logo.alert");
updateProjectForm.reject("logoPath", "project.logo.alert");
} else if (filePart.getFile().length() > LOGO_FILE_LIMIT_SIZE) {
flash(Constants.WARNING, "project.logo.fileSizeAlert");
updateProjectForm.reject("logoPath", "project.logo.fileSizeAlert");
}
}
ValidationError error = updateProjectForm.error("name");
if (error != null) {
if (PatternValidator.message.equals(error.message())) {
flash(Constants.WARNING, "project.name.alert");
updateProjectForm.errors().remove("name");
updateProjectForm.reject("name", "project.name.alert");
} else if (RestrictedValidator.message.equals(error.message())) {
flash(Constants.WARNING, "project.name.reserved.alert");
updateProjectForm.errors().remove("name");
updateProjectForm.reject("name", "project.name.reserved.alert");
}
}
return updateProjectForm.hasErrors();
}
@IsAllowed(Operation.DELETE)
public static Result deleteForm(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
return ok(delete.render("title.projectDelete", projectForm, project));
}
@Transactional
@IsAllowed(Operation.DELETE)
public static Result deleteProject(String ownerId, String projectName) throws Exception {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
project.delete();
RepositoryService.deleteRepository(project);
if (HttpUtil.isRequestedWithXHR(request())){
response().setHeader("Location", routes.Application.index().toString());
return status(204);
}
return redirect(routes.Application.index());
}
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result members(String loginId, String projectName) {
Project project = Project.findByOwnerAndProjectName(loginId, projectName);
project.cleanEnrolledUsers();
return ok(views.html.project.members.render("title.projectMembers",
ProjectUser.findMemberListByProject(project.id), project,
Role.findProjectRoles()));
}
@IsAllowed(Operation.READ)
public static Result mentionList(String loginId, String projectName, Long number, String resourceType) {
String prefer = HttpUtil.getPreferType(request(), HTML, JSON);
if (prefer == null) {
return status(Http.Status.NOT_ACCEPTABLE);
} else {
response().setHeader("Vary", "Accept");
}
Project project = Project.findByOwnerAndProjectName(loginId, projectName);
List<User> userList = new ArrayList<>();
collectAuthorAndCommenter(project, number, userList, resourceType);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
private static List<Map<String, String>> getIssueList(Project project) {
List<Map<String, String>> mentionListOfIssues = new ArrayList<>();
collectedIssuesToMap(mentionListOfIssues, getMentionIssueList(project));
return mentionListOfIssues;
}
private static List<Map<String, String>> getUserList(Project project, List<User> userList) {
List<Map<String, String>> mentionListOfUser = new ArrayList<>();
collectedUsersToMentionList(mentionListOfUser, userList);
addProjectNameToMentionList(mentionListOfUser, project);
addOrganizationNameToMentionList(mentionListOfUser, project);
return mentionListOfUser;
}
private static void addProjectNameToMentionList(List<Map<String, String>> users, Project project) {
Map<String, String> projectUserMap = new HashMap<>();
if(project != null){
projectUserMap.put("loginid", project.owner+"/" + project.name);
projectUserMap.put("username", project.name );
projectUserMap.put("name", project.name);
projectUserMap.put("image", urlToProjectLogo(project).toString());
users.add(projectUserMap);
}
}
private static void addOrganizationNameToMentionList(List<Map<String, String>> users, Project project) {
Map<String, String> projectUserMap = new HashMap<>();
if(project != null && project.organization != null){
projectUserMap.put("loginid", project.organization.name);
projectUserMap.put("username", project.organization.name);
projectUserMap.put("name", project.organization.name);
projectUserMap.put("image", urlToOrganizationLogo(project.organization).toString());
users.add(projectUserMap);
}
}
private static void collectedIssuesToMap(List<Map<String, String>> mentionList,
List<Issue> issueList) {
for (Issue issue : issueList) {
Map<String, String> projectIssueMap = new HashMap<>();
projectIssueMap.put("name", issue.getNumber().toString() + issue.title);
projectIssueMap.put("issueNo", issue.getNumber().toString());
projectIssueMap.put("title", issue.title);
mentionList.add(projectIssueMap);
}
}
private static List<Issue> getMentionIssueList(Project project) {
return Issue.finder.where()
.eq("project.id", project.isForkedFromOrigin() ? project.originalProject.id : project.id)
.orderBy("createdDate desc")
.setMaxRows(ISSUE_MENTION_SHOW_LIMIT)
.findList();
}
@IsAllowed(Operation.READ)
public static Result mentionListAtCommitDiff(String ownerId, String projectName, String commitId, Long pullRequestId)
throws IOException, UnsupportedOperationException, ServletException, SVNException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PullRequest pullRequest;
Project fromProject = project;
if (pullRequestId != -1) {
pullRequest = PullRequest.findById(pullRequestId);
if (pullRequest != null) {
fromProject = pullRequest.fromProject;
}
}
Commit commit = RepositoryService.getRepository(fromProject).getCommit(commitId);
List<User> userList = new ArrayList<>();
addCommitAuthor(commit, userList);
addCodeCommenters(commitId, fromProject.id, userList);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
@IsAllowed(Operation.READ)
public static Result mentionListAtPullRequest(String ownerId, String projectName, String commitId, Long pullRequestId)
throws IOException, UnsupportedOperationException, ServletException, SVNException {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
PullRequest pullRequest = PullRequest.findById(pullRequestId);
List<User> userList = new ArrayList<>();
addCommentAuthors(pullRequestId, userList);
addProjectMemberList(project, userList);
addGroupMemberList(project, userList);
if(!commitId.isEmpty()) {
addCommitAuthor(RepositoryService.getRepository(pullRequest.fromProject).getCommit(commitId), userList);
}
User contributor = pullRequest.contributor;
if(!userList.contains(contributor)) {
userList.add(contributor);
}
userList.remove(UserApp.currentUser());
userList.add(UserApp.currentUser()); //send me last at list
Map<String, List<Map<String, String>>> result = new HashMap<>();
result.put("result", getUserList(project, userList));
result.put("issues", getIssueList(project));
return ok(toJson(result));
}
private static void addCommentAuthors(Long pullRequestId, List<User> userList) {
List<CommentThread> threads = PullRequest.findById(pullRequestId).commentThreads;
for (CommentThread thread : threads) {
for (ReviewComment comment : thread.reviewComments) {
final User commenter = User.findByLoginId(comment.author.loginId);
if(userList.contains(commenter)) {
userList.remove(commenter);
}
userList.add(commenter);
}
}
Collections.reverse(userList);
}
@IsAllowed(Operation.DELETE)
public static Result transferForm(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Form<Project> projectForm = form(Project.class).fill(project);
return ok(transfer.render("title.projectTransfer", projectForm, project));
}
@Transactional
@IsAllowed(Operation.DELETE)
public static Result transferProject(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
String destination = request().getQueryString("owner");
User destOwner = User.findByLoginId(destination);
Organization destOrg = Organization.findByName(destination);
if (destOwner.isAnonymous() && destOrg == null) {
return badRequest(ErrorViews.BadRequest.render());
}
User projectOwner = User.findByLoginId(project.owner);
Organization projectOrg = Organization.findByName(project.owner);
if(destOwner.equals(projectOwner) || projectOrg.equals(destOrg)) {
flash(Constants.INFO, "project.transfer.has.same.owner");
Form<Project> projectForm = form(Project.class).fill(project);
return ok(transfer.render("title.projectTransfer", projectForm, project));
}
ProjectTransfer pt = null;
// make a request to move to an user
if (!destOwner.isAnonymous()) {
pt = ProjectTransfer.requestNewTransfer(project, UserApp.currentUser(), destOwner.loginId);
}
// make a request to move to an group
if (destOrg != null) {
pt = ProjectTransfer.requestNewTransfer(project, UserApp.currentUser(), destOrg.name);
}
sendTransferRequestMail(pt);
flash(Constants.INFO, "project.transfer.is.requested");
// if the request is sent by XHR, response with 204 204 No Content and Location header.
String url = routes.ProjectApp.project(ownerId, projectName).url();
if (HttpUtil.isRequestedWithXHR(request())) {
response().setHeader("Location", url);
return status(204);
}
return redirect(url);
}
@Transactional
@With(AnonymousCheckAction.class)
public static synchronized Result acceptTransfer(Long id, String confirmKey) throws IOException, ServletException {
ProjectTransfer pt = ProjectTransfer.findValidOne(id);
if (pt == null) {
return notFound(ErrorViews.NotFound.render());
}
if (confirmKey == null || !pt.confirmKey.equals(confirmKey)) {
return badRequest(ErrorViews.BadRequest.render());
}
if (!AccessControl.isAllowed(UserApp.currentUser(), pt.asResource(), Operation.ACCEPT)) {
return forbidden(ErrorViews.Forbidden.render());
}
Project project = pt.project;
// Change the project's name and move the repository.
String newProjectName = Project.newProjectName(pt.destination, project.name);
PlayRepository repository = RepositoryService.getRepository(project);
repository.move(project.owner, project.name, pt.destination, newProjectName);
User newOwnerUser = User.findByLoginId(pt.destination);
Organization newOwnerOrg = Organization.findByName(pt.destination);
// Change the project's information.
project.owner = pt.destination;
project.name = newProjectName;
if (newOwnerOrg != null) {
project.organization = newOwnerOrg;
} else {
project.organization = null;
}
project.update();
// Change roles.
if (!newOwnerUser.isAnonymous()) {
ProjectUser.assignRole(newOwnerUser.id, project.id, RoleType.MANAGER);
}
if (ProjectUser.isManager(pt.sender.id, project.id)) {
ProjectUser.assignRole(pt.sender.id, project.id, RoleType.MEMBER);
}
// Change the tranfer's status to be accepted.
pt.newProjectName = newProjectName;
pt.accepted = true;
pt.update();
// If the opposite request is exists, delete it.
ProjectTransfer.deleteExisting(project, pt.sender, pt.destination);
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
private static void sendTransferRequestMail(ProjectTransfer pt) {
HtmlEmail email = new HtmlEmail();
try {
String acceptUrl = pt.getAcceptUrl();
String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n"
+ Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner, pt.destination) + "\n"
+ Messages.get("transfer.message.link") + "\n\n"
+ acceptUrl + "\n\n"
+ Messages.get("transfer.message.deadline") + "\n\n"
+ Messages.get("transfer.message.thank");
email.setFrom(Config.getEmailFromSmtp(), pt.sender.name);
email.addTo(Config.getEmailFromSmtp(), "Yobi");
User to = User.findByLoginId(pt.destination);
if (!to.isAnonymous()) {
email.addBcc(to.email, to.name);
}
Organization org = Organization.findByName(pt.destination);
if (org != null) {
List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org);
for(OrganizationUser admin : admins) {
email.addBcc(admin.user.email, admin.user.name);
}
}
email.setSubject(String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId));
email.setHtmlMsg(Markdown.render(message));
email.setTextMsg(message);
email.setCharset("utf-8");
email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">");
email.setSentDate(pt.requested);
Mailer.send(email);
String escapedTitle = email.getSubject().replace("\"", "\\\"");
String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
play.Logger.of("mail").info(logEntry);
} catch (Exception e) {
Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
}
}
private static void addCodeCommenters(String commitId, Long projectId, List<User> userList) {
Project project = Project.find.byId(projectId);
if (RepositoryService.VCS_GIT.equals(project.vcs)) {
List<ReviewComment> comments = ReviewComment.find
.fetch("thread")
.where()
.eq("thread.commitId",commitId)
.eq("thread.project", project)
.eq("thread.pullRequest", null).findList();
for (ReviewComment comment : comments) {
User commentAuthor = User.findByLoginId(comment.author.loginId);
if (userList.contains(commentAuthor)) {
userList.remove(commentAuthor);
}
userList.add(commentAuthor);
}
} else {
List<CommitComment> comments = CommitComment.find.where().eq("commitId",
commitId).eq("project.id", projectId).findList();
for (CommitComment codeComment : comments) {
User commentAuthor = User.findByLoginId(codeComment.authorLoginId);
if (userList.contains(commentAuthor)) {
userList.remove(commentAuthor);
}
userList.add(commentAuthor);
}
}
Collections.reverse(userList);
}
private static void addCommitAuthor(Commit commit, List<User> userList) {
if (!commit.getAuthor().isAnonymous() && !userList.contains(commit.getAuthor())) {
userList.add(commit.getAuthor());
}
//fallback: additional search by email id
if (commit.getAuthorEmail() != null) {
User authorByEmail = User.findByLoginId(commit.getAuthorEmail().substring(0, commit.getAuthorEmail().lastIndexOf("@")));
if (!authorByEmail.isAnonymous() && !userList.contains(authorByEmail)) {
userList.add(authorByEmail);
}
}
}
private static void collectAuthorAndCommenter(Project project, Long number, List<User> userList, String resourceType) {
AbstractPosting posting;
switch (ResourceType.getValue(resourceType)) {
case ISSUE_POST:
posting = AbstractPosting.findByNumber(Issue.finder, project, number);
break;
case BOARD_POST:
posting = AbstractPosting.findByNumber(Posting.finder, project, number);
break;
default:
return;
}
if (posting != null) {
for (Comment comment: posting.getComments()) {
User commentUser = User.findByLoginId(comment.authorLoginId);
if (userList.contains(commentUser)) {
userList.remove(commentUser);
}
userList.add(commentUser);
}
Collections.reverse(userList); // recent commenter first!
User postAuthor = User.findByLoginId(posting.authorLoginId);
if (!userList.contains(postAuthor)) {
userList.add(postAuthor);
}
}
}
private static void collectedUsersToMentionList(List<Map<String, String>> users, List<User> userList) {
for (User user: userList) {
Map<String, String> projectUserMap = new HashMap<>();
if (user != null && !user.loginId.equals(Constants.ADMIN_LOGIN_ID)) {
projectUserMap.put("loginid", user.loginId);
projectUserMap.put("username", user.name);
projectUserMap.put("name", user.name + user.loginId);
projectUserMap.put("image", user.avatarUrl());
users.add(projectUserMap);
}
}
}
private static void addProjectMemberList(Project project, List<User> userList) {
for (ProjectUser projectUser: project.projectUser) {
if (!userList.contains(projectUser.user)) {
userList.add(projectUser.user);
}
}
}
private static void addGroupMemberList(Project project, List<User> userList) {
if (!project.hasGroup()) {
return;
}
for (OrganizationUser organizationUser : project.organization.users) {
if (!userList.contains(organizationUser.user)) {
userList.add(organizationUser.user);
}
}
}
@Transactional
@With(DefaultProjectCheckAction.class)
@IsAllowed(Operation.UPDATE)
public static Result newMember(String ownerId, String projectName) {
Form<User> addMemberForm = form(User.class).bindFromRequest();
User newMember = User.findByLoginId(addMemberForm.field("loginId").value());
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (isErrorOnAddMemberForm(newMember, project, addMemberForm)) {
if(HttpUtil.isJSONPreferred(request())){
return badRequest(addMemberForm.errorsAsJson());
}
List<ValidationError> errors = addMemberForm.errors().get("loginId");
flash(Constants.WARNING, errors.get(errors.size() - 1).message());
return redirect(routes.ProjectApp.members(ownerId, projectName));
}
ProjectUser.assignRole(newMember.id, project.id, RoleType.MEMBER);
project.cleanEnrolledUsers();
NotificationEvent.afterMemberRequest(project, newMember, RequestState.ACCEPT);
if(HttpUtil.isJSONPreferred(request())){
return ok("{}");
}
return redirect(routes.ProjectApp.members(ownerId, projectName));
}
private static boolean isErrorOnAddMemberForm(User user, Project project, Form<User> addMemberForm) {
if (addMemberForm.hasErrors()) {
addMemberForm.reject("loginId", "project.members.addMember");
} else if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) {
addMemberForm.reject("loginId", "project.member.isManager");
} else if (user.isAnonymous()) {
addMemberForm.reject("loginId", "project.member.notExist");
} else if (ProjectUser.isMember(user.id, project.id)) {
addMemberForm.reject("loginId", "project.member.alreadyMember");
}
return addMemberForm.hasErrors();
}
/**
* Returns OK(200) with {@code location} which is represented as JSON .
*
* Since returning redirect response(3xx) to Ajax request causes unexpected result, this function returns OK(200) containing redirect location.
* The client will check {@code location} and have a page move to the location.
*
* @param location
* @return
*/
private static Result okWithLocation(String location) {
ObjectNode result = Json.newObject();
result.put("location", location);
return ok(result);
}
/**
* @param ownerId the user login id
* @param projectName the project name
* @param userId
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result deleteMember(String ownerId, String projectName, Long userId) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
User deleteMember = User.find.byId(userId);
if (!UserApp.currentUser().id.equals(userId)
&& !AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
if (project.isOwner(deleteMember)) {
return forbidden(ErrorViews.Forbidden.render("project.member.ownerCannotLeave", project));
}
ProjectUser.delete(userId, project.id);
if (UserApp.currentUser().id.equals(userId)) {
if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
return okWithLocation(routes.ProjectApp.project(project.owner, project.name).url());
} else {
return okWithLocation(routes.Application.index().url());
}
} else {
return okWithLocation(routes.ProjectApp.members(ownerId, projectName).url());
}
}
/**
* @param ownerId the user login id
* @param projectName the project name
* @param userId the user id
* @return
*/
@Transactional
@IsAllowed(Operation.UPDATE)
public static Result editMember(String ownerId, String projectName, Long userId) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
User editMember = User.find.byId(userId);
if (project.isOwner(editMember)) {
return badRequest(ErrorViews.Forbidden.render("project.member.ownerMustBeAManager", project));
}
ProjectUser.assignRole(userId, project.id, form(Role.class).bindFromRequest().get().id);
return status(Http.Status.NO_CONTENT);
}
/**
* @param query the query
* @param pageNum the page num
* @return
*/
public static Result projects(String query, int pageNum) {
String prefer = HttpUtil.getPreferType(request(), HTML, JSON);
if (prefer == null) {
return status(Http.Status.NOT_ACCEPTABLE);
}
response().setHeader("Vary", "Accept");
if (prefer.equals(JSON)) {
return getProjectsToJSON(query);
} else {
return getPagingProjects(query, pageNum);
}
}
private static Result getPagingProjects(String query, int pageNum) {
ExpressionList<Project> el = createProjectSearchExpressionList(query);
Set<Long> labelIds = LabelSearchUtil.getLabelIds(request());
if (CollectionUtils.isNotEmpty(labelIds)) {
el.add(LabelSearchUtil.createLabelSearchExpression(el.query(), labelIds));
}
el.orderBy("createdDate desc");
Page<Project> projects = el.findPagingList(PROJECT_COUNT_PER_PAGE).getPage(pageNum - 1);
return ok(views.html.project.list.render("title.projectList", projects, query));
}
private static Result getProjectsToJSON(String query) {
ExpressionList<Project> el = createProjectSearchExpressionList(query);
int total = el.findRowCount();
if (total > MAX_FETCH_PROJECTS) {
el.setMaxRows(MAX_FETCH_PROJECTS);
response().setHeader("Content-Range", "items " + MAX_FETCH_PROJECTS + "/" + total);
}
List<String> projectNames = new ArrayList<>();
for (Project project: el.findList()) {
projectNames.add(project.owner + "/" + project.name);
}
return ok(toJson(projectNames));
}
private static ExpressionList<Project> createProjectSearchExpressionList(String query) {
ExpressionList<Project> el = Project.find.where();
if (StringUtils.isNotBlank(query)) {
Junction<Project> junction = el.disjunction();
junction.icontains("owner", query)
.icontains("name", query)
.icontains("overview", query);
List<Object> ids = Project.find.where().icontains("labels.name", query).findIds();
if (!ids.isEmpty()) {
junction.idIn(ids);
}
junction.endJunction();
}
if (!UserApp.currentUser().isSiteManager()) {
el.eq("projectScope", ProjectScope.PUBLIC);
}
return el;
}
/**
* @param ownerId the owner login id
* @param projectName the project name
* @return
*/
@IsAllowed(Operation.READ)
public static Result labels(String ownerId, String projectName) {
if (!request().accepts("application/json")) {
return status(Http.Status.NOT_ACCEPTABLE);
}
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
Map<Long, Map<String, String>> labels = new HashMap<>();
for (Label label: project.labels) {
labels.put(label.id, convertToMap(label));
}
return ok(toJson(labels));
}
/**
* convert from some part of {@link models.Label} to {@link java.util.Map}
* @param label {@link models.Label} object
* @return label's map data
*/
private static Map<String, String> convertToMap(Label label) {
Map<String, String> tagMap = new HashMap<>();
tagMap.put("category", label.category);
tagMap.put("name", label.name);
return tagMap;
}
/**
* @param ownerId the owner name
* @param projectName the project name
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result attachLabel(String ownerId, String projectName) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
// Get category and name from the request. Return 400 Bad Request if name is not given.
Map<String, String[]> data = request().body().asFormUrlEncoded();
String category = HttpUtil.getFirstValueFromQuery(data, "category");
String name = HttpUtil.getFirstValueFromQuery(data, "name");
if (StringUtils.isEmpty(name)) {
// A label must have its name.
return badRequest(ErrorViews.BadRequest.render("Label name is missing.", project));
}
Label label = Label.find
.where().eq("category", category).eq("name", name).findUnique();
boolean isCreated = false;
if (label == null) {
// Create new label if there is no label which has the given name.
label = new Label(category, name);
label.projects.add(project);
label.save();
isCreated = true;
}
Boolean isAttached = project.attachLabel(label);
if (!isCreated && !isAttached) {
// Something is wrong. This case is not possible.
play.Logger.warn(
"A label '" + label + "' is created but failed to attach to project '" + project + "'.");
}
if (isAttached) {
// Return the attached label. The return type is Map<Long, Map<String, String>>
// even if there is only one label, to unify the return type with
// ProjectApp.labels().
Map<Long, Map<String, String>> labels = new HashMap<>();
labels.put(label.id, convertToMap(label));
if (isCreated) {
return created(toJson(labels));
} else {
return ok(toJson(labels));
}
} else {
// Return 204 No Content if the label is already attached.
return status(Http.Status.NO_CONTENT);
}
}
/**
* @param ownerId the owner name
* @param projectName the project name
* @param id the id
* @return the result
*/
@Transactional
@With(DefaultProjectCheckAction.class)
public static Result detachLabel(String ownerId, String projectName, Long id) {
Project project = Project.findByOwnerAndProjectName(ownerId, projectName);
if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", project));
}
// _method must be 'delete'
Map<String, String[]> data = request().body().asFormUrlEncoded();
if (!HttpUtil.getFirstValueFromQuery(data, "_method").toLowerCase()
.equals("delete")) {
return badRequest(ErrorViews.BadRequest.render("_method must be 'delete'.", project));
}
Label tag = Label.find.byId(id);
if (tag == null) {
return notFound(ErrorViews.NotFound.render("error.notfound"));
}
project.detachLabel(tag);
return status(Http.Status.NO_CONTENT);
}
@Transactional
@With(AnonymousCheckAction.class)
@IsAllowed(Operation.DELETE)
public static Result deletePushedBranch(String ownerId, String projectName, Long id) {
PushedBranch pushedBranch = PushedBranch.find.byId(id);
if (pushedBranch != null) {
pushedBranch.delete();
}
return ok();
}
}
| Transfer: Added null check
| app/controllers/ProjectApp.java | Transfer: Added null check |
|
Java | apache-2.0 | 91ec19189766533a37b809f90be81268f15822dc | 0 | semonte/intellij-community,blademainer/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,nicolargo/intellij-community,holmes/intellij-community,fitermay/intellij-community,amith01994/intellij-community,caot/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,slisson/intellij-community,ryano144/intellij-community,ibinti/intellij-community,joewalnes/idea-community,adedayo/intellij-community,ibinti/intellij-community,clumsy/intellij-community,samthor/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,da1z/intellij-community,diorcety/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,FHannes/intellij-community,asedunov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,signed/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ernestp/consulo,caot/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,dslomov/intellij-community,dslomov/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,ryano144/intellij-community,vladmm/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,izonder/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,vladmm/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,signed/intellij-community,vladmm/intellij-community,samthor/intellij-community,retomerz/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,supersven/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,clumsy/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,samthor/intellij-community,caot/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,signed/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,asedunov/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,fnouama/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,joewalnes/idea-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,consulo/consulo,gnuhub/intellij-community,izonder/intellij-community,joewalnes/idea-community,da1z/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,fnouama/intellij-community,izonder/intellij-community,vladmm/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,adedayo/intellij-community,kool79/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,caot/intellij-community,hurricup/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,xfournet/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,vladmm/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,izonder/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,robovm/robovm-studio,semonte/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,robovm/robovm-studio,clumsy/intellij-community,jagguli/intellij-community,semonte/intellij-community,ibinti/intellij-community,supersven/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,holmes/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ernestp/consulo,tmpgit/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,holmes/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ernestp/consulo,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,ahb0327/intellij-community,supersven/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,allotria/intellij-community,petteyg/intellij-community,apixandru/intellij-community,hurricup/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,slisson/intellij-community,akosyakov/intellij-community,semonte/intellij-community,Distrotech/intellij-community,kool79/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ryano144/intellij-community,consulo/consulo,petteyg/intellij-community,allotria/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,asedunov/intellij-community,clumsy/intellij-community,izonder/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,supersven/intellij-community,signed/intellij-community,fnouama/intellij-community,da1z/intellij-community,caot/intellij-community,clumsy/intellij-community,diorcety/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,kdwink/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,signed/intellij-community,hurricup/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,holmes/intellij-community,orekyuu/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,jagguli/intellij-community,retomerz/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,holmes/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,consulo/consulo,da1z/intellij-community,kool79/intellij-community,kdwink/intellij-community,fnouama/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,supersven/intellij-community,kdwink/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ernestp/consulo,Distrotech/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,FHannes/intellij-community,izonder/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,FHannes/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,retomerz/intellij-community,signed/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,signed/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ryano144/intellij-community,asedunov/intellij-community,supersven/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,da1z/intellij-community,apixandru/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,slisson/intellij-community,youdonghai/intellij-community,caot/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,izonder/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,xfournet/intellij-community,asedunov/intellij-community,samthor/intellij-community,ibinti/intellij-community,jagguli/intellij-community,signed/intellij-community,fitermay/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,holmes/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,asedunov/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,supersven/intellij-community,slisson/intellij-community,caot/intellij-community,da1z/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,consulo/consulo,michaelgallacher/intellij-community,consulo/consulo,ol-loginov/intellij-community,semonte/intellij-community,da1z/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,caot/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,kdwink/intellij-community,izonder/intellij-community,holmes/intellij-community,holmes/intellij-community,fnouama/intellij-community,amith01994/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,jagguli/intellij-community,semonte/intellij-community,Distrotech/intellij-community,signed/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,slisson/intellij-community,robovm/robovm-studio,samthor/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,supersven/intellij-community,dslomov/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,supersven/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,caot/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,blademainer/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.spellchecker.quickfixes;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.refactoring.rename.NameSuggestionProvider;
import com.intellij.spellchecker.SpellCheckerManager;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class DictionarySuggestionProvider implements NameSuggestionProvider {
private boolean active;
public void setActive(boolean active) {
this.active = active;
}
public SuggestedNameInfo getSuggestedNames(PsiElement element, PsiElement nameSuggestionContext, List<String> result) {
assert result != null;
if (!active || nameSuggestionContext==null) {
return null;
}
String text = nameSuggestionContext.getText();
if (nameSuggestionContext instanceof PsiNamedElement) {
//noinspection ConstantConditions
text = ((PsiNamedElement)element).getName();
}
if (text == null) {
return null;
}
SpellCheckerManager manager = SpellCheckerManager.getInstance(element.getProject());
Set<String> set = new TreeSet<String>();
set.addAll(manager.getSuggestions(text));
result.addAll(set);
return null;
}
public Collection<LookupElement> completeName(PsiElement element, PsiElement nameSuggestionContext, String prefix) {
return null;
}
}
| plugins/spellchecker/src/com/intellij/spellchecker/quickfixes/DictionarySuggestionProvider.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.spellchecker.quickfixes;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.refactoring.rename.NameSuggestionProvider;
import com.intellij.spellchecker.SpellCheckerManager;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class DictionarySuggestionProvider implements NameSuggestionProvider {
private boolean active;
public void setActive(boolean active) {
this.active = active;
}
public SuggestedNameInfo getSuggestedNames(PsiElement element, PsiElement nameSuggestionContext, List<String> result) {
assert result != null;
if (!active) {
return null;
}
String text = nameSuggestionContext.getText();
if (nameSuggestionContext instanceof PsiNamedElement) {
//noinspection ConstantConditions
text = ((PsiNamedElement)element).getName();
}
if (text == null) {
return null;
}
SpellCheckerManager manager = SpellCheckerManager.getInstance(element.getProject());
Set<String> set = new TreeSet<String>();
set.addAll(manager.getSuggestions(text));
result.addAll(set);
return null;
}
public Collection<LookupElement> completeName(PsiElement element, PsiElement nameSuggestionContext, String prefix) {
return null;
}
}
| Spellchecker: fix NPE in DictionarySuggestionProvider (EA id 17899)
| plugins/spellchecker/src/com/intellij/spellchecker/quickfixes/DictionarySuggestionProvider.java | Spellchecker: fix NPE in DictionarySuggestionProvider (EA id 17899) |
|
Java | apache-2.0 | 379912311cf89d96a6a9b4c47bfc89f15437727b | 0 | hguehl/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,MaxSmile/guacamole-client,lato333/guacamole-client,jmuehlner/incubator-guacamole-client,flangelo/guacamole-client,hguehl/incubator-guacamole-client,hguehl/incubator-guacamole-client,TheAxnJaxn/guacamole-client,necouchman/incubator-guacamole-client,noelbk/guacamole-client,MaxSmile/guacamole-client,lato333/guacamole-client,TribeMedia/guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,qiangyee/guacamole-client,softpymesJeffer/incubator-guacamole-client,noelbk/guacamole-client,necouchman/incubator-guacamole-client,lato333/guacamole-client,noelbk/guacamole-client,mike-jumper/incubator-guacamole-client,MaxSmile/guacamole-client,nkoterba/guacamole-common-js,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,Akheon23/guacamole-client,glyptodon/guacamole-client,softpymesJeffer/incubator-guacamole-client,DaanWillemsen/guacamole-client,TribeMedia/guacamole-client,mike-jumper/incubator-guacamole-client,AIexandr/guacamole-client,DaanWillemsen/guacamole-client,hguehl/incubator-guacamole-client,AIexandr/guacamole-client,TheAxnJaxn/guacamole-client,DaanWillemsen/guacamole-client,mike-jumper/incubator-guacamole-client,Akheon23/guacamole-client,flangelo/guacamole-client,TribeMedia/guacamole-client,qiangyee/guacamole-client,flangelo/guacamole-client,Akheon23/guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,qiangyee/guacamole-client,esmailpour-hosein/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,AIexandr/guacamole-client,lato333/guacamole-client,TheAxnJaxn/guacamole-client,jmuehlner/incubator-guacamole-client |
package net.sourceforge.guacamole.net.auth.noauth;
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-auth-noauth.
*
* The Initial Developer of the Original Code is
* Laurent Meunier
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* XML parser for the configuration file used by the NoAuth auth provider.
*
* @author Laurent Meunier
*/
public class NoAuthConfigContentHandler extends DefaultHandler {
/**
* Map of all configurations, indexed by name.
*/
private Map<String, GuacamoleConfiguration> configs = new HashMap<String, GuacamoleConfiguration>();
/**
* The name of the current configuration, if any.
*/
private String current = null;
/**
* The current configuration being parsed, if any.
*/
private GuacamoleConfiguration currentConfig = null;
/**
* Returns the a map of all available configurations as parsed from the
* XML file. This map is unmodifiable.
*
* @return A map of all available configurations.
*/
public Map<String, GuacamoleConfiguration> getConfigs() {
return Collections.unmodifiableMap(configs);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// If end of config element, add to map
if (localName.equals("config")) {
// Add to map
configs.put(current, currentConfig);
// Reset state for next configuration
currentConfig = null;
current = null;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// Begin configuration parsing if config element
if (localName.equals("config")) {
// Ensure this config is on the top level
if (current != null)
throw new SAXException("Configurations cannot be nested.");
// Read name
String name = attributes.getValue("name");
if (name == null)
throw new SAXException("Each configuration must have a name.");
// Read protocol
String protocol = attributes.getValue("protocol");
if (protocol == null)
throw new SAXException("Each configuration must have a protocol.");
// Create config stub
current = name;
currentConfig = new GuacamoleConfiguration();
currentConfig.setProtocol(protocol);
}
// Add parameters to existing configuration
else if (localName.equals("param")) {
// Ensure a corresponding config exists
if (currentConfig == null)
throw new SAXException("Parameter without corresponding configuration.");
currentConfig.setParameter(attributes.getValue("name"), attributes.getValue("value"));
}
// Fail on unexpected elements
else
throw new SAXException("Unexpected element: " + localName);
}
}
| extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthConfigContentHandler.java |
package net.sourceforge.guacamole.net.auth.noauth;
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-auth-noauth.
*
* The Initial Developer of the Original Code is
* Laurent Meunier
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author Laurent Meunier
*/
public class NoAuthConfigContentHandler extends DefaultHandler {
private Map<String, GuacamoleConfiguration> configs = new HashMap<String, GuacamoleConfiguration>();
private String current = null;
private GuacamoleConfiguration currentConfig = null;
public Map<String, GuacamoleConfiguration> getConfigs() {
return Collections.unmodifiableMap(configs);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equals("config")) {
configs.put(current, currentConfig);
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals("config")) {
current = attributes.getValue("name");
currentConfig = new GuacamoleConfiguration();
currentConfig.setProtocol(attributes.getValue("protocol"));
}
else if (localName.equals("param")) {
currentConfig.setParameter(attributes.getValue("name"), attributes.getValue("value"));
}
}
}
| Clean up parser. Add sanity checks against XML. Add documentation. | extensions/guacamole-auth-noauth/src/main/java/net/sourceforge/guacamole/net/auth/noauth/NoAuthConfigContentHandler.java | Clean up parser. Add sanity checks against XML. Add documentation. |
|
Java | apache-2.0 | 92898503e164b6c65755d656d7810914b1db2378 | 0 | ringdna/jitsi,cobratbq/jitsi,laborautonomo/jitsi,bhatvv/jitsi,procandi/jitsi,bebo/jitsi,mckayclarey/jitsi,gpolitis/jitsi,tuijldert/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,laborautonomo/jitsi,pplatek/jitsi,jitsi/jitsi,pplatek/jitsi,ibauersachs/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,gpolitis/jitsi,ibauersachs/jitsi,damencho/jitsi,marclaporte/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,damencho/jitsi,dkcreinoso/jitsi,459below/jitsi,mckayclarey/jitsi,bhatvv/jitsi,procandi/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,jibaro/jitsi,level7systems/jitsi,bhatvv/jitsi,jibaro/jitsi,Metaswitch/jitsi,bhatvv/jitsi,ringdna/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,ringdna/jitsi,marclaporte/jitsi,tuijldert/jitsi,iant-gmbh/jitsi,martin7890/jitsi,Metaswitch/jitsi,tuijldert/jitsi,procandi/jitsi,procandi/jitsi,459below/jitsi,level7systems/jitsi,laborautonomo/jitsi,bebo/jitsi,damencho/jitsi,dkcreinoso/jitsi,level7systems/jitsi,ibauersachs/jitsi,jibaro/jitsi,cobratbq/jitsi,martin7890/jitsi,ringdna/jitsi,iant-gmbh/jitsi,pplatek/jitsi,gpolitis/jitsi,martin7890/jitsi,bebo/jitsi,marclaporte/jitsi,459below/jitsi,martin7890/jitsi,459below/jitsi,level7systems/jitsi,gpolitis/jitsi,iant-gmbh/jitsi,tuijldert/jitsi,459below/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,bebo/jitsi,Metaswitch/jitsi,jitsi/jitsi,jitsi/jitsi,level7systems/jitsi,dkcreinoso/jitsi,damencho/jitsi,procandi/jitsi,mckayclarey/jitsi,jitsi/jitsi,dkcreinoso/jitsi,damencho/jitsi,bebo/jitsi,martin7890/jitsi,ringdna/jitsi,jitsi/jitsi,bhatvv/jitsi,ibauersachs/jitsi,laborautonomo/jitsi,ibauersachs/jitsi,mckayclarey/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,jibaro/jitsi,pplatek/jitsi,marclaporte/jitsi,jibaro/jitsi,tuijldert/jitsi | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist.contactsource;
import java.util.*;
import java.util.regex.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.contactlist.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import javax.swing.*;
/**
* The <tt>MetaContactListSource</tt> is an abstraction of the
* <tt>MetaContactListService</tt>, which makes the correspondence between a
* <tt>MetaContact</tt> and an <tt>UIContact</tt> and between a
* <tt>MetaContactGroup</tt> and an <tt>UIGroup</tt>. It is also responsible
* for filtering of the <tt>MetaContactListService</tt> through a given pattern.
*
* @author Yana Stamcheva
*/
public class MetaContactListSource
implements ContactPresenceStatusListener,
MetaContactListListener
{
/**
* The data key of the MetaContactDescriptor object used to store a
* reference to this object in its corresponding MetaContact.
*/
public static final String UI_CONTACT_DATA_KEY
= MetaUIContact.class.getName() + ".uiContactDescriptor";
/**
* The data key of the MetaGroupDescriptor object used to store a
* reference to this object in its corresponding MetaContactGroup.
*/
public static final String UI_GROUP_DATA_KEY
= MetaUIGroup.class.getName() + ".uiGroupDescriptor";
/**
* The initial result count below which we insert all filter results
* directly to the contact list without firing events.
*/
private final int INITIAL_CONTACT_COUNT = 30;
/**
* The logger.
*/
private static final Logger logger
= Logger.getLogger(MetaContactListSource.class);
/**
* Returns the <tt>UIContact</tt> corresponding to the given
* <tt>MetaContact</tt>.
* @param metaContact the <tt>MetaContact</tt>, which corresponding UI
* contact we're looking for
* @return the <tt>UIContact</tt> corresponding to the given
* <tt>MetaContact</tt>
*/
public static UIContact getUIContact(MetaContact metaContact)
{
return (UIContact) metaContact.getData(UI_CONTACT_DATA_KEY);
}
/**
* Returns the <tt>UIGroup</tt> corresponding to the given
* <tt>MetaContactGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt>, which UI group we're
* looking for
* @return the <tt>UIGroup</tt> corresponding to the given
* <tt>MetaContactGroup</tt>
*/
public static UIGroup getUIGroup(MetaContactGroup metaGroup)
{
return (UIGroup) metaGroup.getData(UI_GROUP_DATA_KEY);
}
/**
* Creates a <tt>UIContact</tt> for the given <tt>metaContact</tt>.
* @param metaContact the <tt>MetaContact</tt> for which we would like to
* create an <tt>UIContact</tt>
* @return an <tt>UIContact</tt> for the given <tt>metaContact</tt>
*/
public static UIContact createUIContact(final MetaContact metaContact)
{
final MetaUIContact descriptor
= new MetaUIContact(metaContact);
// fixes an issue with moving meta contacts where removeContact
// will set data to null in swing thread and it will be after we have
// set the data here, so we also move this set to the swing thread
// to order the calls of setData.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
metaContact.setData(UI_CONTACT_DATA_KEY, descriptor);
}
});
return descriptor;
}
/**
* Removes the <tt>UIContact</tt> from the given <tt>metaContact</tt>.
* @param metaContact the <tt>MetaContact</tt>, which corresponding UI
* contact we would like to remove
*/
public static void removeUIContact(MetaContact metaContact)
{
metaContact.setData(UI_CONTACT_DATA_KEY, null);
}
/**
* Creates a <tt>UIGroupDescriptor</tt> for the given <tt>metaGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt> for which we would like to
* create an <tt>UIContact</tt>
* @return a <tt>UIGroup</tt> for the given <tt>metaGroup</tt>
*/
public static UIGroup createUIGroup(MetaContactGroup metaGroup)
{
MetaUIGroup descriptor = new MetaUIGroup(metaGroup);
metaGroup.setData(UI_GROUP_DATA_KEY, descriptor);
return descriptor;
}
/**
* Removes the descriptor from the given <tt>metaGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt>, which descriptor we
* would like to remove
*/
public static void removeUIGroup(
MetaContactGroup metaGroup)
{
metaGroup.setData(UI_GROUP_DATA_KEY, null);
}
/**
* Indicates if the given <tt>MetaContactGroup</tt> is the root group.
* @param group the <tt>MetaContactGroup</tt> to check
* @return <tt>true</tt> if the given <tt>group</tt> is the root group,
* <tt>false</tt> - otherwise
*/
public static boolean isRootGroup(MetaContactGroup group)
{
return group.equals(GuiActivator.getContactListService().getRoot());
}
/**
* Filters the <tt>MetaContactListService</tt> to match the given
* <tt>filterPattern</tt> and stores the result in the given
* <tt>treeModel</tt>.
* @param filterPattern the pattern to filter through
* @return the created <tt>MetaContactQuery</tt> corresponding to the
* query this method does
*/
public MetaContactQuery queryMetaContactSource(final Pattern filterPattern)
{
final MetaContactQuery query = new MetaContactQuery();
new Thread()
{
public void run()
{
int resultCount = 0;
queryMetaContactSource( filterPattern,
GuiActivator.getContactListService().getRoot(),
query,
resultCount);
if (!query.isCanceled())
query.fireQueryEvent(
MetaContactQueryStatusEvent.QUERY_COMPLETED);
else
query.fireQueryEvent(
MetaContactQueryStatusEvent.QUERY_CANCELED);
}
}.start();
return query;
}
/**
* Filters the children in the given <tt>MetaContactGroup</tt> to match the
* given <tt>filterPattern</tt> and stores the result in the given
* <tt>treeModel</tt>.
* @param filterPattern the pattern to filter through
* @param parentGroup the <tt>MetaContactGroup</tt> to filter
* @param query the object that tracks the query
* @param resultCount the initial result count we would insert directly to
* the contact list without firing events
*/
public void queryMetaContactSource(Pattern filterPattern,
MetaContactGroup parentGroup,
MetaContactQuery query,
int resultCount)
{
Iterator<MetaContact> childContacts = parentGroup.getChildContacts();
while (childContacts.hasNext() && !query.isCanceled())
{
MetaContact metaContact = childContacts.next();
if (isMatching(filterPattern, metaContact))
{
synchronized (metaContact)
{
resultCount++;
if (resultCount <= INITIAL_CONTACT_COUNT)
{
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
UIContact uiContact = getUIContact(metaContact);
if (uiContact != null)
continue;
uiContact = createUIContact(metaContact);
GuiActivator.getContactList().addContact(
uiContact,
uiGroup,
true,
true);
query.setInitialResultCount(resultCount);
}
else
query.fireQueryEvent(metaContact);
}
}
}
// If in the meantime the query is canceled we return here.
if(query.isCanceled())
return;
Iterator<MetaContactGroup> subgroups = parentGroup.getSubgroups();
while (subgroups.hasNext() && !query.isCanceled())
{
MetaContactGroup subgroup = subgroups.next();
queryMetaContactSource(filterPattern, subgroup, query, resultCount);
}
}
/**
* Checks if the given <tt>metaContact</tt> is matching the given
* <tt>filterPattern</tt>.
* A <tt>MetaContact</tt> would be matching the filter if one of the
* following is true:<br>
* - its display name contains the filter string
* - at least one of its child protocol contacts has a display name or an
* address that contains the filter string.
* @param filterPattern the filter pattern to check for matches
* @param metaContact the <tt>MetaContact</tt> to check
* @return <tt>true</tt> to indicate that the given <tt>metaContact</tt> is
* matching the current filter, otherwise returns <tt>false</tt>
*/
private boolean isMatching(Pattern filterPattern, MetaContact metaContact)
{
Matcher matcher = filterPattern.matcher(metaContact.getDisplayName());
if(matcher.find())
return true;
Iterator<Contact> contacts = metaContact.getContacts();
while (contacts.hasNext())
{
Contact contact = contacts.next();
matcher = filterPattern.matcher(contact.getDisplayName());
if (matcher.find())
return true;
matcher = filterPattern.matcher(contact.getAddress());
if (matcher.find())
return true;
}
return false;
}
/**
* Checks if the given <tt>metaGroup</tt> is matching the current filter. A
* group is matching the current filter only if it contains at least one
* child <tt>MetaContact</tt>, which is matching the current filter.
* @param filterPattern the filter pattern to check for matches
* @param metaGroup the <tt>MetaContactGroup</tt> to check
* @return <tt>true</tt> to indicate that the given <tt>metaGroup</tt> is
* matching the current filter, otherwise returns <tt>false</tt>
*/
public boolean isMatching(Pattern filterPattern, MetaContactGroup metaGroup)
{
Iterator<MetaContact> contacts = metaGroup.getChildContacts();
while (contacts.hasNext())
{
MetaContact metaContact = contacts.next();
if (isMatching(filterPattern, metaContact))
return true;
}
return false;
}
public void contactPresenceStatusChanged(
ContactPresenceStatusChangeEvent evt)
{
if (evt.getOldStatus() == evt.getNewStatus())
return;
final Contact sourceContact = evt.getSourceContact();
final MetaContact metaContact
= GuiActivator.getContactListService().findMetaContactByContact(
sourceContact);
if (metaContact == null)
return;
synchronized (metaContact)
{
UIContact uiContact = getUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (uiContact == null)
{
uiContact = createUIContact(metaContact);
if (currentFilter != null && currentFilter.isMatching(uiContact))
{
MetaContactGroup parentGroup
= metaContact.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
if (logger.isDebugEnabled())
logger.debug(
"Add matching contact due to status change: "
+ uiContact.getDisplayName());
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
removeUIContact(metaContact);
}
else
{
if (currentFilter != null
&& !currentFilter.isMatching(uiContact))
{
if (logger.isDebugEnabled())
logger.debug(
"Remove unmatching contact due to status change: "
+ uiContact.getDisplayName());
GuiActivator.getContactList().removeContact(uiContact);
}
else
GuiActivator.getContactList()
.nodeChanged(uiContact.getContactNode());
}
}
}
/**
* Reorders contact list nodes, when <tt>MetaContact</tt>-s in a
* <tt>MetaContactGroup</tt> has been reordered.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void childContactsReordered(MetaContactGroupEvent evt)
{
MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup;
ContactListTreeModel treeModel
= GuiActivator.getContactList().getTreeModel();
if (isRootGroup(metaGroup))
uiGroup = treeModel.getRoot().getGroupDescriptor();
else
uiGroup = MetaContactListSource.getUIGroup(metaGroup);
if (uiGroup != null)
{
GroupNode groupNode = uiGroup.getGroupNode();
if (groupNode != null)
groupNode.sort(treeModel);
}
}
/**
* Adds a node in the contact list, when a <tt>MetaContact</tt> has been
* added in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactAdded(final MetaContactEvent evt)
{
final MetaContact metaContact = evt.getSourceMetaContact();
final MetaContactGroup parentGroup = evt.getParentGroup();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
// If there's already an UIContact for this meta contact, we have
// nothing to do here.
if (uiContact != null)
return;
uiContact = MetaContactListSource.createUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
{
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(metaContact);
}
}
/**
* Adds a group node in the contact list, when a <tt>MetaContactGroup</tt>
* has been added in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupAdded(MetaContactGroupEvent evt)
{
final MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup = MetaContactListSource.getUIGroup(metaGroup);
// If there's already an UIGroup for this meta contact, we have
// nothing to do here.
if (uiGroup != null)
return;
uiGroup = MetaContactListSource.createUIGroup(metaGroup);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiGroup))
GuiActivator.getContactList().addGroup(uiGroup, true);
else
MetaContactListSource.removeUIGroup(metaGroup);
}
/**
* Notifies the tree model, when a <tt>MetaContactGroup</tt> has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupModified(MetaContactGroupEvent evt)
{
final MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup
= MetaContactListSource.getUIGroup(metaGroup);
if (uiGroup != null)
{
GroupNode groupNode = uiGroup.getGroupNode();
if (groupNode != null)
GuiActivator.getContactList().getTreeModel()
.nodeChanged(groupNode);
}
}
/**
* Removes the corresponding group node in the contact list, when a
* <tt>MetaContactGroup</tt> has been removed from the
* <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupRemoved(final MetaContactGroupEvent evt)
{
UIGroup uiGroup
= MetaContactListSource.getUIGroup(
evt.getSourceMetaContactGroup());
if (uiGroup != null)
GuiActivator.getContactList().removeGroup(uiGroup);
}
/**
* Notifies the tree model, when a <tt>MetaContact</tt> has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactModified(final MetaContactModifiedEvent evt)
{
UIContact uiContact
= MetaContactListSource.getUIContact(
evt.getSourceMetaContact());
if (uiContact != null)
{
ContactNode contactNode
= uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
/**
* Performs needed operations, when a <tt>MetaContact</tt> has been
* moved in the <tt>MetaContactListService</tt> from one group to another.
* @param evt the <tt>MetaContactMovedEvent</tt> that notified us
*/
public void metaContactMoved(final MetaContactMovedEvent evt)
{
final MetaContact metaContact = evt.getSourceMetaContact();
final MetaContactGroup oldParent = evt.getOldParent();
final MetaContactGroup newParent = evt.getNewParent();
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact == null)
return;
UIGroup oldUIGroup;
if (MetaContactListSource.isRootGroup(oldParent))
oldUIGroup = GuiActivator.getContactList().getTreeModel()
.getRoot().getGroupDescriptor();
else
oldUIGroup = MetaContactListSource.getUIGroup(oldParent);
if (oldUIGroup != null)
GuiActivator.getContactList().removeContact(uiContact);
// Add the contact to the new place.
uiContact = MetaContactListSource.createUIContact(
evt.getSourceMetaContact());
UIGroup newUIGroup = null;
if (!MetaContactListSource.isRootGroup(newParent))
{
newUIGroup = MetaContactListSource.getUIGroup(newParent);
if (newUIGroup == null)
newUIGroup
= MetaContactListSource.createUIGroup(newParent);
}
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
GuiActivator.getContactList()
.addContact(uiContact, newUIGroup, true, true);
else
MetaContactListSource.removeUIContact(metaContact);
}
/**
* Removes the corresponding contact node in the contact list, when a
* <tt>MetaContact</tt> has been removed from the
* <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactRemoved(final MetaContactEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact != null)
GuiActivator.getContactList().removeContact(uiContact);
}
}
/**
* Refreshes the corresponding node, when a <tt>MetaContact</tt> has been
* renamed in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactRenamedEvent</tt> that notified us
*/
public void metaContactRenamed(final MetaContactRenamedEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Notifies the tree model, when the <tt>MetaContact</tt> avatar has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactAvatarUpdated(final MetaContactAvatarUpdateEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(
evt.getSourceMetaContact());
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Adds a contact node corresponding to the parent <tt>MetaContact</tt> if
* this last is matching the current filter and wasn't previously contained
* in the contact list.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactAdded(ProtoContactEvent evt)
{
final MetaContact metaContact = evt.getNewParent();
synchronized (metaContact)
{
UIContact parentUIContact
= MetaContactListSource.getUIContact(metaContact);
if (parentUIContact == null)
{
UIContact uiContact
= MetaContactListSource.createUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
{
MetaContactGroup parentGroup
= metaContact.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource
.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(metaContact);
}
}
}
/**
* Notifies the UI representation of the parent <tt>MetaContact</tt> that
* this contact has been modified.
*
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactModified(ProtoContactEvent evt)
{
MetaContact metaContact = evt.getNewParent();
synchronized (metaContact)
{
UIContact uiContact = MetaContactListSource
.getUIContact(evt.getNewParent());
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Adds the new <tt>MetaContact</tt> parent and removes the old one if the
* first is matching the current filter and the last is no longer matching
* it.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactMoved(ProtoContactEvent evt)
{
final MetaContact oldParent = evt.getOldParent();
final MetaContact newParent = evt.getNewParent();
synchronized (oldParent)
{
UIContact oldUIContact
= MetaContactListSource.getUIContact(oldParent);
// Remove old parent if not matching.
if (oldUIContact != null
&& !GuiActivator.getContactList().getCurrentFilter()
.isMatching(oldUIContact))
{
GuiActivator.getContactList().removeContact(oldUIContact);
}
}
synchronized (newParent)
{
// Add new parent if matching.
UIContact newUIContact
= MetaContactListSource.getUIContact(newParent);
if (newUIContact == null)
{
newUIContact
= MetaContactListSource.createUIContact(newParent);
if (GuiActivator.getContactList().getCurrentFilter()
.isMatching(newUIContact))
{
MetaContactGroup parentGroup
= newParent.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource
.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(newUIContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(newParent);
}
}
}
/**
* Removes the contact node corresponding to the parent
* <tt>MetaContact</tt> if the last is no longer matching the current filter
* and wasn't previously contained in the contact list.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactRemoved(ProtoContactEvent evt)
{
final MetaContact oldParent = evt.getOldParent();
synchronized (oldParent)
{
UIContact oldUIContact
= MetaContactListSource.getUIContact(oldParent);
if (oldUIContact != null)
{
ContactNode contactNode = oldUIContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
}
| src/net/java/sip/communicator/impl/gui/main/contactlist/contactsource/MetaContactListSource.java | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist.contactsource;
import java.util.*;
import java.util.regex.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.contactlist.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import javax.swing.*;
/**
* The <tt>MetaContactListSource</tt> is an abstraction of the
* <tt>MetaContactListService</tt>, which makes the correspondence between a
* <tt>MetaContact</tt> and an <tt>UIContact</tt> and between a
* <tt>MetaContactGroup</tt> and an <tt>UIGroup</tt>. It is also responsible
* for filtering of the <tt>MetaContactListService</tt> through a given pattern.
*
* @author Yana Stamcheva
*/
public class MetaContactListSource
implements ContactPresenceStatusListener,
MetaContactListListener
{
/**
* The data key of the MetaContactDescriptor object used to store a
* reference to this object in its corresponding MetaContact.
*/
public static final String UI_CONTACT_DATA_KEY
= MetaUIContact.class.getName() + ".uiContactDescriptor";
/**
* The data key of the MetaGroupDescriptor object used to store a
* reference to this object in its corresponding MetaContactGroup.
*/
public static final String UI_GROUP_DATA_KEY
= MetaUIGroup.class.getName() + ".uiGroupDescriptor";
/**
* The initial result count below which we insert all filter results
* directly to the contact list without firing events.
*/
private final int INITIAL_CONTACT_COUNT = 30;
/**
* The logger.
*/
private static final Logger logger
= Logger.getLogger(MetaContactListSource.class);
/**
* Returns the <tt>UIContact</tt> corresponding to the given
* <tt>MetaContact</tt>.
* @param metaContact the <tt>MetaContact</tt>, which corresponding UI
* contact we're looking for
* @return the <tt>UIContact</tt> corresponding to the given
* <tt>MetaContact</tt>
*/
public static UIContact getUIContact(MetaContact metaContact)
{
return (UIContact) metaContact.getData(UI_CONTACT_DATA_KEY);
}
/**
* Returns the <tt>UIGroup</tt> corresponding to the given
* <tt>MetaContactGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt>, which UI group we're
* looking for
* @return the <tt>UIGroup</tt> corresponding to the given
* <tt>MetaContactGroup</tt>
*/
public static UIGroup getUIGroup(MetaContactGroup metaGroup)
{
return (UIGroup) metaGroup.getData(UI_GROUP_DATA_KEY);
}
/**
* Creates a <tt>UIContact</tt> for the given <tt>metaContact</tt>.
* @param metaContact the <tt>MetaContact</tt> for which we would like to
* create an <tt>UIContact</tt>
* @return an <tt>UIContact</tt> for the given <tt>metaContact</tt>
*/
public static UIContact createUIContact(final MetaContact metaContact)
{
final MetaUIContact descriptor
= new MetaUIContact(metaContact);
// fixes an issue with moving meta contacts where removeContact
// will set data to null in swing thread and it will be after we have
// set the data here, so we also move this set to the swing thread
// to order the calls of setData.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
metaContact.setData(UI_CONTACT_DATA_KEY, descriptor);
}
});
return descriptor;
}
/**
* Removes the <tt>UIContact</tt> from the given <tt>metaContact</tt>.
* @param metaContact the <tt>MetaContact</tt>, which corresponding UI
* contact we would like to remove
*/
public static void removeUIContact(MetaContact metaContact)
{
metaContact.setData(UI_CONTACT_DATA_KEY, null);
}
/**
* Creates a <tt>UIGroupDescriptor</tt> for the given <tt>metaGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt> for which we would like to
* create an <tt>UIContact</tt>
* @return a <tt>UIGroup</tt> for the given <tt>metaGroup</tt>
*/
public static UIGroup createUIGroup(MetaContactGroup metaGroup)
{
MetaUIGroup descriptor = new MetaUIGroup(metaGroup);
metaGroup.setData(UI_GROUP_DATA_KEY, descriptor);
return descriptor;
}
/**
* Removes the descriptor from the given <tt>metaGroup</tt>.
* @param metaGroup the <tt>MetaContactGroup</tt>, which descriptor we
* would like to remove
*/
public static void removeUIGroup(
MetaContactGroup metaGroup)
{
metaGroup.setData(UI_GROUP_DATA_KEY, null);
}
/**
* Indicates if the given <tt>MetaContactGroup</tt> is the root group.
* @param group the <tt>MetaContactGroup</tt> to check
* @return <tt>true</tt> if the given <tt>group</tt> is the root group,
* <tt>false</tt> - otherwise
*/
public static boolean isRootGroup(MetaContactGroup group)
{
return group.equals(GuiActivator.getContactListService().getRoot());
}
/**
* Filters the <tt>MetaContactListService</tt> to match the given
* <tt>filterPattern</tt> and stores the result in the given
* <tt>treeModel</tt>.
* @param filterPattern the pattern to filter through
* @return the created <tt>MetaContactQuery</tt> corresponding to the
* query this method does
*/
public MetaContactQuery queryMetaContactSource(final Pattern filterPattern)
{
final MetaContactQuery query = new MetaContactQuery();
new Thread()
{
public void run()
{
int resultCount = 0;
queryMetaContactSource( filterPattern,
GuiActivator.getContactListService().getRoot(),
query,
resultCount);
if (!query.isCanceled())
query.fireQueryEvent(
MetaContactQueryStatusEvent.QUERY_COMPLETED);
else
query.fireQueryEvent(
MetaContactQueryStatusEvent.QUERY_CANCELED);
}
}.start();
return query;
}
/**
* Filters the children in the given <tt>MetaContactGroup</tt> to match the
* given <tt>filterPattern</tt> and stores the result in the given
* <tt>treeModel</tt>.
* @param filterPattern the pattern to filter through
* @param parentGroup the <tt>MetaContactGroup</tt> to filter
* @param query the object that tracks the query
* @param resultCount the initial result count we would insert directly to
* the contact list without firing events
*/
public void queryMetaContactSource(Pattern filterPattern,
MetaContactGroup parentGroup,
MetaContactQuery query,
int resultCount)
{
Iterator<MetaContact> childContacts = parentGroup.getChildContacts();
while (childContacts.hasNext() && !query.isCanceled())
{
MetaContact metaContact = childContacts.next();
if (isMatching(filterPattern, metaContact))
{
synchronized (metaContact)
{
resultCount++;
if (resultCount <= INITIAL_CONTACT_COUNT)
{
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
UIContact uiContact = getUIContact(metaContact);
if (uiContact != null)
continue;
uiContact = createUIContact(metaContact);
GuiActivator.getContactList().addContact(
uiContact,
uiGroup,
true,
true);
query.setInitialResultCount(resultCount);
}
else
query.fireQueryEvent(metaContact);
}
}
}
// If in the meantime the query is canceled we return here.
if(query.isCanceled())
return;
Iterator<MetaContactGroup> subgroups = parentGroup.getSubgroups();
while (subgroups.hasNext() && !query.isCanceled())
{
MetaContactGroup subgroup = subgroups.next();
queryMetaContactSource(filterPattern, subgroup, query, resultCount);
}
}
/**
* Checks if the given <tt>metaContact</tt> is matching the given
* <tt>filterPattern</tt>.
* A <tt>MetaContact</tt> would be matching the filter if one of the
* following is true:<br>
* - its display name contains the filter string
* - at least one of its child protocol contacts has a display name or an
* address that contains the filter string.
* @param filterPattern the filter pattern to check for matches
* @param metaContact the <tt>MetaContact</tt> to check
* @return <tt>true</tt> to indicate that the given <tt>metaContact</tt> is
* matching the current filter, otherwise returns <tt>false</tt>
*/
private boolean isMatching(Pattern filterPattern, MetaContact metaContact)
{
Matcher matcher = filterPattern.matcher(metaContact.getDisplayName());
if(matcher.find())
return true;
Iterator<Contact> contacts = metaContact.getContacts();
while (contacts.hasNext())
{
Contact contact = contacts.next();
matcher = filterPattern.matcher(contact.getDisplayName());
if (matcher.find())
return true;
matcher = filterPattern.matcher(contact.getAddress());
if (matcher.find())
return true;
}
return false;
}
/**
* Checks if the given <tt>metaGroup</tt> is matching the current filter. A
* group is matching the current filter only if it contains at least one
* child <tt>MetaContact</tt>, which is matching the current filter.
* @param filterPattern the filter pattern to check for matches
* @param metaGroup the <tt>MetaContactGroup</tt> to check
* @return <tt>true</tt> to indicate that the given <tt>metaGroup</tt> is
* matching the current filter, otherwise returns <tt>false</tt>
*/
public boolean isMatching(Pattern filterPattern, MetaContactGroup metaGroup)
{
Iterator<MetaContact> contacts = metaGroup.getChildContacts();
while (contacts.hasNext())
{
MetaContact metaContact = contacts.next();
if (isMatching(filterPattern, metaContact))
return true;
}
return false;
}
@Override
public void contactPresenceStatusChanged(
ContactPresenceStatusChangeEvent evt)
{
if (evt.getOldStatus() == evt.getNewStatus())
return;
final Contact sourceContact = evt.getSourceContact();
final MetaContact metaContact
= GuiActivator.getContactListService().findMetaContactByContact(
sourceContact);
if (metaContact == null)
return;
synchronized (metaContact)
{
UIContact uiContact = getUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (uiContact == null)
{
uiContact = createUIContact(metaContact);
if (currentFilter != null && currentFilter.isMatching(uiContact))
{
MetaContactGroup parentGroup
= metaContact.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
if (logger.isDebugEnabled())
logger.debug(
"Add matching contact due to status change: "
+ uiContact.getDisplayName());
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
removeUIContact(metaContact);
}
else
{
if (currentFilter != null
&& !currentFilter.isMatching(uiContact))
{
if (logger.isDebugEnabled())
logger.debug(
"Remove unmatching contact due to status change: "
+ uiContact.getDisplayName());
GuiActivator.getContactList().removeContact(uiContact);
}
else
GuiActivator.getContactList()
.nodeChanged(uiContact.getContactNode());
}
}
}
/**
* Reorders contact list nodes, when <tt>MetaContact</tt>-s in a
* <tt>MetaContactGroup</tt> has been reordered.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void childContactsReordered(MetaContactGroupEvent evt)
{
MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup;
ContactListTreeModel treeModel
= GuiActivator.getContactList().getTreeModel();
if (isRootGroup(metaGroup))
uiGroup = treeModel.getRoot().getGroupDescriptor();
else
uiGroup = MetaContactListSource.getUIGroup(metaGroup);
if (uiGroup != null)
{
GroupNode groupNode = uiGroup.getGroupNode();
if (groupNode != null)
groupNode.sort(treeModel);
}
}
/**
* Adds a node in the contact list, when a <tt>MetaContact</tt> has been
* added in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactAdded(final MetaContactEvent evt)
{
final MetaContact metaContact = evt.getSourceMetaContact();
final MetaContactGroup parentGroup = evt.getParentGroup();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
// If there's already an UIContact for this meta contact, we have
// nothing to do here.
if (uiContact != null)
return;
uiContact = MetaContactListSource.createUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
{
UIGroup uiGroup = null;
if (!MetaContactListSource.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(metaContact);
}
}
/**
* Adds a group node in the contact list, when a <tt>MetaContactGroup</tt>
* has been added in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupAdded(MetaContactGroupEvent evt)
{
final MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup = MetaContactListSource.getUIGroup(metaGroup);
// If there's already an UIGroup for this meta contact, we have
// nothing to do here.
if (uiGroup != null)
return;
uiGroup = MetaContactListSource.createUIGroup(metaGroup);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiGroup))
GuiActivator.getContactList().addGroup(uiGroup, true);
else
MetaContactListSource.removeUIGroup(metaGroup);
}
/**
* Notifies the tree model, when a <tt>MetaContactGroup</tt> has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupModified(MetaContactGroupEvent evt)
{
final MetaContactGroup metaGroup = evt.getSourceMetaContactGroup();
UIGroup uiGroup
= MetaContactListSource.getUIGroup(metaGroup);
if (uiGroup != null)
{
GroupNode groupNode = uiGroup.getGroupNode();
if (groupNode != null)
GuiActivator.getContactList().getTreeModel()
.nodeChanged(groupNode);
}
}
/**
* Removes the corresponding group node in the contact list, when a
* <tt>MetaContactGroup</tt> has been removed from the
* <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactGroupEvent</tt> that notified us
*/
public void metaContactGroupRemoved(final MetaContactGroupEvent evt)
{
UIGroup uiGroup
= MetaContactListSource.getUIGroup(
evt.getSourceMetaContactGroup());
if (uiGroup != null)
GuiActivator.getContactList().removeGroup(uiGroup);
}
/**
* Notifies the tree model, when a <tt>MetaContact</tt> has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactModified(final MetaContactModifiedEvent evt)
{
UIContact uiContact
= MetaContactListSource.getUIContact(
evt.getSourceMetaContact());
if (uiContact != null)
{
ContactNode contactNode
= uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
/**
* Performs needed operations, when a <tt>MetaContact</tt> has been
* moved in the <tt>MetaContactListService</tt> from one group to another.
* @param evt the <tt>MetaContactMovedEvent</tt> that notified us
*/
public void metaContactMoved(final MetaContactMovedEvent evt)
{
final MetaContact metaContact = evt.getSourceMetaContact();
final MetaContactGroup oldParent = evt.getOldParent();
final MetaContactGroup newParent = evt.getNewParent();
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact == null)
return;
UIGroup oldUIGroup;
if (MetaContactListSource.isRootGroup(oldParent))
oldUIGroup = GuiActivator.getContactList().getTreeModel()
.getRoot().getGroupDescriptor();
else
oldUIGroup = MetaContactListSource.getUIGroup(oldParent);
if (oldUIGroup != null)
GuiActivator.getContactList().removeContact(uiContact);
// Add the contact to the new place.
uiContact = MetaContactListSource.createUIContact(
evt.getSourceMetaContact());
UIGroup newUIGroup = null;
if (!MetaContactListSource.isRootGroup(newParent))
{
newUIGroup = MetaContactListSource.getUIGroup(newParent);
if (newUIGroup == null)
newUIGroup
= MetaContactListSource.createUIGroup(newParent);
}
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
GuiActivator.getContactList()
.addContact(uiContact, newUIGroup, true, true);
else
MetaContactListSource.removeUIContact(metaContact);
}
/**
* Removes the corresponding contact node in the contact list, when a
* <tt>MetaContact</tt> has been removed from the
* <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactRemoved(final MetaContactEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact != null)
GuiActivator.getContactList().removeContact(uiContact);
}
}
/**
* Refreshes the corresponding node, when a <tt>MetaContact</tt> has been
* renamed in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactRenamedEvent</tt> that notified us
*/
public void metaContactRenamed(final MetaContactRenamedEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(metaContact);
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Notifies the tree model, when the <tt>MetaContact</tt> avatar has been
* modified in the <tt>MetaContactListService</tt>.
* @param evt the <tt>MetaContactEvent</tt> that notified us
*/
public void metaContactAvatarUpdated(final MetaContactAvatarUpdateEvent evt)
{
MetaContact metaContact = evt.getSourceMetaContact();
synchronized (metaContact)
{
UIContact uiContact
= MetaContactListSource.getUIContact(
evt.getSourceMetaContact());
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Adds a contact node corresponding to the parent <tt>MetaContact</tt> if
* this last is matching the current filter and wasn't previously contained
* in the contact list.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactAdded(ProtoContactEvent evt)
{
final MetaContact metaContact = evt.getNewParent();
synchronized (metaContact)
{
UIContact parentUIContact
= MetaContactListSource.getUIContact(metaContact);
if (parentUIContact == null)
{
UIContact uiContact
= MetaContactListSource.createUIContact(metaContact);
ContactListFilter currentFilter
= GuiActivator.getContactList().getCurrentFilter();
if (currentFilter.isMatching(uiContact))
{
MetaContactGroup parentGroup
= metaContact.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource
.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(uiContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(metaContact);
}
}
}
/**
* Notifies the UI representation of the parent <tt>MetaContact</tt> that
* this contact has been modified.
*
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactModified(ProtoContactEvent evt)
{
MetaContact metaContact = evt.getNewParent();
synchronized (metaContact)
{
UIContact uiContact = MetaContactListSource
.getUIContact(evt.getNewParent());
if (uiContact != null)
{
ContactNode contactNode = uiContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
/**
* Adds the new <tt>MetaContact</tt> parent and removes the old one if the
* first is matching the current filter and the last is no longer matching
* it.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactMoved(ProtoContactEvent evt)
{
final MetaContact oldParent = evt.getOldParent();
final MetaContact newParent = evt.getNewParent();
synchronized (oldParent)
{
UIContact oldUIContact
= MetaContactListSource.getUIContact(oldParent);
// Remove old parent if not matching.
if (oldUIContact != null
&& !GuiActivator.getContactList().getCurrentFilter()
.isMatching(oldUIContact))
{
GuiActivator.getContactList().removeContact(oldUIContact);
}
}
synchronized (newParent)
{
// Add new parent if matching.
UIContact newUIContact
= MetaContactListSource.getUIContact(newParent);
if (newUIContact == null)
{
newUIContact
= MetaContactListSource.createUIContact(newParent);
if (GuiActivator.getContactList().getCurrentFilter()
.isMatching(newUIContact))
{
MetaContactGroup parentGroup
= newParent.getParentMetaContactGroup();
UIGroup uiGroup = null;
if (!MetaContactListSource
.isRootGroup(parentGroup))
{
uiGroup = MetaContactListSource
.getUIGroup(parentGroup);
if (uiGroup == null)
uiGroup = MetaContactListSource
.createUIGroup(parentGroup);
}
GuiActivator.getContactList()
.addContact(newUIContact, uiGroup, true, true);
}
else
MetaContactListSource.removeUIContact(newParent);
}
}
}
/**
* Removes the contact node corresponding to the parent
* <tt>MetaContact</tt> if the last is no longer matching the current filter
* and wasn't previously contained in the contact list.
* @param evt the <tt>ProtoContactEvent</tt> that notified us
*/
public void protoContactRemoved(ProtoContactEvent evt)
{
final MetaContact oldParent = evt.getOldParent();
synchronized (oldParent)
{
UIContact oldUIContact
= MetaContactListSource.getUIContact(oldParent);
if (oldUIContact != null)
{
ContactNode contactNode = oldUIContact.getContactNode();
if (contactNode != null)
GuiActivator.getContactList().nodeChanged(contactNode);
}
}
}
}
| Fixes java 1.5 compatibility.
| src/net/java/sip/communicator/impl/gui/main/contactlist/contactsource/MetaContactListSource.java | Fixes java 1.5 compatibility. |
|
Java | apache-2.0 | b3c4d0d5b43007af66c835a5426e379e78358699 | 0 | ist-dresden/sling,mmanski/sling,tyge68/sling,headwirecom/sling,SylvesterAbreu/sling,JEBailey/sling,tteofili/sling,tmaret/sling,roele/sling,cleliameneghin/sling,tyge68/sling,tteofili/sling,JEBailey/sling,nleite/sling,vladbailescu/sling,vladbailescu/sling,labertasch/sling,SylvesterAbreu/sling,Nimco/sling,Nimco/sling,mikibrv/sling,JEBailey/sling,labertasch/sling,Nimco/sling,anchela/sling,ist-dresden/sling,headwirecom/sling,ieb/sling,ieb/sling,mmanski/sling,headwirecom/sling,tmaret/sling,labertasch/sling,tyge68/sling,nleite/sling,mcdan/sling,roele/sling,headwirecom/sling,trekawek/sling,Nimco/sling,headwirecom/sling,tteofili/sling,cleliameneghin/sling,nleite/sling,tteofili/sling,ieb/sling,mmanski/sling,trekawek/sling,mcdan/sling,trekawek/sling,tmaret/sling,trekawek/sling,mcdan/sling,mikibrv/sling,ieb/sling,mcdan/sling,wimsymons/sling,mmanski/sling,nleite/sling,awadheshv/sling,ist-dresden/sling,Nimco/sling,mmanski/sling,roele/sling,tmaret/sling,awadheshv/sling,mikibrv/sling,ieb/sling,wimsymons/sling,tyge68/sling,JEBailey/sling,wimsymons/sling,awadheshv/sling,SylvesterAbreu/sling,anchela/sling,vladbailescu/sling,ieb/sling,mcdan/sling,anchela/sling,mikibrv/sling,mcdan/sling,vladbailescu/sling,nleite/sling,wimsymons/sling,tteofili/sling,labertasch/sling,ist-dresden/sling,nleite/sling,SylvesterAbreu/sling,JEBailey/sling,Nimco/sling,ist-dresden/sling,awadheshv/sling,anchela/sling,anchela/sling,tyge68/sling,awadheshv/sling,wimsymons/sling,vladbailescu/sling,cleliameneghin/sling,cleliameneghin/sling,awadheshv/sling,wimsymons/sling,SylvesterAbreu/sling,trekawek/sling,labertasch/sling,tmaret/sling,tyge68/sling,roele/sling,tteofili/sling,roele/sling,mikibrv/sling,mmanski/sling,SylvesterAbreu/sling,trekawek/sling,cleliameneghin/sling,mikibrv/sling | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.discovery.base.its;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.sling.discovery.ClusterView;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEvent.Type;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.discovery.base.commons.ClusterViewHelper;
import org.apache.sling.discovery.base.commons.ClusterViewService;
import org.apache.sling.discovery.base.commons.UndefinedClusterViewException;
import org.apache.sling.discovery.base.connectors.announcement.Announcement;
import org.apache.sling.discovery.base.connectors.announcement.AnnouncementFilter;
import org.apache.sling.discovery.base.connectors.announcement.AnnouncementRegistry;
import org.apache.sling.discovery.base.its.setup.VirtualInstance;
import org.apache.sling.discovery.base.its.setup.VirtualInstanceBuilder;
import org.apache.sling.discovery.base.its.setup.mock.AcceptsMultiple;
import org.apache.sling.discovery.base.its.setup.mock.AssertingTopologyEventListener;
import org.apache.sling.discovery.base.its.setup.mock.PropertyProviderImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractClusterTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private class SimpleClusterView {
private VirtualInstance[] instances;
SimpleClusterView(VirtualInstance... instances) {
this.instances = instances;
}
@Override
public String toString() {
String instanceSlingIds = "";
for(int i=0; i<instances.length; i++) {
instanceSlingIds = instanceSlingIds + instances[i].slingId + ",";
}
return "an expected cluster with "+instances.length+" instances: "+instanceSlingIds;
}
}
VirtualInstance instance1;
VirtualInstance instance2;
VirtualInstance instance3;
private String property1Value;
protected String property2Value;
private String property1Name;
private String property2Name;
VirtualInstance instance4;
VirtualInstance instance5;
VirtualInstance instance1Restarted;
private Level logLevel;
protected abstract VirtualInstanceBuilder newBuilder();
@Before
public void setup() throws Exception {
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.TRACE);
logger.debug("here we are");
instance1 = newBuilder().setDebugName("firstInstance").newRepository("/var/discovery/impl/", true).build();
instance2 = newBuilder().setDebugName("secondInstance").useRepositoryOf(instance1).build();
}
@After
public void tearDown() throws Exception {
if (instance5 != null) {
instance5.stop();
}
if (instance4 != null) {
instance4.stop();
}
if (instance3 != null) {
instance3.stop();
}
if (instance3 != null) {
instance3.stop();
}
if (instance2 != null) {
instance2.stop();
}
if (instance1 != null) {
instance1.stop();
}
if (instance1Restarted != null) {
instance1Restarted.stop();
}
instance1Restarted = null;
instance1 = null;
instance2 = null;
instance3 = null;
instance4 = null;
instance5 = null;
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
discoveryLogger.setLevel(logLevel);
}
/** test leader behaviour with ascending slingIds, SLING-3253 **/
@Test
public void testLeaderAsc() throws Throwable {
logger.info("testLeaderAsc: start");
doTestLeader("000", "111");
logger.info("testLeaderAsc: end");
}
/** test leader behaviour with descending slingIds, SLING-3253 **/
@Test
public void testLeaderDesc() throws Throwable {
logger.info("testLeaderDesc: start");
doTestLeader("111", "000");
logger.info("testLeaderDesc: end");
}
private void doTestLeader(String slingId1, String slingId2) throws Throwable {
logger.info("doTestLeader("+slingId1+","+slingId2+"): start");
// stop 1 and 2 and create them with a lower heartbeat timeout
instance2.stopViewChecker();
instance1.stopViewChecker();
instance2.stop();
instance1.stop();
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(30)
.setMinEventDelay(1)
.setSlingId(slingId1).build();
// sleep so that the two dont have the same startup time, and thus leaderElectionId is lower for instance1
logger.info("doTestLeader: 1st sleep 200ms");
Thread.sleep(200);
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(30)
.setMinEventDelay(1)
.setSlingId(slingId2).build();
assertNotNull(instance1);
assertNotNull(instance2);
// the two instances are still isolated - hence they throw an exception
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// let the sync/voting happen
for(int m=0; m<4; m++) {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
logger.info("doTestLeader: sleep 500ms");
Thread.sleep(500);
}
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
// now they must be in the same cluster, so in a cluster of size 1
assertEquals(2, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView().getInstances().size());
// the first instance should be the leader - since it was started first
assertTrue(instance1.getLocalInstanceDescription().isLeader());
assertFalse(instance2.getLocalInstanceDescription().isLeader());
logger.info("doTestLeader("+slingId1+","+slingId2+"): end");
}
/**
* Tests stale announcement reported in SLING-4139:
* An instance which crashes but had announcements, never cleans up those announcements.
* Thus on a restart, those announcements are still there, even if the connector
* would no longer be in use (or point somewhere else etc).
* That has various effects, one of them tested in this method: peers in the same cluster,
* after the crashed/stopped instance restarts, will assume those stale announcements
* as being correct and include them in the topology - hence reporting stale instances
* (which can be old instances or even duplicates).
*/
@Test
public void testStaleAnnouncementsVisibleToClusterPeers4139() throws Throwable {
logger.info("testStaleAnnouncementsVisibleToClusterPeers4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
// facts: connector 3->1 does not exist actively anymore,
// instance 1+2 should build a cluster,
// instance 3 should be isolated
logger.info("instance1Restarted.dump: "+instance1Restarted.slingId);
instance1Restarted.dumpRepo();
logger.info("instance2.dump: "+instance2.slingId);
instance2.dumpRepo();
logger.info("instance3.dump: "+instance3.slingId);
instance3.dumpRepo();
assertTopology(instance1Restarted, new SimpleClusterView(instance1Restarted, instance2));
assertTopology(instance3, new SimpleClusterView(instance3));
assertTopology(instance2, new SimpleClusterView(instance1Restarted, instance2));
instance1Restarted.stop();
logger.info("testStaleAnnouncementsVisibleToClusterPeers4139: end");
}
/**
* Tests a situation where a connector was done to instance1, which eventually
* crashed, then the connector is done to instance2. Meanwhile instance1
* got restarted and this test assures that the instance3 is not reported
* twice in the topology. Did not happen before 4139, but should never afterwards neither
*/
@Test
public void testDuplicateInstanceIn2Clusters4139() throws Throwable {
logger.info("testDuplicateInstanceIn2Clusters4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// instead, now start a connector from instance3 to instance2
pingConnector(instance3, instance2);
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
logger.info("iteration 0");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2), new SimpleClusterView(instance3));
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
logger.info("iteration 1");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2), new SimpleClusterView(instance3));
instance1Restarted.stop();
logger.info("testDuplicateInstanceIn2Clusters4139: end");
}
/* ok, this test should do the following:
* cluster A with instance 1 and instance 2
* cluster B with instance 3 and instance 4
* cluster C with instance 5
* initially, instance3 is pinging instance1, and instance 5 is pinging instance1 as well (MAC hub)
* that should result in instance3 and 5 to inherit the rest from instance1
* then simulate load balancer switching from instance1 to instance2 - hence pings go to instance2
*
*/
@Test
public void testConnectorSwitching4139() throws Throwable {
final int MIN_EVENT_DELAY = 1;
tearDown(); // reset any setup that was done - we start with a different setup than the default one
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.DEBUG);
instance1 = newBuilder().setDebugName("instance1")
.newRepository("/var/discovery/clusterA/", true)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance2 = newBuilder().setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// now launch the remote instance
instance3 = newBuilder().setDebugName("instance3")
.newRepository("/var/discovery/clusterB/", false)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance4 = newBuilder().setDebugName("instance4")
.useRepositoryOf(instance3)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance5 = newBuilder().setDebugName("instance5")
.newRepository("/var/discovery/clusterC/", false)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// join the instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
assertSameTopology(new SimpleClusterView(instance1, instance2));
assertSameTopology(new SimpleClusterView(instance3, instance4));
assertSameTopology(new SimpleClusterView(instance5));
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
Thread.sleep(500);
// make asserts on the topology
logger.info("testConnectorSwitching4139: instance1.slingId="+instance1.slingId);
logger.info("testConnectorSwitching4139: instance2.slingId="+instance2.slingId);
logger.info("testConnectorSwitching4139: instance3.slingId="+instance3.slingId);
logger.info("testConnectorSwitching4139: instance4.slingId="+instance4.slingId);
logger.info("testConnectorSwitching4139: instance5.slingId="+instance5.slingId);
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
// simulate a crash of instance1, resulting in load-balancer to switch the pings
boolean success = false;
for(int i=0; i<25; i++) {
// loop for max 25 times, min 20 times
runHeartbeatOnceWith(instance2, instance3, instance4, instance5);
final boolean ping1 = pingConnector(instance3, instance2);
final boolean ping2 = pingConnector(instance5, instance2);
if (ping1 && ping2) {
// both pings were fine - hence break
success = true;
logger.info("testConnectorSwitching4139: successfully switched all pings to instance2 after "+i+" rounds.");
if (i<20) {
logger.info("testConnectorSwitching4139: min loop cnt not yet reached: i="+i);
Thread.sleep(1000); // 20x1000ms = 20sec max - (vs 10sec timeout) - should be enough for timing out
continue;
}
break;
}
logger.info("testConnectorSwitching4139: looping cos ping1="+ping1+", ping2="+ping2);
Thread.sleep(1000); // 25x1000ms = 25sec max - (vs 10sec timeout)
}
assertTrue(success);
// one final heartbeat
runHeartbeatOnceWith(instance2, instance3, instance4, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
instance2.dumpRepo();
assertSameTopology(new SimpleClusterView(instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
// restart instance1, crash instance4
instance4.stopViewChecker();
instance1Restarted = newBuilder().setDebugName("instance1")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1.getSlingId()).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
success = false;
for(int i=0; i<25; i++) {
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance5);
instance1.getViewChecker().checkView();
// we used to do:
//assertTrue(pingConnector(instance3, instance2));
// but that could fail with the introduction of marking
// an establishedView as failing upon detecting a view change
// when the view changes, we're sending TOPOLOGY_CHANGING to listeners
// so getTopology() should also return isCurrent==false - which
// means that doing a ping will also fail, cos that wants to
// get a current topology to send as an announcement.
// which is a long way of saying: we cannot do an assert here
// since instance3 *can* have an undefined cluster view..
try{
pingConnector(instance3, instance2);
} catch(UndefinedClusterViewException ucve) {
// ignore
}
pingConnector(instance5, instance2);
final TopologyView topology = instance3.getDiscoveryService().getTopology();
InstanceDescription i3 = null;
for (Iterator<InstanceDescription> it = topology.getInstances().iterator(); it.hasNext();) {
final InstanceDescription id = it.next();
if (id.getSlingId().equals(instance3.slingId)) {
i3 = id;
break;
}
}
assertNotNull(i3);
assertEquals(instance3.slingId, i3.getSlingId());
final ClusterView i3Cluster = i3.getClusterView();
final int i3ClusterSize = i3Cluster.getInstances().size();
if (i3ClusterSize==1) {
if (i<20) {
logger.info("testConnectorSwitching4139: [2] min loop cnt not yet reached: i="+i);
Thread.sleep(500); // 20x500ms = 10sec max - (vs 5sec timeout) - should be enough for timing out
continue;
}
success = true;
break;
}
logger.info("testConnectorSwitching4139: i3ClusterSize: "+i3ClusterSize);
Thread.sleep(500);
}
logger.info("testConnectorSwitching4139: instance1Restarted.slingId="+instance1Restarted.slingId);
logger.info("testConnectorSwitching4139: instance2.slingId="+instance2.slingId);
logger.info("testConnectorSwitching4139: instance3.slingId="+instance3.slingId);
logger.info("testConnectorSwitching4139: instance4.slingId="+instance4.slingId);
logger.info("testConnectorSwitching4139: instance5.slingId="+instance5.slingId);
instance1Restarted.dumpRepo();
assertTrue(success);
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2),
new SimpleClusterView(instance3),
new SimpleClusterView(instance5));
instance1Restarted.stop();
}
@Test
public void testDuplicateInstance3726() throws Throwable {
logger.info("testDuplicateInstance3726: start");
final int MIN_EVENT_DELAY = 1;
tearDown(); // reset any setup that was done - we start with a different setup than the default one
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.DEBUG);
instance1 = newBuilder().setDebugName("instance1")
.newRepository("/var/discovery/clusterA/", true)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance2 = newBuilder().setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// now launch the remote instance
instance3 = newBuilder().setDebugName("instance3")
.newRepository("/var/discovery/clusterB/", false)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance5 = newBuilder().setDebugName("instance5")
.newRepository("/var/discovery/clusterC/", false)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// join the instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
assertSameTopology(new SimpleClusterView(instance1, instance2));
assertSameTopology(new SimpleClusterView(instance3));
assertSameTopology(new SimpleClusterView(instance5));
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
// make asserts on the topology
logger.info("testDuplicateInstance3726: instance1.slingId="+instance1.slingId);
logger.info("testDuplicateInstance3726: instance2.slingId="+instance2.slingId);
logger.info("testDuplicateInstance3726: instance3.slingId="+instance3.slingId);
logger.info("testDuplicateInstance3726: instance5.slingId="+instance5.slingId);
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2),
new SimpleClusterView(instance3/*, instance4*/),
new SimpleClusterView(instance5));
// simulate a crash of instance1, resulting in load-balancer to switch the pings
instance1.stopViewChecker();
boolean success = false;
for(int i=0; i<25; i++) {
// loop for max 25 times, min 20 times
runHeartbeatOnceWith(instance2, instance3, /*instance4, */instance5);
final boolean ping1 = pingConnector(instance3, instance2);
final boolean ping2 = pingConnector(instance5, instance2);
if (ping1 && ping2) {
// both pings were fine - hence break
success = true;
logger.info("testDuplicateInstance3726: successfully switched all pings to instance2 after "+i+" rounds.");
if (i<20) {
logger.info("testDuplicateInstance3726: min loop cnt not yet reached: i="+i);
Thread.sleep(1000); // 20x1000ms = 20sec max - (vs 15sec timeout) - should be enough for timing out
continue;
}
break;
}
logger.info("testDuplicateInstance3726: looping");
Thread.sleep(1000); // 25x1000ms = 25sec max - (vs 15sec timeout)
}
assertTrue(success);
// one final heartbeat
runHeartbeatOnceWith(instance2, instance3, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
instance2.dumpRepo();
assertSameTopology(new SimpleClusterView(instance2),
new SimpleClusterView(instance3),
new SimpleClusterView(instance5));
// restart instance1, start instance4
instance1Restarted = newBuilder().setDebugName("instance1")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1.getSlingId()).build();
instance4 = newBuilder().setDebugName("instance4")
.useRepositoryOf(instance3)
.setConnectorPingTimeout(30 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
for(int i=0; i<3; i++) {
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4, instance5);
Thread.sleep(250);
// since instance4 just started - hooked to instance3
// it is possible that it doesn't just have a topology
// yet - so we cannot do:
//assertTrue(pingConnector(instance3, instance2));
// but instead do
try{
pingConnector(instance3, instance2);
} catch(UndefinedClusterViewException ucve) {
// ignore
}
assertTrue(pingConnector(instance5, instance2));
}
instance1Restarted.dumpRepo();
logger.info("testDuplicateInstance3726: instance1Restarted.slingId="+instance1Restarted.slingId);
logger.info("testDuplicateInstance3726: instance2.slingId="+instance2.slingId);
logger.info("testDuplicateInstance3726: instance3.slingId="+instance3.slingId);
logger.info("testDuplicateInstance3726: instance4.slingId="+instance4.slingId);
logger.info("testDuplicateInstance3726: instance5.slingId="+instance5.slingId);
assertTrue(success);
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
instance1Restarted.stop();
logger.info("testDuplicateInstance3726: end");
}
private void assertSameTopology(SimpleClusterView... clusters) throws UndefinedClusterViewException {
if (clusters==null) {
return;
}
for(int i=0; i<clusters.length; i++) { // go through all clusters
final SimpleClusterView aCluster = clusters[i];
assertSameClusterIds(aCluster.instances);
for(int j=0; j<aCluster.instances.length; j++) { // and all instances therein
final VirtualInstance anInstance = aCluster.instances[j];
assertTopology(anInstance, clusters); // an verify that they all see the same
for(int k=0; k<clusters.length; k++) {
final SimpleClusterView otherCluster = clusters[k];
if (aCluster==otherCluster) {
continue; // then ignore this one
}
for(int m=0; m<otherCluster.instances.length; m++) {
assertNotSameClusterIds(anInstance, otherCluster.instances[m]);
}
}
}
}
}
private void runHeartbeatOnceWith(VirtualInstance... instances) {
if (instances==null) {
return;
}
for(int i=0; i<instances.length; i++) {
instances[i].heartbeatsAndCheckView();
}
}
/**
* Tests a situation where a connector was done to instance1, which eventually
* crashed, then the connector is done to instance4 (which is in a separate, 3rd cluster).
* Meanwhile instance1 got restarted and this test assures that the instance3 is not reported
* twice in the topology. This used to happen prior to SLING-4139
*/
@Test
public void testStaleInstanceIn3Clusters4139() throws Throwable {
logger.info("testStaleInstanceIn3Clusters4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// start instance4 in a separate cluster
instance4 = newBuilder().setDebugName("remoteInstance4")
.newRepository("/var/discovery/implremote4/", false)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
try{
instance4.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// instead, now start a connector from instance3 to instance2
instance4.heartbeatsAndCheckView();
instance4.heartbeatsAndCheckView();
pingConnector(instance3, instance4);
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
logger.info("iteration 0");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
Thread.sleep(100);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
logger.info("iteration 1");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
Thread.sleep(100);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
// now the situation should be as follows:
logger.info("iteration 2");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
instance1Restarted.stop();
logger.info("testStaleInstanceIn3Clusters4139: end");
}
/**
* Preparation steps for SLING-4139 tests:
* Creates two clusters: A: with instance1 and 2, B with instance 3
* instance 3 creates a connector to instance 1
* then instance 1 is killed (crashes)
* @return the slingId of the original (crashed) instance1
*/
private String prepare4139() throws Throwable, Exception,
InterruptedException {
tearDown(); // stop anything running..
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
// join the two instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2);
Thread.sleep(100);
runHeartbeatOnceWith(instance1, instance2);
Thread.sleep(100);
runHeartbeatOnceWith(instance1, instance2);
assertSameClusterIds(instance1, instance2);
// now launch the remote instance
instance3 = newBuilder().setDebugName("remoteInstance")
.newRepository("/var/discovery/implremote/", false)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
assertSameClusterIds(instance1, instance2);
try{
instance3.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException ue) {
// ok
}
assertEquals(0, instance1.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance1.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
assertEquals(0, instance2.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance2.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
assertEquals(0, instance3.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance3.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
instance3.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
Thread.sleep(1000);
pingConnector(instance3, instance1);
// make asserts on the topology
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2), new SimpleClusterView(instance3));
// kill instance 1
logger.info("instance1.slingId="+instance1.slingId);
logger.info("instance2.slingId="+instance2.slingId);
logger.info("instance3.slingId="+instance3.slingId);
final String instance1SlingId = instance1.slingId;
instance1.stopViewChecker(); // and have instance3 no longer pinging instance1
instance1.stop(); // otherwise it will have itself still registered with the observation manager and fiddle with future events..
instance1 = null; // set to null to early fail if anyone still assumes (original) instance1 is up form now on
instance2.getConfig().setViewCheckTimeout(1); // set instance2's heartbeatTimeout to 1 sec to time out instance1 quickly!
instance3.getConfig().setViewCheckTimeout(1); // set instance3's heartbeatTimeout to 1 sec to time out instance1 quickly!
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
// instance 2 should now be alone - in fact, 3 should be alone as well
instance2.dumpRepo();
assertTopology(instance2, new SimpleClusterView(instance2));
assertTopology(instance3, new SimpleClusterView(instance3));
instance2.getConfig().setViewCheckTimeout(Integer.MAX_VALUE /* no timeout */); // set instance2's heartbeatTimeout back to Integer.MAX_VALUE /* no timeout */
instance3.getConfig().setViewCheckTimeout(Integer.MAX_VALUE /* no timeout */); // set instance3's heartbeatTimeout back to Integer.MAX_VALUE /* no timeout */
return instance1SlingId;
}
private void assertNotSameClusterIds(VirtualInstance... instances) throws UndefinedClusterViewException {
if (instances==null) {
fail("must not pass empty set of instances here");
}
if (instances.length<=1) {
fail("must not pass 0 or 1 instance only");
}
final String clusterId1 = instances[0].getClusterViewService()
.getLocalClusterView().getId();
for(int i=1; i<instances.length; i++) {
final String otherClusterId = instances[i].getClusterViewService()
.getLocalClusterView().getId();
// cluster ids must NOT be the same
assertNotEquals(clusterId1, otherClusterId);
}
if (instances.length>2) {
final VirtualInstance[] subset = new VirtualInstance[instances.length-1];
System.arraycopy(instances, 0, subset, 1, instances.length-1);
assertNotSameClusterIds(subset);
}
}
private void assertSameClusterIds(VirtualInstance... instances) throws UndefinedClusterViewException {
if (instances==null) {
// then there is nothing to compare
return;
}
if (instances.length==1) {
// then there is nothing to compare
return;
}
final String clusterId1 = instances[0].getClusterViewService()
.getLocalClusterView().getId();
for(int i=1; i<instances.length; i++) {
final String otherClusterId = instances[i].getClusterViewService()
.getLocalClusterView().getId();
// cluster ids must be the same
if (!clusterId1.equals(otherClusterId)) {
logger.error("assertSameClusterIds: instances[0]: "+instances[0]);
logger.error("assertSameClusterIds: instances["+i+"]: "+instances[i]);
fail("mismatch in clusterIds: expected to equal: clusterId1="+clusterId1+", otherClusterId="+otherClusterId);
}
}
}
private void assertTopology(VirtualInstance instance, SimpleClusterView... assertedClusterViews) {
final TopologyView topology = instance.getDiscoveryService().getTopology();
logger.info("assertTopology: instance "+instance.slingId+" sees topology: "+topology+", expected: "+assertedClusterViews);
assertNotNull(topology);
if (assertedClusterViews.length!=topology.getClusterViews().size()) {
dumpFailureDetails(topology, assertedClusterViews);
fail("instance "+instance.slingId+ " expected "+assertedClusterViews.length+", got: "+topology.getClusterViews().size());
}
final Set<ClusterView> actualClusters = new HashSet<ClusterView>(topology.getClusterViews());
for(int i=0; i<assertedClusterViews.length; i++) {
final SimpleClusterView assertedClusterView = assertedClusterViews[i];
boolean foundMatch = false;
for (Iterator<ClusterView> it = actualClusters.iterator(); it
.hasNext();) {
final ClusterView actualClusterView = it.next();
if (matches(assertedClusterView, actualClusterView)) {
it.remove();
foundMatch = true;
break;
}
}
if (!foundMatch) {
dumpFailureDetails(topology, assertedClusterViews);
fail("instance "+instance.slingId+ " could not find a match in the topology with instance="+instance.slingId+" and clusterViews="+assertedClusterViews.length);
}
}
assertEquals("not all asserted clusterviews are in the actual view with instance="+instance+" and clusterViews="+assertedClusterViews, actualClusters.size(), 0);
}
private void dumpFailureDetails(TopologyView topology, SimpleClusterView... assertedClusterViews) {
logger.error("assertTopology: expected: "+assertedClusterViews.length);
for(int j=0; j<assertedClusterViews.length; j++) {
logger.error("assertTopology: ["+j+"]: "+assertedClusterViews[j].toString());
}
final Set<ClusterView> clusterViews = topology.getClusterViews();
final Set<InstanceDescription> instances = topology.getInstances();
logger.error("assertTopology: actual: "+clusterViews.size()+" clusters with a total of "+instances.size()+" instances");
for (Iterator<ClusterView> it = clusterViews.iterator(); it.hasNext();) {
final ClusterView aCluster = it.next();
logger.error("assertTopology: a cluster: "+aCluster.getId());
for (Iterator<InstanceDescription> it2 = aCluster.getInstances().iterator(); it2.hasNext();) {
final InstanceDescription id = it2.next();
logger.error("assertTopology: - an instance "+id.getSlingId());
}
}
logger.error("assertTopology: list of all instances: "+instances.size());
for (Iterator<InstanceDescription> it = instances.iterator(); it.hasNext();) {
final InstanceDescription id = it.next();
logger.error("assertTopology: - an instance: "+id.getSlingId());
}
}
private boolean matches(SimpleClusterView assertedClusterView,
ClusterView actualClusterView) {
assertNotNull(assertedClusterView);
assertNotNull(actualClusterView);
if (assertedClusterView.instances.length!=actualClusterView.getInstances().size()) {
return false;
}
final Set<InstanceDescription> actualInstances = new HashSet<InstanceDescription>(actualClusterView.getInstances());
outerLoop:for(int i=0; i<assertedClusterView.instances.length; i++) {
final VirtualInstance assertedInstance = assertedClusterView.instances[i];
for (Iterator<InstanceDescription> it = actualInstances.iterator(); it
.hasNext();) {
final InstanceDescription anActualInstance = it.next();
if (assertedInstance.slingId.equals(anActualInstance.getSlingId())) {
continue outerLoop;
}
}
return false;
}
return true;
}
private boolean pingConnector(final VirtualInstance from, final VirtualInstance to) throws UndefinedClusterViewException {
final Announcement fromAnnouncement = createFromAnnouncement(from);
Announcement replyAnnouncement = null;
try{
replyAnnouncement = ping(to, fromAnnouncement);
} catch(AssertionError e) {
logger.warn("pingConnector: ping failed, assertionError: "+e);
return false;
} catch (UndefinedClusterViewException e) {
logger.warn("pingConnector: ping failed, currently the cluster view is undefined: "+e);
return false;
}
registerReplyAnnouncement(from, replyAnnouncement);
return true;
}
private void registerReplyAnnouncement(VirtualInstance from,
Announcement inheritedAnnouncement) {
final AnnouncementRegistry announcementRegistry = from.getAnnouncementRegistry();
if (inheritedAnnouncement.isLoop()) {
fail("loop detected");
// we dont currently support loops here in the junit tests
return;
} else {
inheritedAnnouncement.setInherited(true);
if (announcementRegistry
.registerAnnouncement(inheritedAnnouncement)==-1) {
logger.info("ping: connector response is from an instance which I already see in my topology"
+ inheritedAnnouncement);
return;
}
}
// resultingAnnouncement = inheritedAnnouncement;
// statusDetails = null;
}
private Announcement ping(VirtualInstance to, final Announcement incomingTopologyAnnouncement)
throws UndefinedClusterViewException {
final String slingId = to.slingId;
final ClusterViewService clusterViewService = to.getClusterViewService();
final AnnouncementRegistry announcementRegistry = to.getAnnouncementRegistry();
incomingTopologyAnnouncement.removeInherited(slingId);
final Announcement replyAnnouncement = new Announcement(
slingId);
long backoffInterval = -1;
final ClusterView clusterView = clusterViewService.getLocalClusterView();
if (!incomingTopologyAnnouncement.isCorrectVersion()) {
fail("incorrect version");
return null; // never reached
} else if (ClusterViewHelper.contains(clusterView, incomingTopologyAnnouncement
.getOwnerId())) {
fail("loop=true");
return null; // never reached
} else if (ClusterViewHelper.containsAny(clusterView, incomingTopologyAnnouncement
.listInstances())) {
fail("incoming announcement contains instances that are part of my cluster");
return null; // never reached
} else {
backoffInterval = announcementRegistry
.registerAnnouncement(incomingTopologyAnnouncement);
if (backoffInterval==-1) {
fail("rejecting an announcement from an instance that I already see in my topology: ");
return null; // never reached
} else {
// normal, successful case: replying with the part of the topology which this instance sees
replyAnnouncement.setLocalCluster(clusterView);
announcementRegistry.addAllExcept(replyAnnouncement, clusterView,
new AnnouncementFilter() {
public boolean accept(final String receivingSlingId, Announcement announcement) {
if (announcement.getPrimaryKey().equals(
incomingTopologyAnnouncement
.getPrimaryKey())) {
return false;
}
return true;
}
});
return replyAnnouncement;
}
}
}
private Announcement createFromAnnouncement(final VirtualInstance from) throws UndefinedClusterViewException {
// TODO: refactor TopologyConnectorClient to avoid duplicating code from there (ping())
Announcement topologyAnnouncement = new Announcement(from.slingId);
topologyAnnouncement.setServerInfo(from.slingId);
final ClusterView clusterView = from.getClusterViewService().getLocalClusterView();
topologyAnnouncement.setLocalCluster(clusterView);
from.getAnnouncementRegistry().addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {
public boolean accept(final String receivingSlingId, final Announcement announcement) {
// filter out announcements that are of old cluster instances
// which I dont really have in my cluster view at the moment
final Iterator<InstanceDescription> it =
clusterView.getInstances().iterator();
while(it.hasNext()) {
final InstanceDescription instance = it.next();
if (instance.getSlingId().equals(receivingSlingId)) {
// then I have the receiving instance in my cluster view
// all fine then
return true;
}
}
// looks like I dont have the receiving instance in my cluster view
// then I should also not propagate that announcement anywhere
return false;
}
});
return topologyAnnouncement;
}
@Test
public void testStableClusterId() throws Throwable {
logger.info("testStableClusterId: start");
// stop 1 and 2 and create them with a lower heartbeat timeout
instance2.stopViewChecker();
instance1.stopViewChecker();
instance2.stop();
instance1.stop();
// SLING-4302 : first set the heartbeatTimeout to 100 sec - large enough to work on all CI instances
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(100)
.setMinEventDelay(1).build();
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(100)
.setMinEventDelay(1).build();
assertNotNull(instance1);
assertNotNull(instance2);
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// let the sync/voting happen
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
String newClusterId1 = instance1.getClusterViewService()
.getLocalClusterView().getId();
String newClusterId2 = instance2.getClusterViewService()
.getLocalClusterView().getId();
// both cluster ids must be the same
assertEquals(newClusterId1, newClusterId1);
instance1.dumpRepo();
assertEquals(2, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView().getInstances().size());
// let instance2 'die' by now longer doing heartbeats
// SLING-4302 : then set the heartbeatTimeouts back to 1 sec to have them properly time out with the sleeps applied below
instance2.getConfig().setViewCheckTimeout(1);
instance1.getConfig().setViewCheckTimeout(1);
instance2.stopViewChecker(); // would actually not be necessary as it was never started.. this test only runs heartbeats manually
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
// the cluster should now have size 1
assertEquals(1, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
// the instance 2 should be in isolated mode as it is no longer in the established view
// hence null
try{
instance2.getViewChecker().checkView();
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// but the cluster id must have remained stable
instance1.dumpRepo();
String actualClusterId = instance1.getClusterViewService()
.getLocalClusterView().getId();
logger.info("expected cluster id: "+newClusterId1);
logger.info("actual cluster id: "+actualClusterId);
assertEquals(newClusterId1, actualClusterId);
logger.info("testStableClusterId: end");
}
@Test
public void testClusterView() throws Exception {
logger.info("testClusterView: start");
assertNotNull(instance1);
assertNotNull(instance2);
assertNull(instance3);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
assertNotNull(instance3);
assertEquals(instance1.getSlingId(), instance1.getClusterViewService()
.getSlingId());
assertEquals(instance2.getSlingId(), instance2.getClusterViewService()
.getSlingId());
assertEquals(instance3.getSlingId(), instance3.getClusterViewService()
.getSlingId());
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance3.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
instance1.dumpRepo();
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
instance1.dumpRepo();
logger.info("testClusterView: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testClusterView: 2nd 2s sleep");
Thread.sleep(2000);
instance1.dumpRepo();
String clusterId1 = instance1.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId1=" + clusterId1);
String clusterId2 = instance2.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId2=" + clusterId2);
String clusterId3 = instance3.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId3=" + clusterId3);
assertEquals(clusterId1, clusterId2);
assertEquals(clusterId1, clusterId3);
assertEquals(3, instance1.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(3, instance2.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(3, instance3.getClusterViewService().getLocalClusterView()
.getInstances().size());
logger.info("testClusterView: end");
}
@Test
public void testAdditionalInstance() throws Throwable {
logger.info("testAdditionalInstance: start");
assertNotNull(instance1);
assertNotNull(instance2);
assertEquals(instance1.getSlingId(), instance1.getClusterViewService()
.getSlingId());
assertEquals(instance2.getSlingId(), instance2.getClusterViewService()
.getSlingId());
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance1.dumpRepo();
logger.info("testAdditionalInstance: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 2nd 2s sleep");
Thread.sleep(2000);
instance1.dumpRepo();
String clusterId1 = instance1.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId1=" + clusterId1);
String clusterId2 = instance2.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId2=" + clusterId2);
assertEquals(clusterId1, clusterId2);
assertEquals(2, instance1.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView()
.getInstances().size());
AssertingTopologyEventListener assertingTopologyEventListener = new AssertingTopologyEventListener();
assertingTopologyEventListener.addExpected(Type.TOPOLOGY_INIT);
assertEquals(1, assertingTopologyEventListener.getRemainingExpectedCount());
instance1.bindTopologyEventListener(assertingTopologyEventListener);
Thread.sleep(500); // SLING-4755: async event sending requires some minimal wait time nowadays
assertEquals(0, assertingTopologyEventListener.getRemainingExpectedCount());
// startup instance 3
AcceptsMultiple acceptsMultiple = new AcceptsMultiple(
Type.TOPOLOGY_CHANGING, Type.TOPOLOGY_CHANGED);
assertingTopologyEventListener.addExpected(acceptsMultiple);
assertingTopologyEventListener.addExpected(acceptsMultiple);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 3rd 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 4th 2s sleep");
Thread.sleep(2000);
assertEquals(1, acceptsMultiple.getEventCnt(Type.TOPOLOGY_CHANGING));
assertEquals(1, acceptsMultiple.getEventCnt(Type.TOPOLOGY_CHANGED));
logger.info("testAdditionalInstance: end");
}
@Test
public void testPropertyProviders() throws Throwable {
logger.info("testPropertyProviders: start");
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
assertNull(instance3);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 2nd 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 3rd 2s sleep");
Thread.sleep(2000);
property1Value = UUID.randomUUID().toString();
property1Name = UUID.randomUUID().toString();
PropertyProviderImpl pp1 = new PropertyProviderImpl();
pp1.setProperty(property1Name, property1Value);
instance1.bindPropertyProvider(pp1, property1Name);
property2Value = UUID.randomUUID().toString();
property2Name = UUID.randomUUID().toString();
PropertyProviderImpl pp2 = new PropertyProviderImpl();
pp2.setProperty(property2Name, property2Value);
instance2.bindPropertyProvider(pp2, property2Name);
assertPropertyValues();
property1Value = UUID.randomUUID().toString();
pp1.setProperty(property1Name, property1Value);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
assertPropertyValues();
assertNull(instance1.getClusterViewService().getLocalClusterView()
.getInstances().get(0)
.getProperty(UUID.randomUUID().toString()));
assertNull(instance2.getClusterViewService().getLocalClusterView()
.getInstances().get(0)
.getProperty(UUID.randomUUID().toString()));
logger.info("testPropertyProviders: end");
}
private void assertPropertyValues() throws UndefinedClusterViewException {
assertPropertyValues(instance1.getSlingId(), property1Name,
property1Value);
assertPropertyValues(instance2.getSlingId(), property2Name,
property2Value);
}
private void assertPropertyValues(String slingId, String name, String value) throws UndefinedClusterViewException {
assertEquals(value, getInstance(instance1, slingId).getProperty(name));
assertEquals(value, getInstance(instance2, slingId).getProperty(name));
}
private InstanceDescription getInstance(VirtualInstance instance, String slingId) throws UndefinedClusterViewException {
Iterator<InstanceDescription> it = instance.getClusterViewService()
.getLocalClusterView().getInstances().iterator();
while (it.hasNext()) {
InstanceDescription id = it.next();
if (id.getSlingId().equals(slingId)) {
return id;
}
}
throw new IllegalStateException("instance not found: instance="
+ instance + ", slingId=" + slingId);
}
class LongRunningListener implements TopologyEventListener {
String failMsg = null;
boolean initReceived = false;
int noninitReceived;
private Semaphore changedSemaphore = new Semaphore(0);
public void assertNoFail() {
if (failMsg!=null) {
fail(failMsg);
}
}
public Semaphore getChangedSemaphore() {
return changedSemaphore;
}
public void handleTopologyEvent(TopologyEvent event) {
if (failMsg!=null) {
failMsg += "/ Already failed, got another event; "+event;
return;
}
if (!initReceived) {
if (event.getType()!=Type.TOPOLOGY_INIT) {
failMsg = "Expected TOPOLOGY_INIT first, got: "+event.getType();
return;
}
initReceived = true;
return;
}
if (event.getType()==Type.TOPOLOGY_CHANGED) {
try {
changedSemaphore.acquire();
} catch (InterruptedException e) {
throw new Error("don't interrupt me pls: "+e);
}
}
noninitReceived++;
}
}
/**
* Test plan:
* * have a discoveryservice with two listeners registered
* * one of them (the 'first' one) is long running
* * during one of the topology changes, when the first
* one is hit, deactivate the discovery service
* * that deactivation used to block (SLING-4755) due
* to synchronized(lock) which was blocked by the
* long running listener. With having asynchronous
* event sending this should no longer be the case
* * also, once asserted that deactivation finished,
* and that the first listener is still busy, make
* sure that once the first listener finishes, that
* the second listener still gets the event
* @throws Throwable
*/
@Test
public void testLongRunningListener() throws Throwable {
// let the instance1 become alone, instance2 is idle
instance1.getConfig().setViewCheckTimeout(2);
instance2.getConfig().setViewCheckTimeout(2);
logger.info("testLongRunningListener : letting instance2 remain silent from now on");
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
logger.info("testLongRunningListener : instance 2 should now be considered dead");
// instance1.dumpRepo();
LongRunningListener longRunningListener1 = new LongRunningListener();
AssertingTopologyEventListener fastListener2 = new AssertingTopologyEventListener();
fastListener2.addExpected(Type.TOPOLOGY_INIT);
longRunningListener1.assertNoFail();
assertEquals(1, fastListener2.getRemainingExpectedCount());
logger.info("testLongRunningListener : binding longRunningListener1 ...");
instance1.bindTopologyEventListener(longRunningListener1);
logger.info("testLongRunningListener : binding fastListener2 ...");
instance1.bindTopologyEventListener(fastListener2);
logger.info("testLongRunningListener : waiting a bit for longRunningListener1 to receive the TOPOLOGY_INIT event");
Thread.sleep(2500); // SLING-4755: async event sending requires some minimal wait time nowadays
assertEquals(0, fastListener2.getRemainingExpectedCount());
assertTrue(longRunningListener1.initReceived);
// after INIT, now do an actual change where listener1 will do a long-running handling
fastListener2.addExpected(Type.TOPOLOGY_CHANGING);
fastListener2.addExpected(Type.TOPOLOGY_CHANGED);
instance1.getConfig().setViewCheckTimeout(10);
instance2.getConfig().setViewCheckTimeout(10);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.dumpRepo();
longRunningListener1.assertNoFail();
// nothing unexpected should arrive at listener2:
assertEquals(0, fastListener2.getUnexpectedCount());
// however, listener2 should only get one (CHANGING) event, cos the CHANGED event is still blocked
assertEquals(1, fastListener2.getRemainingExpectedCount());
// and also listener2 should only get CHANGING, the CHANGED is blocked via changedSemaphore
assertEquals(1, longRunningListener1.noninitReceived);
assertTrue(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
Thread.sleep(2000);
// even after a 2sec sleep things should be unchanged:
assertEquals(0, fastListener2.getUnexpectedCount());
assertEquals(1, fastListener2.getRemainingExpectedCount());
assertEquals(1, longRunningListener1.noninitReceived);
assertTrue(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
// now let's simulate SLING-4755: deactivation while longRunningListener1 does long processing
// - which is simulated by waiting on changedSemaphore.
final List<Exception> asyncException = new LinkedList<Exception>();
Thread th = new Thread(new Runnable() {
public void run() {
try {
instance1.stop();
} catch (Exception e) {
synchronized(asyncException) {
asyncException.add(e);
}
}
}
});
th.start();
logger.info("Waiting max 4 sec...");
th.join(4000);
logger.info("Done waiting max 4 sec...");
if (th.isAlive()) {
logger.warn("Thread still alive: "+th.isAlive());
// release before issuing fail as otherwise test will block forever
longRunningListener1.getChangedSemaphore().release();
fail("Thread was still alive");
}
logger.info("Thread was no longer alive: "+th.isAlive());
synchronized(asyncException) {
logger.info("Async exceptions: "+asyncException.size());
if (asyncException.size()!=0) {
// release before issuing fail as otherwise test will block forever
longRunningListener1.getChangedSemaphore().release();
fail("async exceptions: "+asyncException.size()+", first: "+asyncException.get(0));
}
}
// now the test consists of
// a) the fact that we reached this place without unlocking the changedSemaphore
// b) when we now unlock the changedSemaphore the remaining events should flush through
longRunningListener1.getChangedSemaphore().release();
Thread.sleep(500);// shouldn't take long and then things should have flushed:
assertEquals(0, fastListener2.getUnexpectedCount());
assertEquals(0, fastListener2.getRemainingExpectedCount());
assertEquals(2, longRunningListener1.noninitReceived);
assertFalse(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
}
}
| bundles/extensions/discovery/base/src/test/java/org/apache/sling/discovery/base/its/AbstractClusterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.discovery.base.its;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.sling.discovery.ClusterView;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEvent.Type;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.discovery.base.commons.ClusterViewHelper;
import org.apache.sling.discovery.base.commons.ClusterViewService;
import org.apache.sling.discovery.base.commons.UndefinedClusterViewException;
import org.apache.sling.discovery.base.connectors.announcement.Announcement;
import org.apache.sling.discovery.base.connectors.announcement.AnnouncementFilter;
import org.apache.sling.discovery.base.connectors.announcement.AnnouncementRegistry;
import org.apache.sling.discovery.base.its.setup.VirtualInstance;
import org.apache.sling.discovery.base.its.setup.VirtualInstanceBuilder;
import org.apache.sling.discovery.base.its.setup.mock.AcceptsMultiple;
import org.apache.sling.discovery.base.its.setup.mock.AssertingTopologyEventListener;
import org.apache.sling.discovery.base.its.setup.mock.PropertyProviderImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractClusterTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private class SimpleClusterView {
private VirtualInstance[] instances;
SimpleClusterView(VirtualInstance... instances) {
this.instances = instances;
}
@Override
public String toString() {
String instanceSlingIds = "";
for(int i=0; i<instances.length; i++) {
instanceSlingIds = instanceSlingIds + instances[i].slingId + ",";
}
return "an expected cluster with "+instances.length+" instances: "+instanceSlingIds;
}
}
VirtualInstance instance1;
VirtualInstance instance2;
VirtualInstance instance3;
private String property1Value;
protected String property2Value;
private String property1Name;
private String property2Name;
VirtualInstance instance4;
VirtualInstance instance5;
VirtualInstance instance1Restarted;
private Level logLevel;
protected abstract VirtualInstanceBuilder newBuilder();
@Before
public void setup() throws Exception {
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.TRACE);
logger.debug("here we are");
instance1 = newBuilder().setDebugName("firstInstance").newRepository("/var/discovery/impl/", true).build();
instance2 = newBuilder().setDebugName("secondInstance").useRepositoryOf(instance1).build();
}
@After
public void tearDown() throws Exception {
if (instance5 != null) {
instance5.stop();
}
if (instance4 != null) {
instance4.stop();
}
if (instance3 != null) {
instance3.stop();
}
if (instance3 != null) {
instance3.stop();
}
if (instance2 != null) {
instance2.stop();
}
if (instance1 != null) {
instance1.stop();
}
if (instance1Restarted != null) {
instance1Restarted.stop();
}
instance1Restarted = null;
instance1 = null;
instance2 = null;
instance3 = null;
instance4 = null;
instance5 = null;
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
discoveryLogger.setLevel(logLevel);
}
/** test leader behaviour with ascending slingIds, SLING-3253 **/
@Test
public void testLeaderAsc() throws Throwable {
logger.info("testLeaderAsc: start");
doTestLeader("000", "111");
logger.info("testLeaderAsc: end");
}
/** test leader behaviour with descending slingIds, SLING-3253 **/
@Test
public void testLeaderDesc() throws Throwable {
logger.info("testLeaderDesc: start");
doTestLeader("111", "000");
logger.info("testLeaderDesc: end");
}
private void doTestLeader(String slingId1, String slingId2) throws Throwable {
logger.info("doTestLeader("+slingId1+","+slingId2+"): start");
// stop 1 and 2 and create them with a lower heartbeat timeout
instance2.stopViewChecker();
instance1.stopViewChecker();
instance2.stop();
instance1.stop();
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(30)
.setMinEventDelay(1)
.setSlingId(slingId1).build();
// sleep so that the two dont have the same startup time, and thus leaderElectionId is lower for instance1
logger.info("doTestLeader: 1st sleep 200ms");
Thread.sleep(200);
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(30)
.setMinEventDelay(1)
.setSlingId(slingId2).build();
assertNotNull(instance1);
assertNotNull(instance2);
// the two instances are still isolated - hence they throw an exception
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// let the sync/voting happen
for(int m=0; m<4; m++) {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
logger.info("doTestLeader: sleep 500ms");
Thread.sleep(500);
}
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
// now they must be in the same cluster, so in a cluster of size 1
assertEquals(2, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView().getInstances().size());
// the first instance should be the leader - since it was started first
assertTrue(instance1.getLocalInstanceDescription().isLeader());
assertFalse(instance2.getLocalInstanceDescription().isLeader());
logger.info("doTestLeader("+slingId1+","+slingId2+"): end");
}
/**
* Tests stale announcement reported in SLING-4139:
* An instance which crashes but had announcements, never cleans up those announcements.
* Thus on a restart, those announcements are still there, even if the connector
* would no longer be in use (or point somewhere else etc).
* That has various effects, one of them tested in this method: peers in the same cluster,
* after the crashed/stopped instance restarts, will assume those stale announcements
* as being correct and include them in the topology - hence reporting stale instances
* (which can be old instances or even duplicates).
*/
@Test
public void testStaleAnnouncementsVisibleToClusterPeers4139() throws Throwable {
logger.info("testStaleAnnouncementsVisibleToClusterPeers4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
// facts: connector 3->1 does not exist actively anymore,
// instance 1+2 should build a cluster,
// instance 3 should be isolated
logger.info("instance1Restarted.dump: "+instance1Restarted.slingId);
instance1Restarted.dumpRepo();
logger.info("instance2.dump: "+instance2.slingId);
instance2.dumpRepo();
logger.info("instance3.dump: "+instance3.slingId);
instance3.dumpRepo();
assertTopology(instance1Restarted, new SimpleClusterView(instance1Restarted, instance2));
assertTopology(instance3, new SimpleClusterView(instance3));
assertTopology(instance2, new SimpleClusterView(instance1Restarted, instance2));
instance1Restarted.stop();
logger.info("testStaleAnnouncementsVisibleToClusterPeers4139: end");
}
/**
* Tests a situation where a connector was done to instance1, which eventually
* crashed, then the connector is done to instance2. Meanwhile instance1
* got restarted and this test assures that the instance3 is not reported
* twice in the topology. Did not happen before 4139, but should never afterwards neither
*/
@Test
public void testDuplicateInstanceIn2Clusters4139() throws Throwable {
logger.info("testDuplicateInstanceIn2Clusters4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// instead, now start a connector from instance3 to instance2
pingConnector(instance3, instance2);
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
logger.info("iteration 0");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2), new SimpleClusterView(instance3));
Thread.sleep(500);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3);
pingConnector(instance3, instance2);
logger.info("iteration 1");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2), new SimpleClusterView(instance3));
instance1Restarted.stop();
logger.info("testDuplicateInstanceIn2Clusters4139: end");
}
/* ok, this test should do the following:
* cluster A with instance 1 and instance 2
* cluster B with instance 3 and instance 4
* cluster C with instance 5
* initially, instance3 is pinging instance1, and instance 5 is pinging instance1 as well (MAC hub)
* that should result in instance3 and 5 to inherit the rest from instance1
* then simulate load balancer switching from instance1 to instance2 - hence pings go to instance2
*
*/
@Test
public void testConnectorSwitching4139() throws Throwable {
final int MIN_EVENT_DELAY = 1;
tearDown(); // reset any setup that was done - we start with a different setup than the default one
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.DEBUG);
instance1 = newBuilder().setDebugName("instance1")
.newRepository("/var/discovery/clusterA/", true)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance2 = newBuilder().setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// now launch the remote instance
instance3 = newBuilder().setDebugName("instance3")
.newRepository("/var/discovery/clusterB/", false)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance4 = newBuilder().setDebugName("instance4")
.useRepositoryOf(instance3)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance5 = newBuilder().setDebugName("instance5")
.newRepository("/var/discovery/clusterC/", false)
.setConnectorPingTimeout(10 /* sec */)
.setConnectorPingInterval(999)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// join the instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
Thread.sleep(500);
assertSameTopology(new SimpleClusterView(instance1, instance2));
assertSameTopology(new SimpleClusterView(instance3, instance4));
assertSameTopology(new SimpleClusterView(instance5));
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance4, instance5);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
Thread.sleep(500);
// make asserts on the topology
logger.info("testConnectorSwitching4139: instance1.slingId="+instance1.slingId);
logger.info("testConnectorSwitching4139: instance2.slingId="+instance2.slingId);
logger.info("testConnectorSwitching4139: instance3.slingId="+instance3.slingId);
logger.info("testConnectorSwitching4139: instance4.slingId="+instance4.slingId);
logger.info("testConnectorSwitching4139: instance5.slingId="+instance5.slingId);
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
// simulate a crash of instance1, resulting in load-balancer to switch the pings
boolean success = false;
for(int i=0; i<25; i++) {
// loop for max 25 times, min 20 times
runHeartbeatOnceWith(instance2, instance3, instance4, instance5);
final boolean ping1 = pingConnector(instance3, instance2);
final boolean ping2 = pingConnector(instance5, instance2);
if (ping1 && ping2) {
// both pings were fine - hence break
success = true;
logger.info("testConnectorSwitching4139: successfully switched all pings to instance2 after "+i+" rounds.");
if (i<20) {
logger.info("testConnectorSwitching4139: min loop cnt not yet reached: i="+i);
Thread.sleep(1000); // 20x1000ms = 20sec max - (vs 10sec timeout) - should be enough for timing out
continue;
}
break;
}
logger.info("testConnectorSwitching4139: looping cos ping1="+ping1+", ping2="+ping2);
Thread.sleep(1000); // 25x1000ms = 25sec max - (vs 10sec timeout)
}
assertTrue(success);
// one final heartbeat
runHeartbeatOnceWith(instance2, instance3, instance4, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
instance2.dumpRepo();
assertSameTopology(new SimpleClusterView(instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
// restart instance1, crash instance4
instance4.stopViewChecker();
instance1Restarted = newBuilder().setDebugName("instance1")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1.getSlingId()).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
success = false;
for(int i=0; i<25; i++) {
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance5);
instance1.getViewChecker().checkView();
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
final TopologyView topology = instance3.getDiscoveryService().getTopology();
InstanceDescription i3 = null;
for (Iterator<InstanceDescription> it = topology.getInstances().iterator(); it.hasNext();) {
final InstanceDescription id = it.next();
if (id.getSlingId().equals(instance3.slingId)) {
i3 = id;
break;
}
}
assertNotNull(i3);
assertEquals(instance3.slingId, i3.getSlingId());
final ClusterView i3Cluster = i3.getClusterView();
final int i3ClusterSize = i3Cluster.getInstances().size();
if (i3ClusterSize==1) {
if (i<20) {
logger.info("testConnectorSwitching4139: [2] min loop cnt not yet reached: i="+i);
Thread.sleep(500); // 20x500ms = 10sec max - (vs 5sec timeout) - should be enough for timing out
continue;
}
success = true;
break;
}
logger.info("testConnectorSwitching4139: i3ClusterSize: "+i3ClusterSize);
Thread.sleep(500);
}
logger.info("testConnectorSwitching4139: instance1Restarted.slingId="+instance1Restarted.slingId);
logger.info("testConnectorSwitching4139: instance2.slingId="+instance2.slingId);
logger.info("testConnectorSwitching4139: instance3.slingId="+instance3.slingId);
logger.info("testConnectorSwitching4139: instance4.slingId="+instance4.slingId);
logger.info("testConnectorSwitching4139: instance5.slingId="+instance5.slingId);
instance1Restarted.dumpRepo();
assertTrue(success);
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2),
new SimpleClusterView(instance3),
new SimpleClusterView(instance5));
instance1Restarted.stop();
}
@Test
public void testDuplicateInstance3726() throws Throwable {
logger.info("testDuplicateInstance3726: start");
final int MIN_EVENT_DELAY = 1;
tearDown(); // reset any setup that was done - we start with a different setup than the default one
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.DEBUG);
instance1 = newBuilder().setDebugName("instance1")
.newRepository("/var/discovery/clusterA/", true)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance2 = newBuilder().setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// now launch the remote instance
instance3 = newBuilder().setDebugName("instance3")
.newRepository("/var/discovery/clusterB/", false)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
instance5 = newBuilder().setDebugName("instance5")
.newRepository("/var/discovery/clusterC/", false)
.setConnectorPingTimeout(15 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
// join the instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
runHeartbeatOnceWith(instance1, instance2, instance3, instance5);
Thread.sleep(500);
assertSameTopology(new SimpleClusterView(instance1, instance2));
assertSameTopology(new SimpleClusterView(instance3));
assertSameTopology(new SimpleClusterView(instance5));
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
pingConnector(instance3, instance1);
pingConnector(instance5, instance1);
// make asserts on the topology
logger.info("testDuplicateInstance3726: instance1.slingId="+instance1.slingId);
logger.info("testDuplicateInstance3726: instance2.slingId="+instance2.slingId);
logger.info("testDuplicateInstance3726: instance3.slingId="+instance3.slingId);
logger.info("testDuplicateInstance3726: instance5.slingId="+instance5.slingId);
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2),
new SimpleClusterView(instance3/*, instance4*/),
new SimpleClusterView(instance5));
// simulate a crash of instance1, resulting in load-balancer to switch the pings
instance1.stopViewChecker();
boolean success = false;
for(int i=0; i<25; i++) {
// loop for max 25 times, min 20 times
runHeartbeatOnceWith(instance2, instance3, /*instance4, */instance5);
final boolean ping1 = pingConnector(instance3, instance2);
final boolean ping2 = pingConnector(instance5, instance2);
if (ping1 && ping2) {
// both pings were fine - hence break
success = true;
logger.info("testDuplicateInstance3726: successfully switched all pings to instance2 after "+i+" rounds.");
if (i<20) {
logger.info("testDuplicateInstance3726: min loop cnt not yet reached: i="+i);
Thread.sleep(1000); // 20x1000ms = 20sec max - (vs 15sec timeout) - should be enough for timing out
continue;
}
break;
}
logger.info("testDuplicateInstance3726: looping");
Thread.sleep(1000); // 25x1000ms = 25sec max - (vs 15sec timeout)
}
assertTrue(success);
// one final heartbeat
runHeartbeatOnceWith(instance2, instance3, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
instance2.dumpRepo();
assertSameTopology(new SimpleClusterView(instance2),
new SimpleClusterView(instance3),
new SimpleClusterView(instance5));
// restart instance1, start instance4
instance1Restarted = newBuilder().setDebugName("instance1")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1.getSlingId()).build();
instance4 = newBuilder().setDebugName("instance4")
.useRepositoryOf(instance3)
.setConnectorPingTimeout(30 /* sec */)
.setMinEventDelay(MIN_EVENT_DELAY).build();
for(int i=0; i<3; i++) {
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4, instance5);
assertTrue(pingConnector(instance3, instance2));
assertTrue(pingConnector(instance5, instance2));
}
instance1Restarted.dumpRepo();
logger.info("testDuplicateInstance3726: instance1Restarted.slingId="+instance1Restarted.slingId);
logger.info("testDuplicateInstance3726: instance2.slingId="+instance2.slingId);
logger.info("testDuplicateInstance3726: instance3.slingId="+instance3.slingId);
logger.info("testDuplicateInstance3726: instance4.slingId="+instance4.slingId);
logger.info("testDuplicateInstance3726: instance5.slingId="+instance5.slingId);
assertTrue(success);
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2),
new SimpleClusterView(instance3, instance4),
new SimpleClusterView(instance5));
instance1Restarted.stop();
logger.info("testDuplicateInstance3726: end");
}
private void assertSameTopology(SimpleClusterView... clusters) throws UndefinedClusterViewException {
if (clusters==null) {
return;
}
for(int i=0; i<clusters.length; i++) { // go through all clusters
final SimpleClusterView aCluster = clusters[i];
assertSameClusterIds(aCluster.instances);
for(int j=0; j<aCluster.instances.length; j++) { // and all instances therein
final VirtualInstance anInstance = aCluster.instances[j];
assertTopology(anInstance, clusters); // an verify that they all see the same
for(int k=0; k<clusters.length; k++) {
final SimpleClusterView otherCluster = clusters[k];
if (aCluster==otherCluster) {
continue; // then ignore this one
}
for(int m=0; m<otherCluster.instances.length; m++) {
assertNotSameClusterIds(anInstance, otherCluster.instances[m]);
}
}
}
}
}
private void runHeartbeatOnceWith(VirtualInstance... instances) {
if (instances==null) {
return;
}
for(int i=0; i<instances.length; i++) {
instances[i].heartbeatsAndCheckView();
}
}
/**
* Tests a situation where a connector was done to instance1, which eventually
* crashed, then the connector is done to instance4 (which is in a separate, 3rd cluster).
* Meanwhile instance1 got restarted and this test assures that the instance3 is not reported
* twice in the topology. This used to happen prior to SLING-4139
*/
@Test
public void testStaleInstanceIn3Clusters4139() throws Throwable {
logger.info("testStaleInstanceIn3Clusters4139: start");
final String instance1SlingId = prepare4139();
// remove topology connector from instance3 to instance1
// -> corresponds to stop pinging
// (nothing to assert additionally here)
// start instance4 in a separate cluster
instance4 = newBuilder().setDebugName("remoteInstance4")
.newRepository("/var/discovery/implremote4/", false)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
try{
instance4.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// instead, now start a connector from instance3 to instance2
instance4.heartbeatsAndCheckView();
instance4.heartbeatsAndCheckView();
pingConnector(instance3, instance4);
// start instance 1
instance1Restarted = newBuilder().setDebugName("firstInstance")
.useRepositoryOf(instance2)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1)
.setSlingId(instance1SlingId).build();
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
logger.info("iteration 0");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
Thread.sleep(100);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
logger.info("iteration 1");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
Thread.sleep(100);
runHeartbeatOnceWith(instance1Restarted, instance2, instance3, instance4);
pingConnector(instance3, instance4);
// now the situation should be as follows:
logger.info("iteration 2");
logger.info("instance1Restarted.slingId: "+instance1Restarted.slingId);
logger.info("instance2.slingId: "+instance2.slingId);
logger.info("instance3.slingId: "+instance3.slingId);
logger.info("instance4.slingId: "+instance4.slingId);
instance1Restarted.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1Restarted, instance2));
assertSameTopology(
new SimpleClusterView(instance3),
new SimpleClusterView(instance4));
instance1Restarted.stop();
logger.info("testStaleInstanceIn3Clusters4139: end");
}
/**
* Preparation steps for SLING-4139 tests:
* Creates two clusters: A: with instance1 and 2, B with instance 3
* instance 3 creates a connector to instance 1
* then instance 1 is killed (crashes)
* @return the slingId of the original (crashed) instance1
*/
private String prepare4139() throws Throwable, Exception,
InterruptedException {
tearDown(); // stop anything running..
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
// join the two instances to form a cluster by sending out heartbeats
runHeartbeatOnceWith(instance1, instance2);
Thread.sleep(100);
runHeartbeatOnceWith(instance1, instance2);
Thread.sleep(100);
runHeartbeatOnceWith(instance1, instance2);
assertSameClusterIds(instance1, instance2);
// now launch the remote instance
instance3 = newBuilder().setDebugName("remoteInstance")
.newRepository("/var/discovery/implremote/", false)
.setConnectorPingTimeout(Integer.MAX_VALUE /* no timeout */)
.setMinEventDelay(1).build();
assertSameClusterIds(instance1, instance2);
try{
instance3.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException ue) {
// ok
}
assertEquals(0, instance1.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance1.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
assertEquals(0, instance2.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance2.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
assertEquals(0, instance3.getAnnouncementRegistry().listLocalAnnouncements().size());
assertEquals(0, instance3.getAnnouncementRegistry().listLocalIncomingAnnouncements().size());
// create a topology connector from instance3 to instance1
// -> corresponds to starting to ping
instance3.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
Thread.sleep(1000);
pingConnector(instance3, instance1);
// make asserts on the topology
instance1.dumpRepo();
assertSameTopology(new SimpleClusterView(instance1, instance2), new SimpleClusterView(instance3));
// kill instance 1
logger.info("instance1.slingId="+instance1.slingId);
logger.info("instance2.slingId="+instance2.slingId);
logger.info("instance3.slingId="+instance3.slingId);
final String instance1SlingId = instance1.slingId;
instance1.stopViewChecker(); // and have instance3 no longer pinging instance1
instance1.stop(); // otherwise it will have itself still registered with the observation manager and fiddle with future events..
instance1 = null; // set to null to early fail if anyone still assumes (original) instance1 is up form now on
instance2.getConfig().setViewCheckTimeout(1); // set instance2's heartbeatTimeout to 1 sec to time out instance1 quickly!
instance3.getConfig().setViewCheckTimeout(1); // set instance3's heartbeatTimeout to 1 sec to time out instance1 quickly!
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
Thread.sleep(500);
runHeartbeatOnceWith(instance2, instance3);
// instance 2 should now be alone - in fact, 3 should be alone as well
instance2.dumpRepo();
assertTopology(instance2, new SimpleClusterView(instance2));
assertTopology(instance3, new SimpleClusterView(instance3));
instance2.getConfig().setViewCheckTimeout(Integer.MAX_VALUE /* no timeout */); // set instance2's heartbeatTimeout back to Integer.MAX_VALUE /* no timeout */
instance3.getConfig().setViewCheckTimeout(Integer.MAX_VALUE /* no timeout */); // set instance3's heartbeatTimeout back to Integer.MAX_VALUE /* no timeout */
return instance1SlingId;
}
private void assertNotSameClusterIds(VirtualInstance... instances) throws UndefinedClusterViewException {
if (instances==null) {
fail("must not pass empty set of instances here");
}
if (instances.length<=1) {
fail("must not pass 0 or 1 instance only");
}
final String clusterId1 = instances[0].getClusterViewService()
.getLocalClusterView().getId();
for(int i=1; i<instances.length; i++) {
final String otherClusterId = instances[i].getClusterViewService()
.getLocalClusterView().getId();
// cluster ids must NOT be the same
assertNotEquals(clusterId1, otherClusterId);
}
if (instances.length>2) {
final VirtualInstance[] subset = new VirtualInstance[instances.length-1];
System.arraycopy(instances, 0, subset, 1, instances.length-1);
assertNotSameClusterIds(subset);
}
}
private void assertSameClusterIds(VirtualInstance... instances) throws UndefinedClusterViewException {
if (instances==null) {
// then there is nothing to compare
return;
}
if (instances.length==1) {
// then there is nothing to compare
return;
}
final String clusterId1 = instances[0].getClusterViewService()
.getLocalClusterView().getId();
for(int i=1; i<instances.length; i++) {
final String otherClusterId = instances[i].getClusterViewService()
.getLocalClusterView().getId();
// cluster ids must be the same
if (!clusterId1.equals(otherClusterId)) {
logger.error("assertSameClusterIds: instances[0]: "+instances[0]);
logger.error("assertSameClusterIds: instances["+i+"]: "+instances[i]);
fail("mismatch in clusterIds: expected to equal: clusterId1="+clusterId1+", otherClusterId="+otherClusterId);
}
}
}
private void assertTopology(VirtualInstance instance, SimpleClusterView... assertedClusterViews) {
final TopologyView topology = instance.getDiscoveryService().getTopology();
logger.info("assertTopology: instance "+instance.slingId+" sees topology: "+topology+", expected: "+assertedClusterViews);
assertNotNull(topology);
if (assertedClusterViews.length!=topology.getClusterViews().size()) {
dumpFailureDetails(topology, assertedClusterViews);
fail("instance "+instance.slingId+ " expected "+assertedClusterViews.length+", got: "+topology.getClusterViews().size());
}
final Set<ClusterView> actualClusters = new HashSet<ClusterView>(topology.getClusterViews());
for(int i=0; i<assertedClusterViews.length; i++) {
final SimpleClusterView assertedClusterView = assertedClusterViews[i];
boolean foundMatch = false;
for (Iterator<ClusterView> it = actualClusters.iterator(); it
.hasNext();) {
final ClusterView actualClusterView = it.next();
if (matches(assertedClusterView, actualClusterView)) {
it.remove();
foundMatch = true;
break;
}
}
if (!foundMatch) {
dumpFailureDetails(topology, assertedClusterViews);
fail("instance "+instance.slingId+ " could not find a match in the topology with instance="+instance.slingId+" and clusterViews="+assertedClusterViews.length);
}
}
assertEquals("not all asserted clusterviews are in the actual view with instance="+instance+" and clusterViews="+assertedClusterViews, actualClusters.size(), 0);
}
private void dumpFailureDetails(TopologyView topology, SimpleClusterView... assertedClusterViews) {
logger.error("assertTopology: expected: "+assertedClusterViews.length);
for(int j=0; j<assertedClusterViews.length; j++) {
logger.error("assertTopology: ["+j+"]: "+assertedClusterViews[j].toString());
}
final Set<ClusterView> clusterViews = topology.getClusterViews();
final Set<InstanceDescription> instances = topology.getInstances();
logger.error("assertTopology: actual: "+clusterViews.size()+" clusters with a total of "+instances.size()+" instances");
for (Iterator<ClusterView> it = clusterViews.iterator(); it.hasNext();) {
final ClusterView aCluster = it.next();
logger.error("assertTopology: a cluster: "+aCluster.getId());
for (Iterator<InstanceDescription> it2 = aCluster.getInstances().iterator(); it2.hasNext();) {
final InstanceDescription id = it2.next();
logger.error("assertTopology: - an instance "+id.getSlingId());
}
}
logger.error("assertTopology: list of all instances: "+instances.size());
for (Iterator<InstanceDescription> it = instances.iterator(); it.hasNext();) {
final InstanceDescription id = it.next();
logger.error("assertTopology: - an instance: "+id.getSlingId());
}
}
private boolean matches(SimpleClusterView assertedClusterView,
ClusterView actualClusterView) {
assertNotNull(assertedClusterView);
assertNotNull(actualClusterView);
if (assertedClusterView.instances.length!=actualClusterView.getInstances().size()) {
return false;
}
final Set<InstanceDescription> actualInstances = new HashSet<InstanceDescription>(actualClusterView.getInstances());
outerLoop:for(int i=0; i<assertedClusterView.instances.length; i++) {
final VirtualInstance assertedInstance = assertedClusterView.instances[i];
for (Iterator<InstanceDescription> it = actualInstances.iterator(); it
.hasNext();) {
final InstanceDescription anActualInstance = it.next();
if (assertedInstance.slingId.equals(anActualInstance.getSlingId())) {
continue outerLoop;
}
}
return false;
}
return true;
}
private boolean pingConnector(final VirtualInstance from, final VirtualInstance to) throws UndefinedClusterViewException {
final Announcement fromAnnouncement = createFromAnnouncement(from);
Announcement replyAnnouncement = null;
try{
replyAnnouncement = ping(to, fromAnnouncement);
} catch(AssertionError e) {
logger.warn("pingConnector: ping failed, assertionError: "+e);
return false;
} catch (UndefinedClusterViewException e) {
logger.warn("pingConnector: ping failed, currently the cluster view is undefined: "+e);
return false;
}
registerReplyAnnouncement(from, replyAnnouncement);
return true;
}
private void registerReplyAnnouncement(VirtualInstance from,
Announcement inheritedAnnouncement) {
final AnnouncementRegistry announcementRegistry = from.getAnnouncementRegistry();
if (inheritedAnnouncement.isLoop()) {
fail("loop detected");
// we dont currently support loops here in the junit tests
return;
} else {
inheritedAnnouncement.setInherited(true);
if (announcementRegistry
.registerAnnouncement(inheritedAnnouncement)==-1) {
logger.info("ping: connector response is from an instance which I already see in my topology"
+ inheritedAnnouncement);
return;
}
}
// resultingAnnouncement = inheritedAnnouncement;
// statusDetails = null;
}
private Announcement ping(VirtualInstance to, final Announcement incomingTopologyAnnouncement)
throws UndefinedClusterViewException {
final String slingId = to.slingId;
final ClusterViewService clusterViewService = to.getClusterViewService();
final AnnouncementRegistry announcementRegistry = to.getAnnouncementRegistry();
incomingTopologyAnnouncement.removeInherited(slingId);
final Announcement replyAnnouncement = new Announcement(
slingId);
long backoffInterval = -1;
final ClusterView clusterView = clusterViewService.getLocalClusterView();
if (!incomingTopologyAnnouncement.isCorrectVersion()) {
fail("incorrect version");
return null; // never reached
} else if (ClusterViewHelper.contains(clusterView, incomingTopologyAnnouncement
.getOwnerId())) {
fail("loop=true");
return null; // never reached
} else if (ClusterViewHelper.containsAny(clusterView, incomingTopologyAnnouncement
.listInstances())) {
fail("incoming announcement contains instances that are part of my cluster");
return null; // never reached
} else {
backoffInterval = announcementRegistry
.registerAnnouncement(incomingTopologyAnnouncement);
if (backoffInterval==-1) {
fail("rejecting an announcement from an instance that I already see in my topology: ");
return null; // never reached
} else {
// normal, successful case: replying with the part of the topology which this instance sees
replyAnnouncement.setLocalCluster(clusterView);
announcementRegistry.addAllExcept(replyAnnouncement, clusterView,
new AnnouncementFilter() {
public boolean accept(final String receivingSlingId, Announcement announcement) {
if (announcement.getPrimaryKey().equals(
incomingTopologyAnnouncement
.getPrimaryKey())) {
return false;
}
return true;
}
});
return replyAnnouncement;
}
}
}
private Announcement createFromAnnouncement(final VirtualInstance from) throws UndefinedClusterViewException {
// TODO: refactor TopologyConnectorClient to avoid duplicating code from there (ping())
Announcement topologyAnnouncement = new Announcement(from.slingId);
topologyAnnouncement.setServerInfo(from.slingId);
final ClusterView clusterView = from.getClusterViewService().getLocalClusterView();
topologyAnnouncement.setLocalCluster(clusterView);
from.getAnnouncementRegistry().addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {
public boolean accept(final String receivingSlingId, final Announcement announcement) {
// filter out announcements that are of old cluster instances
// which I dont really have in my cluster view at the moment
final Iterator<InstanceDescription> it =
clusterView.getInstances().iterator();
while(it.hasNext()) {
final InstanceDescription instance = it.next();
if (instance.getSlingId().equals(receivingSlingId)) {
// then I have the receiving instance in my cluster view
// all fine then
return true;
}
}
// looks like I dont have the receiving instance in my cluster view
// then I should also not propagate that announcement anywhere
return false;
}
});
return topologyAnnouncement;
}
@Test
public void testStableClusterId() throws Throwable {
logger.info("testStableClusterId: start");
// stop 1 and 2 and create them with a lower heartbeat timeout
instance2.stopViewChecker();
instance1.stopViewChecker();
instance2.stop();
instance1.stop();
// SLING-4302 : first set the heartbeatTimeout to 100 sec - large enough to work on all CI instances
instance1 = newBuilder().setDebugName("firstInstance")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(100)
.setMinEventDelay(1).build();
instance2 = newBuilder().setDebugName("secondInstance")
.useRepositoryOf(instance1)
.setConnectorPingTimeout(100)
.setMinEventDelay(1).build();
assertNotNull(instance1);
assertNotNull(instance2);
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// let the sync/voting happen
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
String newClusterId1 = instance1.getClusterViewService()
.getLocalClusterView().getId();
String newClusterId2 = instance2.getClusterViewService()
.getLocalClusterView().getId();
// both cluster ids must be the same
assertEquals(newClusterId1, newClusterId1);
instance1.dumpRepo();
assertEquals(2, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView().getInstances().size());
// let instance2 'die' by now longer doing heartbeats
// SLING-4302 : then set the heartbeatTimeouts back to 1 sec to have them properly time out with the sleeps applied below
instance2.getConfig().setViewCheckTimeout(1);
instance1.getConfig().setViewCheckTimeout(1);
instance2.stopViewChecker(); // would actually not be necessary as it was never started.. this test only runs heartbeats manually
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
// the cluster should now have size 1
assertEquals(1, instance1.getClusterViewService().getLocalClusterView().getInstances().size());
// the instance 2 should be in isolated mode as it is no longer in the established view
// hence null
try{
instance2.getViewChecker().checkView();
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
// but the cluster id must have remained stable
instance1.dumpRepo();
String actualClusterId = instance1.getClusterViewService()
.getLocalClusterView().getId();
logger.info("expected cluster id: "+newClusterId1);
logger.info("actual cluster id: "+actualClusterId);
assertEquals(newClusterId1, actualClusterId);
logger.info("testStableClusterId: end");
}
@Test
public void testClusterView() throws Exception {
logger.info("testClusterView: start");
assertNotNull(instance1);
assertNotNull(instance2);
assertNull(instance3);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
assertNotNull(instance3);
assertEquals(instance1.getSlingId(), instance1.getClusterViewService()
.getSlingId());
assertEquals(instance2.getSlingId(), instance2.getClusterViewService()
.getSlingId());
assertEquals(instance3.getSlingId(), instance3.getClusterViewService()
.getSlingId());
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance3.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
instance1.dumpRepo();
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
instance1.dumpRepo();
logger.info("testClusterView: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testClusterView: 2nd 2s sleep");
Thread.sleep(2000);
instance1.dumpRepo();
String clusterId1 = instance1.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId1=" + clusterId1);
String clusterId2 = instance2.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId2=" + clusterId2);
String clusterId3 = instance3.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId3=" + clusterId3);
assertEquals(clusterId1, clusterId2);
assertEquals(clusterId1, clusterId3);
assertEquals(3, instance1.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(3, instance2.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(3, instance3.getClusterViewService().getLocalClusterView()
.getInstances().size());
logger.info("testClusterView: end");
}
@Test
public void testAdditionalInstance() throws Throwable {
logger.info("testAdditionalInstance: start");
assertNotNull(instance1);
assertNotNull(instance2);
assertEquals(instance1.getSlingId(), instance1.getClusterViewService()
.getSlingId());
assertEquals(instance2.getSlingId(), instance2.getClusterViewService()
.getSlingId());
try{
instance1.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
try{
instance2.getClusterViewService().getLocalClusterView();
fail("should complain");
} catch(UndefinedClusterViewException e) {
// ok
}
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance1.dumpRepo();
logger.info("testAdditionalInstance: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 2nd 2s sleep");
Thread.sleep(2000);
instance1.dumpRepo();
String clusterId1 = instance1.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId1=" + clusterId1);
String clusterId2 = instance2.getClusterViewService().getLocalClusterView()
.getId();
logger.info("clusterId2=" + clusterId2);
assertEquals(clusterId1, clusterId2);
assertEquals(2, instance1.getClusterViewService().getLocalClusterView()
.getInstances().size());
assertEquals(2, instance2.getClusterViewService().getLocalClusterView()
.getInstances().size());
AssertingTopologyEventListener assertingTopologyEventListener = new AssertingTopologyEventListener();
assertingTopologyEventListener.addExpected(Type.TOPOLOGY_INIT);
assertEquals(1, assertingTopologyEventListener.getRemainingExpectedCount());
instance1.bindTopologyEventListener(assertingTopologyEventListener);
Thread.sleep(500); // SLING-4755: async event sending requires some minimal wait time nowadays
assertEquals(0, assertingTopologyEventListener.getRemainingExpectedCount());
// startup instance 3
AcceptsMultiple acceptsMultiple = new AcceptsMultiple(
Type.TOPOLOGY_CHANGING, Type.TOPOLOGY_CHANGED);
assertingTopologyEventListener.addExpected(acceptsMultiple);
assertingTopologyEventListener.addExpected(acceptsMultiple);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 3rd 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testAdditionalInstance: 4th 2s sleep");
Thread.sleep(2000);
assertEquals(1, acceptsMultiple.getEventCnt(Type.TOPOLOGY_CHANGING));
assertEquals(1, acceptsMultiple.getEventCnt(Type.TOPOLOGY_CHANGED));
logger.info("testAdditionalInstance: end");
}
@Test
public void testPropertyProviders() throws Throwable {
logger.info("testPropertyProviders: start");
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
assertNull(instance3);
instance3 = newBuilder().setDebugName("thirdInstance")
.useRepositoryOf(instance1)
.build();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 1st 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 2nd 2s sleep");
Thread.sleep(2000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
logger.info("testPropertyProviders: 3rd 2s sleep");
Thread.sleep(2000);
property1Value = UUID.randomUUID().toString();
property1Name = UUID.randomUUID().toString();
PropertyProviderImpl pp1 = new PropertyProviderImpl();
pp1.setProperty(property1Name, property1Value);
instance1.bindPropertyProvider(pp1, property1Name);
property2Value = UUID.randomUUID().toString();
property2Name = UUID.randomUUID().toString();
PropertyProviderImpl pp2 = new PropertyProviderImpl();
pp2.setProperty(property2Name, property2Value);
instance2.bindPropertyProvider(pp2, property2Name);
assertPropertyValues();
property1Value = UUID.randomUUID().toString();
pp1.setProperty(property1Name, property1Value);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
assertPropertyValues();
assertNull(instance1.getClusterViewService().getLocalClusterView()
.getInstances().get(0)
.getProperty(UUID.randomUUID().toString()));
assertNull(instance2.getClusterViewService().getLocalClusterView()
.getInstances().get(0)
.getProperty(UUID.randomUUID().toString()));
logger.info("testPropertyProviders: end");
}
private void assertPropertyValues() throws UndefinedClusterViewException {
assertPropertyValues(instance1.getSlingId(), property1Name,
property1Value);
assertPropertyValues(instance2.getSlingId(), property2Name,
property2Value);
}
private void assertPropertyValues(String slingId, String name, String value) throws UndefinedClusterViewException {
assertEquals(value, getInstance(instance1, slingId).getProperty(name));
assertEquals(value, getInstance(instance2, slingId).getProperty(name));
}
private InstanceDescription getInstance(VirtualInstance instance, String slingId) throws UndefinedClusterViewException {
Iterator<InstanceDescription> it = instance.getClusterViewService()
.getLocalClusterView().getInstances().iterator();
while (it.hasNext()) {
InstanceDescription id = it.next();
if (id.getSlingId().equals(slingId)) {
return id;
}
}
throw new IllegalStateException("instance not found: instance="
+ instance + ", slingId=" + slingId);
}
class LongRunningListener implements TopologyEventListener {
String failMsg = null;
boolean initReceived = false;
int noninitReceived;
private Semaphore changedSemaphore = new Semaphore(0);
public void assertNoFail() {
if (failMsg!=null) {
fail(failMsg);
}
}
public Semaphore getChangedSemaphore() {
return changedSemaphore;
}
public void handleTopologyEvent(TopologyEvent event) {
if (failMsg!=null) {
failMsg += "/ Already failed, got another event; "+event;
return;
}
if (!initReceived) {
if (event.getType()!=Type.TOPOLOGY_INIT) {
failMsg = "Expected TOPOLOGY_INIT first, got: "+event.getType();
return;
}
initReceived = true;
return;
}
if (event.getType()==Type.TOPOLOGY_CHANGED) {
try {
changedSemaphore.acquire();
} catch (InterruptedException e) {
throw new Error("don't interrupt me pls: "+e);
}
}
noninitReceived++;
}
}
/**
* Test plan:
* * have a discoveryservice with two listeners registered
* * one of them (the 'first' one) is long running
* * during one of the topology changes, when the first
* one is hit, deactivate the discovery service
* * that deactivation used to block (SLING-4755) due
* to synchronized(lock) which was blocked by the
* long running listener. With having asynchronous
* event sending this should no longer be the case
* * also, once asserted that deactivation finished,
* and that the first listener is still busy, make
* sure that once the first listener finishes, that
* the second listener still gets the event
* @throws Throwable
*/
@Test
public void testLongRunningListener() throws Throwable {
// let the instance1 become alone, instance2 is idle
instance1.getConfig().setViewCheckTimeout(2);
instance2.getConfig().setViewCheckTimeout(2);
logger.info("testLongRunningListener : letting instance2 remain silent from now on");
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
Thread.sleep(1500);
instance1.heartbeatsAndCheckView();
logger.info("testLongRunningListener : instance 2 should now be considered dead");
// instance1.dumpRepo();
LongRunningListener longRunningListener1 = new LongRunningListener();
AssertingTopologyEventListener fastListener2 = new AssertingTopologyEventListener();
fastListener2.addExpected(Type.TOPOLOGY_INIT);
longRunningListener1.assertNoFail();
assertEquals(1, fastListener2.getRemainingExpectedCount());
logger.info("testLongRunningListener : binding longRunningListener1 ...");
instance1.bindTopologyEventListener(longRunningListener1);
logger.info("testLongRunningListener : binding fastListener2 ...");
instance1.bindTopologyEventListener(fastListener2);
logger.info("testLongRunningListener : waiting a bit for longRunningListener1 to receive the TOPOLOGY_INIT event");
Thread.sleep(2500); // SLING-4755: async event sending requires some minimal wait time nowadays
assertEquals(0, fastListener2.getRemainingExpectedCount());
assertTrue(longRunningListener1.initReceived);
// after INIT, now do an actual change where listener1 will do a long-running handling
fastListener2.addExpected(Type.TOPOLOGY_CHANGING);
fastListener2.addExpected(Type.TOPOLOGY_CHANGED);
instance1.getConfig().setViewCheckTimeout(10);
instance2.getConfig().setViewCheckTimeout(10);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(500);
instance1.dumpRepo();
longRunningListener1.assertNoFail();
// nothing unexpected should arrive at listener2:
assertEquals(0, fastListener2.getUnexpectedCount());
// however, listener2 should only get one (CHANGING) event, cos the CHANGED event is still blocked
assertEquals(1, fastListener2.getRemainingExpectedCount());
// and also listener2 should only get CHANGING, the CHANGED is blocked via changedSemaphore
assertEquals(1, longRunningListener1.noninitReceived);
assertTrue(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
Thread.sleep(2000);
// even after a 2sec sleep things should be unchanged:
assertEquals(0, fastListener2.getUnexpectedCount());
assertEquals(1, fastListener2.getRemainingExpectedCount());
assertEquals(1, longRunningListener1.noninitReceived);
assertTrue(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
// now let's simulate SLING-4755: deactivation while longRunningListener1 does long processing
// - which is simulated by waiting on changedSemaphore.
final List<Exception> asyncException = new LinkedList<Exception>();
Thread th = new Thread(new Runnable() {
public void run() {
try {
instance1.stop();
} catch (Exception e) {
synchronized(asyncException) {
asyncException.add(e);
}
}
}
});
th.start();
logger.info("Waiting max 4 sec...");
th.join(4000);
logger.info("Done waiting max 4 sec...");
if (th.isAlive()) {
logger.warn("Thread still alive: "+th.isAlive());
// release before issuing fail as otherwise test will block forever
longRunningListener1.getChangedSemaphore().release();
fail("Thread was still alive");
}
logger.info("Thread was no longer alive: "+th.isAlive());
synchronized(asyncException) {
logger.info("Async exceptions: "+asyncException.size());
if (asyncException.size()!=0) {
// release before issuing fail as otherwise test will block forever
longRunningListener1.getChangedSemaphore().release();
fail("async exceptions: "+asyncException.size()+", first: "+asyncException.get(0));
}
}
// now the test consists of
// a) the fact that we reached this place without unlocking the changedSemaphore
// b) when we now unlock the changedSemaphore the remaining events should flush through
longRunningListener1.getChangedSemaphore().release();
Thread.sleep(500);// shouldn't take long and then things should have flushed:
assertEquals(0, fastListener2.getUnexpectedCount());
assertEquals(0, fastListener2.getRemainingExpectedCount());
assertEquals(2, longRunningListener1.noninitReceived);
assertFalse(longRunningListener1.getChangedSemaphore().hasQueuedThreads());
}
}
| SLING-5126 / SLING-5195 related: fixing a test
git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1711275 13f79535-47bb-0310-9956-ffa450edef68
| bundles/extensions/discovery/base/src/test/java/org/apache/sling/discovery/base/its/AbstractClusterTest.java | SLING-5126 / SLING-5195 related: fixing a test |
|
Java | apache-2.0 | f4ffbde52bef52fb34451c33ea35924028243b8c | 0 | AndiHappy/solo,xiongba-me/solo,xiongba-me/solo,b3log/b3log-solo,xiongba-me/solo,meikaiyipian/solo,AndiHappy/solo,meikaiyipian/solo,b3log/b3log-solo,AndiHappy/solo,meikaiyipian/solo,b3log/b3log-solo,xiongba-me/solo | /*
* Copyright (c) 2010-2017, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.processor;
import freemarker.template.Template;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.freemarker.Templates;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Comment;
import org.b3log.solo.model.Common;
import org.b3log.solo.model.Page;
import org.b3log.solo.service.CommentMgmtService;
import org.b3log.solo.service.UserMgmtService;
import org.b3log.solo.service.UserQueryService;
import org.json.JSONObject;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Comment processor.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author ArmstrongCN
* @version 1.3.2.12, Feb 17, 2017
* @since 0.3.1
*/
@RequestProcessor
public class CommentProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(CommentProcessor.class.getName());
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Comment management service.
*/
@Inject
private CommentMgmtService commentMgmtService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* User management service.
*/
@Inject
private UserMgmtService userMgmtService;
/**
* Adds a comment to a page.
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_PAGE_SUCC"
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "" // if exists this key, the comment is an reply
* }
* </pre>
* </p>
*
* @param context the specified context, including a request json object, for example,
* "captcha": "",
* "oId": pageId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "", // HTML
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-page-comment.do", method = HTTPRequestMethod.POST)
public void addPageComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Page.PAGE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addPageComment(requestJSONObject);
final Map<String, Object> dataModel = new HashMap<>();
dataModel.put(Comment.COMMENT, addResult);
final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
final Template template = Templates.MAIN_CFG.getTemplate("common-comment.ftl");
final StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
stringWriter.close();
addResult.put("cmtTpl", stringWriter.toString());
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on page", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
/**
* Adds a comment to an article.
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_ARTICLE_SUCC",
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "", // if exists this key, the comment is an reply
* "commentContent": "" // HTML
* }
* </pre>
* </p>
*
* @param context the specified context, including a request json object, for example,
* "captcha": "",
* "oId": articleId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "",
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-article-comment.do", method = HTTPRequestMethod.POST)
public void addArticleComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Article.ARTICLE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addArticleComment(requestJSONObject);
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on article", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
/**
* Fills commenter info if logged in.
*
* @param requestJSONObject the specified request json object
* @param httpServletRequest the specified HTTP servlet request
* @param httpServletResponse the specified HTTP servlet response
*/
private void fillCommenter(final JSONObject requestJSONObject,
final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {
userMgmtService.tryLogInWithCookie(httpServletRequest, httpServletResponse);
final JSONObject currentUser = userQueryService.getCurrentUser(httpServletRequest);
if (null == currentUser) {
return;
}
requestJSONObject.put(Comment.COMMENT_NAME, currentUser.optString(User.USER_NAME));
requestJSONObject.put(Comment.COMMENT_EMAIL, currentUser.optString(User.USER_EMAIL));
requestJSONObject.put(Comment.COMMENT_URL, currentUser.optString(User.USER_URL));
}
}
| src/main/java/org/b3log/solo/processor/CommentProcessor.java | /*
* Copyright (c) 2010-2017, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.processor;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.util.Requests;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Comment;
import org.b3log.solo.model.Common;
import org.b3log.solo.model.Page;
import org.b3log.solo.service.CommentMgmtService;
import org.b3log.solo.service.UserMgmtService;
import org.b3log.solo.service.UserQueryService;
import org.json.JSONObject;
/**
* Comment processor.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author ArmstrongCN
* @version 1.2.2.12, Dec 29, 2015
* @since 0.3.1
*/
@RequestProcessor
public class CommentProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(CommentProcessor.class.getName());
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Comment management service.
*/
@Inject
private CommentMgmtService commentMgmtService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* User management service.
*/
@Inject
private UserMgmtService userMgmtService;
/**
* Adds a comment to a page.
*
* <p> Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_PAGE_SUCC"
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "" // if exists this key, the comment is an reply
* }
* </pre> </p>
*
* @param context the specified context, including a request json object, for example,
* <pre>
* {
* "captcha": "",
* "oId": pageId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "", // HTML
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* }
* </pre>
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-page-comment.do", method = HTTPRequestMethod.POST)
public void addPageComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Page.PAGE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addPageComment(requestJSONObject);
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on page", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
/**
* Adds a comment to an article.
*
*
* <p> Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_ARTICLE_SUCC",
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "", // if exists this key, the comment is an reply
* "commentContent": "" // HTML
* }
* </pre>
*
* @param context the specified context, including a request json object, for example,
* <pre>
* {
* "captcha": "",
* "oId": articleId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "",
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* }
* </pre>
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-article-comment.do", method = HTTPRequestMethod.POST)
public void addArticleComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Article.ARTICLE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addArticleComment(requestJSONObject);
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on article", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
/**
* Fills commenter info if logged in.
*
* @param requestJSONObject the specified request json object
* @param httpServletRequest the specified HTTP servlet request
* @param httpServletResponse the specified HTTP servlet response
*/
private void fillCommenter(final JSONObject requestJSONObject,
final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {
userMgmtService.tryLogInWithCookie(httpServletRequest, httpServletResponse);
final JSONObject currentUser = userQueryService.getCurrentUser(httpServletRequest);
if (null == currentUser) {
return;
}
requestJSONObject.put(Comment.COMMENT_NAME, currentUser.optString(User.USER_NAME));
requestJSONObject.put(Comment.COMMENT_EMAIL, currentUser.optString(User.USER_EMAIL));
requestJSONObject.put(Comment.COMMENT_URL, currentUser.optString(User.USER_URL));
}
}
| :hammer: #12246
| src/main/java/org/b3log/solo/processor/CommentProcessor.java | :hammer: #12246 |
|
Java | apache-2.0 | 2d7574dd60fa67cc77fef0ef4b17cffcee904b14 | 0 | nutzam/nutz,ywjno/nutz,nutzam/nutz,nutzam/nutz,elkan1788/nutz,happyday517/nutz,ansjsun/nutz,ansjsun/nutz,nutzam/nutz,ansjsun/nutz,happyday517/nutz,elkan1788/nutz,happyday517/nutz,ywjno/nutz,ansjsun/nutz,ansjsun/nutz,elkan1788/nutz,happyday517/nutz,ywjno/nutz,ywjno/nutz,ywjno/nutz,elkan1788/nutz,nutzam/nutz | package org.nutz.dao.test.normal;
import static org.junit.Assert.*;
import org.junit.Test;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.test.DaoCase;
import org.nutz.dao.test.meta.BeanWithDefault;
import org.nutz.dao.test.meta.Fighter;
import org.nutz.dao.test.meta.Pet;
import org.nutz.dao.test.meta.Platoon;
import org.nutz.lang.Lang;
import org.nutz.trans.Atom;
public class UpdateTest extends DaoCase {
/**
* For issue #557
*/
@Test
public void test_update_ignore_null() {
dao.create(Pet.class, true);
final Pet pet = Pet.create("XiaoBai").setAge(20);
dao.insert(pet);
FieldFilter.create(Pet.class, true).run(new Atom() {
public void run() {
Pet p1 = new Pet().setAge(12).setId(pet.getId());
dao.update(p1);
}
});
Pet p2 = dao.fetch(Pet.class, pet.getId());
assertEquals("XiaoBai", p2.getName());
}
/**
* For issue #84
*/
@Test
public void test_updateIgnoreNull_width_default() {
dao.create(BeanWithDefault.class, true);
BeanWithDefault bean = new BeanWithDefault();
bean.setName("abc");
dao.insert(bean);
BeanWithDefault b2 = dao.fetch(BeanWithDefault.class);
assertEquals("--", b2.getAlias());
b2.setAlias("AAA");
dao.update(b2);
b2 = dao.fetch(BeanWithDefault.class, "abc");
assertEquals("AAA", b2.getAlias());
b2.setAlias(null);
dao.updateIgnoreNull(b2);
b2 = dao.fetch(BeanWithDefault.class, "abc");
assertEquals("AAA", b2.getAlias());
}
@Test
public void test_update_chain_and_cnd_by_in() {
dao.create(Pet.class, true);
Pet pet = Pet.create("xb");
pet.setNickName("XB");
dao.insert(pet);
dao.update(Pet.class,
Chain.make("name", "xiaobai"),
Cnd.where("nickName", "in", Lang.array("XB")));
pet = dao.fetch(Pet.class, "xiaobai");
assertEquals("XB", pet.getNickName());
}
@Test
public void test_update_chain_and_cnd() {
dao.create(Pet.class, true);
Pet pet = Pet.create("xb");
pet.setNickName("XB");
dao.insert(pet);
dao.update(Pet.class,
Chain.make("name", "xiaobai"),
Cnd.where("nickName", "=", "XB"));
pet = dao.fetch(Pet.class, "xiaobai");
assertEquals("XB", pet.getNickName());
}
@Test
public void batch_update_all() {
pojos.initData();
dao.update(Fighter.class,
Chain.make("type", Fighter.TYPE.SU_35.name()),
null);
assertEquals(13,
dao.count(Fighter.class,
Cnd.where("type", "=", Fighter.TYPE.SU_35.name())));
}
@Test
public void batch_update_partly() {
pojos.initData();
int re = dao.update(Fighter.class,
Chain.make("type", "F15"),
Cnd.where("type", "=", "SU_35"));
assertEquals(1, re);
int maxId = dao.getMaxId(Fighter.class);
re = dao.update(Fighter.class,
Chain.make("type", "UFO"),
Cnd.where("id", ">", maxId - 5));
assertEquals(5, re);
assertEquals(re,
dao.count(Fighter.class, Cnd.where("type", "=", "UFO")));
}
@Test
public void batch_update_relation() {
pojos.initData();
dao.updateRelation(Fighter.class,
"base",
Chain.make("bname", "blue"),
Cnd.where("bname", "=", "red"));
assertEquals(13,
dao.count("dao_m_base_fighter",
Cnd.where("bname", "=", "blue")));
}
@Test
public void fetch_by_name_ignorecase() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
assertEquals("SF", p.getName());
}
@Test
public void test_update_obj_with_readonly_field() {
dao.create(Plant.class, true);
Plant p = new Plant();
p.setNumber(100);
p.setColor("red");
p.setName("Rose");
dao.insert(p);
p = dao.fetch(Plant.class, "Rose");
assertNull(p.getColor());
assertEquals(100, p.getNumber());
p.setColor("black");
p.setNumber(88);
dao.update(p);
p = dao.fetch(Plant.class, "Rose");
assertNull(p.getColor());
assertEquals(88, p.getNumber());
}
@Test
public void update_with_null_links() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.updateWith(p, null);
p = dao.fetch(Platoon.class, "sF");
assertEquals("xyz", p.getLeaderName());
}
@Test
public void test_updateIgnoreNull() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
String name = p.getLeaderName(); // xyz
assertNotNull(name);
p.setLeaderName(null);
int re = dao.updateIgnoreNull(p);
assertEquals(1, re);
p = dao.fetch(Platoon.class, "sF");
assertEquals(name, p.getLeaderName());
p.setLeaderName(null);
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertNull(p.getLeaderName());
p.setLeaderName("ABC");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertEquals("ABC", p.getLeaderName());
FieldFilter.create(Platoon.class, true).run(new Atom() {
public void run() {
System.out.println(FieldFilter.get(Platoon.class));
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName(null);
dao.update(p);
}
});
p = dao.fetch(Platoon.class, "sF");
assertEquals("ABC", p.getLeaderName());
}
@Test
public void test_updateIgnoreNull_by_list() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
String name = p.getLeaderName(); // xyz
assertNotNull(name);
p.setLeaderName(null);
int re = dao.updateIgnoreNull(Lang.list(p));
assertEquals(1, re);
p = dao.fetch(Platoon.class, "sF");
assertEquals(name, p.getLeaderName());
p.setLeaderName(null);
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertNull(p.getLeaderName());
}
@Test
public void test_update_self_plus() {
dao.create(Pet.class, true);
Pet pet = Pet.create("Xy");
pet.setAge(98);
dao.insert(pet);
pet = dao.fetch(Pet.class, (Cnd) null);
dao.update(Pet.class, Chain.makeSpecial("age", "+1"), null);
assertEquals(pet.getAge() + 1, dao.fetch(Pet.class, pet.getId())
.getAge());
}
@Test
public void test_update_with_pk_and_cnd() {
dao.create(Pet.class, true);
Pet pet = Pet.create("wendal");
pet.setAge(30);
dao.insert(pet);
pet = dao.fetch(Pet.class, "wendal");
pet.setAge(31);
// 第一次更新, age符合要求
dao.update(pet, FieldFilter.create(Pet.class, "age"), Cnd.where("age", "=", 30));
// 第二次更新, age不符合要求
pet.setAge(90);
dao.update(pet, FieldFilter.create(Pet.class, "age"), Cnd.where("age", "=", 30));
assertEquals(31, dao.fetch(Pet.class, "wendal").getAge());
}
@Test
public void test_update_with_age_incr() {
dao.create(Pet.class, true);
Pet pet = Pet.create("wendal");
pet.setAge(30);
dao.insert(pet);
final Pet pet2 = dao.fetch(Pet.class, "wendal");
FieldFilter.create(Pet.class, true).run(new Atom() {
public void run() {
// 应该只有第一次生效
dao.updateAndIncrIfMatch(pet2, null, "age");
dao.updateAndIncrIfMatch(pet2, null, "age");
dao.updateAndIncrIfMatch(pet2, null, "age");
dao.updateAndIncrIfMatch(pet2, null, "age");
dao.updateAndIncrIfMatch(pet2, null, "age");
dao.updateAndIncrIfMatch(pet2, null, "age");
assertEquals(31, dao.fetch(Pet.class, "wendal").getAge());
}
});
}
}
| test/org/nutz/dao/test/normal/UpdateTest.java | package org.nutz.dao.test.normal;
import static org.junit.Assert.*;
import org.junit.Test;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.test.DaoCase;
import org.nutz.dao.test.meta.BeanWithDefault;
import org.nutz.dao.test.meta.Fighter;
import org.nutz.dao.test.meta.Pet;
import org.nutz.dao.test.meta.Platoon;
import org.nutz.lang.Lang;
import org.nutz.trans.Atom;
public class UpdateTest extends DaoCase {
/**
* For issue #557
*/
@Test
public void test_update_ignore_null() {
dao.create(Pet.class, true);
final Pet pet = Pet.create("XiaoBai").setAge(20);
dao.insert(pet);
FieldFilter.create(Pet.class, true).run(new Atom() {
public void run() {
Pet p1 = new Pet().setAge(12).setId(pet.getId());
dao.update(p1);
}
});
Pet p2 = dao.fetch(Pet.class, pet.getId());
assertEquals("XiaoBai", p2.getName());
}
/**
* For issue #84
*/
@Test
public void test_updateIgnoreNull_width_default() {
dao.create(BeanWithDefault.class, true);
BeanWithDefault bean = new BeanWithDefault();
bean.setName("abc");
dao.insert(bean);
BeanWithDefault b2 = dao.fetch(BeanWithDefault.class);
assertEquals("--", b2.getAlias());
b2.setAlias("AAA");
dao.update(b2);
b2 = dao.fetch(BeanWithDefault.class, "abc");
assertEquals("AAA", b2.getAlias());
b2.setAlias(null);
dao.updateIgnoreNull(b2);
b2 = dao.fetch(BeanWithDefault.class, "abc");
assertEquals("AAA", b2.getAlias());
}
@Test
public void test_update_chain_and_cnd_by_in() {
dao.create(Pet.class, true);
Pet pet = Pet.create("xb");
pet.setNickName("XB");
dao.insert(pet);
dao.update(Pet.class,
Chain.make("name", "xiaobai"),
Cnd.where("nickName", "in", Lang.array("XB")));
pet = dao.fetch(Pet.class, "xiaobai");
assertEquals("XB", pet.getNickName());
}
@Test
public void test_update_chain_and_cnd() {
dao.create(Pet.class, true);
Pet pet = Pet.create("xb");
pet.setNickName("XB");
dao.insert(pet);
dao.update(Pet.class,
Chain.make("name", "xiaobai"),
Cnd.where("nickName", "=", "XB"));
pet = dao.fetch(Pet.class, "xiaobai");
assertEquals("XB", pet.getNickName());
}
@Test
public void batch_update_all() {
pojos.initData();
dao.update(Fighter.class,
Chain.make("type", Fighter.TYPE.SU_35.name()),
null);
assertEquals(13,
dao.count(Fighter.class,
Cnd.where("type", "=", Fighter.TYPE.SU_35.name())));
}
@Test
public void batch_update_partly() {
pojos.initData();
int re = dao.update(Fighter.class,
Chain.make("type", "F15"),
Cnd.where("type", "=", "SU_35"));
assertEquals(1, re);
int maxId = dao.getMaxId(Fighter.class);
re = dao.update(Fighter.class,
Chain.make("type", "UFO"),
Cnd.where("id", ">", maxId - 5));
assertEquals(5, re);
assertEquals(re,
dao.count(Fighter.class, Cnd.where("type", "=", "UFO")));
}
@Test
public void batch_update_relation() {
pojos.initData();
dao.updateRelation(Fighter.class,
"base",
Chain.make("bname", "blue"),
Cnd.where("bname", "=", "red"));
assertEquals(13,
dao.count("dao_m_base_fighter",
Cnd.where("bname", "=", "blue")));
}
@Test
public void fetch_by_name_ignorecase() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
assertEquals("SF", p.getName());
}
@Test
public void test_update_obj_with_readonly_field() {
dao.create(Plant.class, true);
Plant p = new Plant();
p.setNumber(100);
p.setColor("red");
p.setName("Rose");
dao.insert(p);
p = dao.fetch(Plant.class, "Rose");
assertNull(p.getColor());
assertEquals(100, p.getNumber());
p.setColor("black");
p.setNumber(88);
dao.update(p);
p = dao.fetch(Plant.class, "Rose");
assertNull(p.getColor());
assertEquals(88, p.getNumber());
}
@Test
public void update_with_null_links() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.updateWith(p, null);
p = dao.fetch(Platoon.class, "sF");
assertEquals("xyz", p.getLeaderName());
}
@Test
public void test_updateIgnoreNull() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
String name = p.getLeaderName(); // xyz
assertNotNull(name);
p.setLeaderName(null);
int re = dao.updateIgnoreNull(p);
assertEquals(1, re);
p = dao.fetch(Platoon.class, "sF");
assertEquals(name, p.getLeaderName());
p.setLeaderName(null);
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertNull(p.getLeaderName());
p.setLeaderName("ABC");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertEquals("ABC", p.getLeaderName());
FieldFilter.create(Platoon.class, true).run(new Atom() {
public void run() {
System.out.println(FieldFilter.get(Platoon.class));
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName(null);
dao.update(p);
}
});
p = dao.fetch(Platoon.class, "sF");
assertEquals("ABC", p.getLeaderName());
}
@Test
public void test_updateIgnoreNull_by_list() {
pojos.initData();
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
String name = p.getLeaderName(); // xyz
assertNotNull(name);
p.setLeaderName(null);
int re = dao.updateIgnoreNull(Lang.list(p));
assertEquals(1, re);
p = dao.fetch(Platoon.class, "sF");
assertEquals(name, p.getLeaderName());
p.setLeaderName(null);
dao.update(p);
p = dao.fetch(Platoon.class, "sF");
assertNull(p.getLeaderName());
}
@Test
public void test_update_self_plus() {
dao.create(Pet.class, true);
Pet pet = Pet.create("Xy");
pet.setAge(98);
dao.insert(pet);
pet = dao.fetch(Pet.class, (Cnd) null);
dao.update(Pet.class, Chain.makeSpecial("age", "+1"), null);
assertEquals(pet.getAge() + 1, dao.fetch(Pet.class, pet.getId())
.getAge());
}
@Test
public void test_update_with_pk_and_cnd() {
dao.create(Pet.class, true);
Pet pet = Pet.create("wendal");
pet.setAge(30);
dao.insert(pet);
pet = dao.fetch(Pet.class, "wendal");
pet.setAge(31);
// 第一次更新, age符合要求
dao.update(pet, FieldFilter.create(Pet.class, "age"), Cnd.where("age", "=", 30));
// 第二次更新, age不符合要求
pet.setAge(90);
dao.update(pet, FieldFilter.create(Pet.class, "age"), Cnd.where("age", "=", 30));
assertEquals(31, dao.fetch(Pet.class, "wendal").getAge());
}
@Test
public void test_update_with_age_incr() {
dao.create(Pet.class, true);
Pet pet = Pet.create("wendal");
pet.setAge(30);
dao.insert(pet);
pet = dao.fetch(Pet.class, "wendal");
// 应该只有第一次生效
dao.updateAndIncrIfMatch(pet, null, "age");
dao.updateAndIncrIfMatch(pet, null, "age");
dao.updateAndIncrIfMatch(pet, null, "age");
dao.updateAndIncrIfMatch(pet, null, "age");
dao.updateAndIncrIfMatch(pet, null, "age");
dao.updateAndIncrIfMatch(pet, null, "age");
assertEquals(31, dao.fetch(Pet.class, "wendal").getAge());
}
}
| update: 为毛CI报错呢?
| test/org/nutz/dao/test/normal/UpdateTest.java | update: 为毛CI报错呢? |
|
Java | apache-2.0 | 280c22f0fe92ea754cadbad77f27d04686138438 | 0 | vvv1559/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,asedunov/intellij-community,semonte/intellij-community,blademainer/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,kool79/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,apixandru/intellij-community,slisson/intellij-community,holmes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,caot/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,signed/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,slisson/intellij-community,fnouama/intellij-community,signed/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,caot/intellij-community,vvv1559/intellij-community,kool79/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,semonte/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,petteyg/intellij-community,samthor/intellij-community,supersven/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,slisson/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,supersven/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,samthor/intellij-community,dslomov/intellij-community,holmes/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,allotria/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,da1z/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,supersven/intellij-community,adedayo/intellij-community,allotria/intellij-community,izonder/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,blademainer/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,vladmm/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,slisson/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,supersven/intellij-community,FHannes/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,supersven/intellij-community,semonte/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ryano144/intellij-community,fitermay/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,vladmm/intellij-community,izonder/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,slisson/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,wreckJ/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,signed/intellij-community,apixandru/intellij-community,hurricup/intellij-community,allotria/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,adedayo/intellij-community,clumsy/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,caot/intellij-community,pwoodworth/intellij-community,signed/intellij-community,clumsy/intellij-community,jagguli/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,hurricup/intellij-community,clumsy/intellij-community,xfournet/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,FHannes/intellij-community,robovm/robovm-studio,caot/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,caot/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,diorcety/intellij-community,samthor/intellij-community,supersven/intellij-community,robovm/robovm-studio,FHannes/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,caot/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,signed/intellij-community,diorcety/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,hurricup/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,samthor/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,ibinti/intellij-community,blademainer/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,semonte/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,izonder/intellij-community,samthor/intellij-community,holmes/intellij-community,slisson/intellij-community,signed/intellij-community,retomerz/intellij-community,allotria/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,da1z/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,holmes/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,fnouama/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,semonte/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,jagguli/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,diorcety/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,robovm/robovm-studio,dslomov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,signed/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,youdonghai/intellij-community,izonder/intellij-community,fitermay/intellij-community,kool79/intellij-community,allotria/intellij-community,nicolargo/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,kool79/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ryano144/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,da1z/intellij-community,petteyg/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,xfournet/intellij-community,petteyg/intellij-community,clumsy/intellij-community,caot/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,FHannes/intellij-community,akosyakov/intellij-community,holmes/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,slisson/intellij-community,supersven/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,petteyg/intellij-community,jagguli/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,caot/intellij-community,semonte/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,kool79/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,asedunov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,semonte/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,caot/intellij-community,da1z/intellij-community,amith01994/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,kdwink/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,petteyg/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ibinti/intellij-community,supersven/intellij-community,retomerz/intellij-community,hurricup/intellij-community,diorcety/intellij-community,allotria/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,adedayo/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,Lekanich/intellij-community,kool79/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,semonte/intellij-community,amith01994/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,signed/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,slisson/intellij-community,fnouama/intellij-community,retomerz/intellij-community,retomerz/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,da1z/intellij-community,holmes/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,hurricup/intellij-community,izonder/intellij-community,asedunov/intellij-community | package com.jetbrains.python;
import com.intellij.lang.documentation.QuickDocumentationProvider;
import com.intellij.psi.PsiElement;
import com.intellij.xml.util.XmlStringUtil;
import com.jetbrains.python.psi.PyDocStringOwner;
/**
* @author yole
*/
public class PythonDocumentationProvider extends QuickDocumentationProvider {
public String getQuickNavigateInfo(final PsiElement element) {
return null;
}
public String generateDoc(final PsiElement element, final PsiElement originalElement) {
if (element instanceof PyDocStringOwner) {
String docString = ((PyDocStringOwner) element).getDocString();
return XmlStringUtil.escapeString(docString).replace("\n", "<br>");
}
return null;
}
}
| python/src/com/jetbrains/python/PythonDocumentationProvider.java | package com.jetbrains.python;
import com.intellij.lang.documentation.QuickDocumentationProvider;
import com.intellij.psi.PsiElement;
import com.intellij.xml.util.XmlStringUtil;
import com.jetbrains.python.psi.PyDocStringOwner;
/**
* @author yole
*/
public class PythonDocumentationProvider extends QuickDocumentationProvider {
public String getQuickNavigateInfo(final PsiElement element) {
return null;
}
public String generateDoc(final PsiElement element, final PsiElement originalElement) {
if (element instanceof PyDocStringOwner) {
String docString = ((PyDocStringOwner) element).getDocString();
return XmlStringUtil.escapeString(docString);
}
return null;
}
}
| It seems it makes more sense to keep original linebreaks when displaying python documentation.
| python/src/com/jetbrains/python/PythonDocumentationProvider.java | It seems it makes more sense to keep original linebreaks when displaying python documentation. |
|
Java | apache-2.0 | 31b96bd207421cd2a6fd4c05910c0ce24c2cc9b2 | 0 | AlexMinsk/camunda-bpm-platform,xasx/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,filiphr/camunda-bpm-platform,menski/camunda-bpm-platform,langfr/camunda-bpm-platform,xasx/camunda-bpm-platform,skjolber/camunda-bpm-platform,hupda-edpe/c,hawky-4s-/camunda-bpm-platform,fouasnon/camunda-bpm-platform,fouasnon/camunda-bpm-platform,plexiti/camunda-bpm-platform,skjolber/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,tcrossland/camunda-bpm-platform,nibin/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,filiphr/camunda-bpm-platform,joansmith/camunda-bpm-platform,tcrossland/camunda-bpm-platform,falko/camunda-bpm-platform,jangalinski/camunda-bpm-platform,camunda/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,bentrm/camunda-bpm-platform,camunda/camunda-bpm-platform,nibin/camunda-bpm-platform,falko/camunda-bpm-platform,Sumitdahiya/camunda,xasx/camunda-bpm-platform,skjolber/camunda-bpm-platform,filiphr/camunda-bpm-platform,holisticon/camunda-bpm-platform,menski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,hupda-edpe/c,1and1/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,joansmith/camunda-bpm-platform,langfr/camunda-bpm-platform,hupda-edpe/c,hupda-edpe/c,menski/camunda-bpm-platform,falko/camunda-bpm-platform,joansmith/camunda-bpm-platform,nibin/camunda-bpm-platform,rainerh/camunda-bpm-platform,xasx/camunda-bpm-platform,plexiti/camunda-bpm-platform,menski/camunda-bpm-platform,joansmith/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,bentrm/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,nibin/camunda-bpm-platform,bentrm/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,Sumitdahiya/camunda,ingorichtsmeier/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,holisticon/camunda-bpm-platform,jangalinski/camunda-bpm-platform,falko/camunda-bpm-platform,tcrossland/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,holisticon/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,joansmith/camunda-bpm-platform,1and1/camunda-bpm-platform,Sumitdahiya/camunda,fouasnon/camunda-bpm-platform,skjolber/camunda-bpm-platform,plexiti/camunda-bpm-platform,tcrossland/camunda-bpm-platform,camunda/camunda-bpm-platform,bentrm/camunda-bpm-platform,langfr/camunda-bpm-platform,camunda/camunda-bpm-platform,filiphr/camunda-bpm-platform,clintmanning/new-empty,rainerh/camunda-bpm-platform,clintmanning/new-empty,langfr/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,rainerh/camunda-bpm-platform,falko/camunda-bpm-platform,jangalinski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,camunda/camunda-bpm-platform,holisticon/camunda-bpm-platform,tcrossland/camunda-bpm-platform,jangalinski/camunda-bpm-platform,rainerh/camunda-bpm-platform,hupda-edpe/c,nibin/camunda-bpm-platform,jangalinski/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,skjolber/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,nibin/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,bentrm/camunda-bpm-platform,plexiti/camunda-bpm-platform,langfr/camunda-bpm-platform,clintmanning/new-empty,xasx/camunda-bpm-platform,hupda-edpe/c,subhrajyotim/camunda-bpm-platform,jangalinski/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,Sumitdahiya/camunda,LuisePufahl/camunda-bpm-platform_batchProcessing,xasx/camunda-bpm-platform,1and1/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,tcrossland/camunda-bpm-platform,falko/camunda-bpm-platform,1and1/camunda-bpm-platform,filiphr/camunda-bpm-platform,holisticon/camunda-bpm-platform,menski/camunda-bpm-platform,rainerh/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,fouasnon/camunda-bpm-platform,bentrm/camunda-bpm-platform,fouasnon/camunda-bpm-platform,Sumitdahiya/camunda,holisticon/camunda-bpm-platform,skjolber/camunda-bpm-platform,rainerh/camunda-bpm-platform,joansmith/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,filiphr/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,plexiti/camunda-bpm-platform,plexiti/camunda-bpm-platform,Sumitdahiya/camunda,ingorichtsmeier/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,subhrajyotim/camunda-bpm-platform,langfr/camunda-bpm-platform,camunda/camunda-bpm-platform,fouasnon/camunda-bpm-platform | package org.activiti.cycle.impl.connector.view;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.activiti.cycle.ArtifactType;
import org.activiti.cycle.Content;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.RepositoryConnector;
import org.activiti.cycle.RepositoryException;
import org.activiti.cycle.RepositoryFolder;
import org.activiti.cycle.RepositoryNode;
import org.activiti.cycle.RepositoryNodeCollection;
import org.activiti.cycle.RepositoryNodeNotFoundException;
import org.activiti.cycle.impl.RepositoryFolderImpl;
import org.activiti.cycle.impl.RepositoryNodeCollectionImpl;
import org.activiti.cycle.impl.RepositoryNodeImpl;
/**
* Connector to represent customized view for a user of cycle to hide all the
* internal configuration and {@link RepositoryConnector} stuff from the client
* (e.g. the webapp)
*
* @author [email protected]
*/
public class RootConnector implements RepositoryConnector {
private List<RepositoryConnector> repositoryConnectors;
private RootConnectorConfiguration configuration;
public RootConnector(RootConnectorConfiguration customizedViewConfiguration) {
configuration = customizedViewConfiguration;
}
public RootConnectorConfiguration getConfiguration() {
return configuration;
}
/**
* Get a map with all {@link RepositoryConnector}s created lazily and the name
* of the connector as key for the map.
*/
private List<RepositoryConnector> getRepositoryConnectors() {
if (repositoryConnectors == null) {
repositoryConnectors = getConfiguration().getConfigurationContainer().getConnectorList();
}
return repositoryConnectors;
}
private RepositoryConnector getRepositoryConnector(String name) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
if (connector.getConfiguration().getName().equals(name)) {
return connector;
}
}
throw new RepositoryException("Couldn't find Repository Connector with name '" + name + "'");
}
/**
* login into all repositories configured (if no username and password was
* provided by the configuration already).
*
* TODO: Make more sophisticated. Questions: What to do if one repo cannot
* login?
*/
public boolean login(String username, String password) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
// TODO: What if one repository failes? Try loading the other ones and
// remove the failing from the repo list? Example: Online SIgnavio when
// offile
connector.login(username, password);
}
return true;
}
/**
* commit pending changes in all repository connectors configured
*/
public void commitPendingChanges(String comment) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
connector.commitPendingChanges(comment);
}
}
/**
* construct a unique id for an {@link RepositoryNode} by adding the connector
* name (since this connector maintains different repos)
*/
private String getIdWithRepoName(RepositoryConnector connector, RepositoryNode repositoryNode) {
String repositoryName = connector.getConfiguration().getName();
if (!repositoryNode.getId().startsWith("/")) {
throw new RepositoryException("RepositoryNode id doesn't start with a slash, which is considered invalid: '" + repositoryNode.getId()
+ "' in repository '" + repositoryName + "'");
} else {
return getRepositoryPrefix(repositoryName) + repositoryNode.getId();
}
}
/**
* return the prefix for the {@link RepositoryConnector}
*/
private String getRepositoryPrefix(String repositoryName) {
return "/" + repositoryName;
}
/**
* add repository name in config to URL
*/
private RepositoryNode adjust(RepositoryConnector connector, RepositoryNode node) {
RepositoryNodeImpl repositoryNode = ((RepositoryNodeImpl) node);
repositoryNode.setId(getIdWithRepoName(connector, repositoryNode));
return repositoryNode;
}
protected RepositoryConnector getConnectorFromUrl(String url) {
RepositoryConnector connector = null;
int index = url.indexOf("/");
if (index == -1) {
// demo connector itself
connector = getRepositoryConnector(url);
} else if (index == 0) {
connector = getConnectorFromUrl(url.substring(1));
} else {
String repositoryName = url.substring(0, index);
connector = getRepositoryConnector(repositoryName);
}
if (connector == null) {
throw new RepositoryException("Couldn't find any RepositoryConnector for url '" + url + "'");
} else {
return connector;
}
}
protected String getRepositoryPartOfUrl(String url) {
int index = url.indexOf("/");
if (index == -1) {
// demo connector itself -> root folder is shown
return "/";
} else if (index == 0) {
return getRepositoryPartOfUrl(url.substring(1));
} else {
return url.substring(index);
}
}
public RepositoryNodeCollection getChildren(String parentUrl) {
// special handling for root
if ("/".equals(parentUrl)) {
return getRepoRootFolders();
}
// First identify correct repo and truncate path to local part of
// connector
RepositoryConnector connector = getConnectorFromUrl(parentUrl);
parentUrl = getRepositoryPartOfUrl(parentUrl);
// now make the query
RepositoryNodeCollection children = connector.getChildren(parentUrl);
// and adjust the result to include repo name
for (RepositoryNode repositoryNode : children.asList()) {
adjust(connector, repositoryNode);
}
return children;
}
public RepositoryNodeCollection getRepoRootFolders() {
ArrayList<RepositoryNode> nodes = new ArrayList<RepositoryNode>();
for (RepositoryConnector connector : getRepositoryConnectors()) {
String repoName = connector.getConfiguration().getName();
RepositoryFolderImpl folder = new RepositoryFolderImpl(repoName);
folder.getMetadata().setName(repoName);
folder.getMetadata().setParentFolderId("/");
nodes.add(folder);
}
return new RepositoryNodeCollectionImpl(nodes);
}
public RepositoryArtifact getRepositoryArtifact(String id) {
RepositoryConnector connector = getConnectorFromUrl(id);
RepositoryArtifact repositoryArtifact = connector.getRepositoryArtifact(
getRepositoryPartOfUrl(id));
adjust(connector, repositoryArtifact);
return repositoryArtifact;
}
public Content getRepositoryArtifactPreview(String artifactId) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
return connector.getRepositoryArtifactPreview(getRepositoryPartOfUrl(artifactId));
}
public RepositoryFolder getRepositoryFolder(String id) {
RepositoryConnector connector = getConnectorFromUrl(id);
RepositoryFolder repositoryFolder = connector.getRepositoryFolder(getRepositoryPartOfUrl(id));
adjust(connector, repositoryFolder);
return repositoryFolder;
}
public RepositoryArtifact createArtifact(String containingFolderId, String artifactName, String artifactType, Content artifactContent)
throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(containingFolderId).createArtifact(getRepositoryPartOfUrl(containingFolderId), artifactName, artifactType, artifactContent);
}
public RepositoryArtifact createArtifactFromContentRepresentation(String containingFolderId, String artifactName, String artifactType,
String contentRepresentationName, Content artifactContent) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(containingFolderId).createArtifactFromContentRepresentation(getRepositoryPartOfUrl(containingFolderId), artifactName,
artifactType, contentRepresentationName, artifactContent);
}
public void updateContent(String artifactId, Content content) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
connector.updateContent(getRepositoryPartOfUrl(artifactId), content);
}
public void updateContent(String artifactId, String contentRepresentationName, Content content) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
connector.updateContent(getRepositoryPartOfUrl(artifactId), contentRepresentationName, content);
}
public RepositoryFolder createFolder(String parentFolderId, String name) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(parentFolderId).createFolder(getRepositoryPartOfUrl(parentFolderId), name);
}
public void deleteArtifact(String artifactUrl) {
getConnectorFromUrl(artifactUrl).deleteArtifact(getRepositoryPartOfUrl(artifactUrl));
}
public void deleteFolder(String subFolderUrl) {
getConnectorFromUrl(subFolderUrl).deleteFolder(getRepositoryPartOfUrl(subFolderUrl));
}
public Content getContent(String artifactId, String representationName) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(artifactId).getContent(getRepositoryPartOfUrl(artifactId), representationName);
}
public void executeParameterizedAction(String artifactId, String actionId, Map<String, Object> parameters) throws Exception {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
String repoPartOfId = getRepositoryPartOfUrl(artifactId);
for (Entry<String, Object> parameter : new HashSet<Entry<String, Object>>(parameters.entrySet())) {
if (parameter.getKey().equals("treeTarget")) {
String targetFolderId = (String) parameter.getValue();
parameters.put("targetFolderConnector", getConnectorFromUrl(targetFolderId));
parameters.put("targetFolder", getRepositoryPartOfUrl(targetFolderId));
}
}
connector.executeParameterizedAction(repoPartOfId, actionId, parameters);
}
public List<ArtifactType> getSupportedArtifactTypes(String folderId) {
if (folderId == null || folderId.length() <= 1) {
// "virtual" root folder doesn't support any artifact types
return new ArrayList<ArtifactType>();
}
return getConnectorFromUrl(folderId).getSupportedArtifactTypes(getRepositoryPartOfUrl(folderId));
}
}
| activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/view/RootConnector.java | package org.activiti.cycle.impl.connector.view;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.activiti.cycle.ArtifactType;
import org.activiti.cycle.Content;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.RepositoryConnector;
import org.activiti.cycle.RepositoryException;
import org.activiti.cycle.RepositoryFolder;
import org.activiti.cycle.RepositoryNode;
import org.activiti.cycle.RepositoryNodeCollection;
import org.activiti.cycle.RepositoryNodeNotFoundException;
import org.activiti.cycle.impl.RepositoryFolderImpl;
import org.activiti.cycle.impl.RepositoryNodeCollectionImpl;
import org.activiti.cycle.impl.RepositoryNodeImpl;
/**
* Connector to represent customized view for a user of cycle to hide all the
* internal configuration and {@link RepositoryConnector} stuff from the client
* (e.g. the webapp)
*
* @author [email protected]
*/
public class RootConnector implements RepositoryConnector {
private List<RepositoryConnector> repositoryConnectors;
private RootConnectorConfiguration configuration;
public RootConnector(RootConnectorConfiguration customizedViewConfiguration) {
configuration = customizedViewConfiguration;
}
public RootConnectorConfiguration getConfiguration() {
return configuration;
}
/**
* Get a map with all {@link RepositoryConnector}s created lazily and the name
* of the connector as key for the map.
*/
private List<RepositoryConnector> getRepositoryConnectors() {
if (repositoryConnectors == null) {
repositoryConnectors = getConfiguration().getConfigurationContainer().getConnectorList();
}
return repositoryConnectors;
}
private RepositoryConnector getRepositoryConnector(String name) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
if (connector.getConfiguration().getName().equals(name)) {
return connector;
}
}
throw new RepositoryException("Couldn't find Repository Connector with name '" + name + "'");
}
/**
* login into all repositories configured (if no username and password was
* provided by the configuration already).
*
* TODO: Make more sophisticated. Questions: What to do if one repo cannot
* login?
*/
public boolean login(String username, String password) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
// TODO: What if one repository failes? Try loading the other ones and
// remove the failing from the repo list? Example: Online SIgnavio when
// offile
connector.login(username, password);
}
return true;
}
/**
* commit pending changes in all repository connectors configured
*/
public void commitPendingChanges(String comment) {
for (RepositoryConnector connector : getRepositoryConnectors()) {
connector.commitPendingChanges(comment);
}
}
/**
* construct a unique id for an {@link RepositoryNode} by adding the connector
* name (since this connector maintains different repos)
*/
private String getIdWithRepoName(RepositoryConnector connector, RepositoryNode repositoryNode) {
String repositoryName = connector.getConfiguration().getName();
if (!repositoryNode.getId().startsWith("/")) {
throw new RepositoryException("RepositoryNode id doesn't start with a slash, which is copnsidered invalid: '" + repositoryNode.getId()
+ "' in repository '" + repositoryName + "'");
} else {
return getRepositoryPrefix(repositoryName) + repositoryNode.getId();
}
}
/**
* return the prefix for the {@link RepositoryConnector}
*/
private String getRepositoryPrefix(String repositoryName) {
return "/" + repositoryName;
}
/**
* add repository name in config to URL
*/
private RepositoryNode adjust(RepositoryConnector connector, RepositoryNode node) {
RepositoryNodeImpl repositoryNode = ((RepositoryNodeImpl) node);
repositoryNode.setId(getIdWithRepoName(connector, repositoryNode));
return repositoryNode;
}
protected RepositoryConnector getConnectorFromUrl(String url) {
RepositoryConnector connector = null;
int index = url.indexOf("/");
if (index == -1) {
// demo connector itself
connector = getRepositoryConnector(url);
} else if (index == 0) {
connector = getConnectorFromUrl(url.substring(1));
} else {
String repositoryName = url.substring(0, index);
connector = getRepositoryConnector(repositoryName);
}
if (connector == null) {
throw new RepositoryException("Couldn't find any RepositoryConnector for url '" + url + "'");
} else {
return connector;
}
}
protected String getRepositoryPartOfUrl(String url) {
int index = url.indexOf("/");
if (index == -1) {
// demo connector itself -> root folder is shown
return "/";
} else if (index == 0) {
return getRepositoryPartOfUrl(url.substring(1));
} else {
return url.substring(index);
}
}
public RepositoryNodeCollection getChildren(String parentUrl) {
// special handling for root
if ("/".equals(parentUrl)) {
return getRepoRootFolders();
}
// First identify correct repo and truncate path to local part of
// connector
RepositoryConnector connector = getConnectorFromUrl(parentUrl);
parentUrl = getRepositoryPartOfUrl(parentUrl);
// now make the query
RepositoryNodeCollection children = connector.getChildren(parentUrl);
// and adjust the result to include repo name
for (RepositoryNode repositoryNode : children.asList()) {
adjust(connector, repositoryNode);
}
return children;
}
public RepositoryNodeCollection getRepoRootFolders() {
ArrayList<RepositoryNode> nodes = new ArrayList<RepositoryNode>();
for (RepositoryConnector connector : getRepositoryConnectors()) {
String repoName = connector.getConfiguration().getName();
RepositoryFolderImpl folder = new RepositoryFolderImpl(repoName);
folder.getMetadata().setName(repoName);
folder.getMetadata().setParentFolderId("/");
nodes.add(folder);
}
return new RepositoryNodeCollectionImpl(nodes);
}
public RepositoryArtifact getRepositoryArtifact(String id) {
RepositoryConnector connector = getConnectorFromUrl(id);
RepositoryArtifact repositoryArtifact = connector.getRepositoryArtifact(
getRepositoryPartOfUrl(id));
adjust(connector, repositoryArtifact);
return repositoryArtifact;
}
public Content getRepositoryArtifactPreview(String artifactId) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
return connector.getRepositoryArtifactPreview(getRepositoryPartOfUrl(artifactId));
}
public RepositoryFolder getRepositoryFolder(String id) {
RepositoryConnector connector = getConnectorFromUrl(id);
RepositoryFolder repositoryFolder = connector.getRepositoryFolder(getRepositoryPartOfUrl(id));
adjust(connector, repositoryFolder);
return repositoryFolder;
}
public RepositoryArtifact createArtifact(String containingFolderId, String artifactName, String artifactType, Content artifactContent)
throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(containingFolderId).createArtifact(getRepositoryPartOfUrl(containingFolderId), artifactName, artifactType, artifactContent);
}
public RepositoryArtifact createArtifactFromContentRepresentation(String containingFolderId, String artifactName, String artifactType,
String contentRepresentationName, Content artifactContent) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(containingFolderId).createArtifactFromContentRepresentation(getRepositoryPartOfUrl(containingFolderId), artifactName,
artifactType, contentRepresentationName, artifactContent);
}
public void updateContent(String artifactId, Content content) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
connector.updateContent(getRepositoryPartOfUrl(artifactId), content);
}
public void updateContent(String artifactId, String contentRepresentationName, Content content) throws RepositoryNodeNotFoundException {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
connector.updateContent(getRepositoryPartOfUrl(artifactId), contentRepresentationName, content);
}
public RepositoryFolder createFolder(String parentFolderId, String name) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(parentFolderId).createFolder(getRepositoryPartOfUrl(parentFolderId), name);
}
public void deleteArtifact(String artifactUrl) {
getConnectorFromUrl(artifactUrl).deleteArtifact(getRepositoryPartOfUrl(artifactUrl));
}
public void deleteFolder(String subFolderUrl) {
getConnectorFromUrl(subFolderUrl).deleteFolder(getRepositoryPartOfUrl(subFolderUrl));
}
public Content getContent(String artifactId, String representationName) throws RepositoryNodeNotFoundException {
return getConnectorFromUrl(artifactId).getContent(getRepositoryPartOfUrl(artifactId), representationName);
}
public void executeParameterizedAction(String artifactId, String actionId, Map<String, Object> parameters) throws Exception {
RepositoryConnector connector = getConnectorFromUrl(artifactId);
String repoPartOfId = getRepositoryPartOfUrl(artifactId);
for (Entry<String, Object> parameter : new HashSet<Entry<String, Object>>(parameters.entrySet())) {
if (parameter.getKey().equals("treeTarget")) {
String targetFolderId = (String) parameter.getValue();
parameters.put("targetFolderConnector", getConnectorFromUrl(targetFolderId));
parameters.put("targetFolder", getRepositoryPartOfUrl(targetFolderId));
}
}
connector.executeParameterizedAction(repoPartOfId, actionId, parameters);
}
public List<ArtifactType> getSupportedArtifactTypes(String folderId) {
if (folderId == null || folderId.length() <= 1) {
// "virtual" root folder doesn't support any artifact types
return new ArrayList<ArtifactType>();
}
return getConnectorFromUrl(folderId).getSupportedArtifactTypes(getRepositoryPartOfUrl(folderId));
}
}
| just fixed a typo
| activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/view/RootConnector.java | just fixed a typo |
|
Java | apache-2.0 | e08500578c604b88605cda5e011c0aa9ad3c3a5e | 0 | andrewmains12/hbase,andrewmains12/hbase,vincentpoon/hbase,Guavus/hbase,mahak/hbase,intel-hadoop/hbase-rhino,bijugs/hbase,francisliu/hbase,bijugs/hbase,apurtell/hbase,ultratendency/hbase,SeekerResource/hbase,StackVista/hbase,Guavus/hbase,Apache9/hbase,Guavus/hbase,vincentpoon/hbase,intel-hadoop/hbase-rhino,mahak/hbase,joshelser/hbase,toshimasa-nasu/hbase,lshmouse/hbase,gustavoanatoly/hbase,intel-hadoop/hbase-rhino,JingchengDu/hbase,mahak/hbase,francisliu/hbase,HubSpot/hbase,amyvmiwei/hbase,HubSpot/hbase,juwi/hbase,ndimiduk/hbase,toshimasa-nasu/hbase,Guavus/hbase,ibmsoe/hbase,juwi/hbase,mapr/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,narendragoyal/hbase,mapr/hbase,JingchengDu/hbase,drewpope/hbase,juwi/hbase,joshelser/hbase,amyvmiwei/hbase,Guavus/hbase,ndimiduk/hbase,justintung/hbase,Apache9/hbase,SeekerResource/hbase,amyvmiwei/hbase,JingchengDu/hbase,Guavus/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,HubSpot/hbase,andrewmains12/hbase,ultratendency/hbase,mahak/hbase,ChinmaySKulkarni/hbase,SeekerResource/hbase,ChinmaySKulkarni/hbase,toshimasa-nasu/hbase,narendragoyal/hbase,Eshcar/hbase,toshimasa-nasu/hbase,Eshcar/hbase,drewpope/hbase,vincentpoon/hbase,Apache9/hbase,ndimiduk/hbase,lshmouse/hbase,justintung/hbase,Guavus/hbase,ibmsoe/hbase,bijugs/hbase,narendragoyal/hbase,justintung/hbase,gustavoanatoly/hbase,lshmouse/hbase,lshmouse/hbase,SeekerResource/hbase,Eshcar/hbase,narendragoyal/hbase,toshimasa-nasu/hbase,vincentpoon/hbase,vincentpoon/hbase,narendragoyal/hbase,narendragoyal/hbase,JingchengDu/hbase,francisliu/hbase,HubSpot/hbase,apurtell/hbase,apurtell/hbase,JingchengDu/hbase,vincentpoon/hbase,JingchengDu/hbase,ibmsoe/hbase,ChinmaySKulkarni/hbase,drewpope/hbase,mapr/hbase,narendragoyal/hbase,SeekerResource/hbase,justintung/hbase,ultratendency/hbase,francisliu/hbase,justintung/hbase,toshimasa-nasu/hbase,joshelser/hbase,toshimasa-nasu/hbase,joshelser/hbase,francisliu/hbase,mahak/hbase,ultratendency/hbase,drewpope/hbase,SeekerResource/hbase,ibmsoe/hbase,ultratendency/hbase,ultratendency/hbase,joshelser/hbase,amyvmiwei/hbase,mahak/hbase,lshmouse/hbase,HubSpot/hbase,ibmsoe/hbase,juwi/hbase,bijugs/hbase,gustavoanatoly/hbase,andrewmains12/hbase,vincentpoon/hbase,lshmouse/hbase,drewpope/hbase,apurtell/hbase,ibmsoe/hbase,gustavoanatoly/hbase,juwi/hbase,JingchengDu/hbase,Eshcar/hbase,joshelser/hbase,andrewmains12/hbase,justintung/hbase,mapr/hbase,StackVista/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,justintung/hbase,andrewmains12/hbase,SeekerResource/hbase,ultratendency/hbase,toshimasa-nasu/hbase,joshelser/hbase,Apache9/hbase,ultratendency/hbase,francisliu/hbase,francisliu/hbase,SeekerResource/hbase,amyvmiwei/hbase,StackVista/hbase,mapr/hbase,juwi/hbase,mapr/hbase,amyvmiwei/hbase,Apache9/hbase,Eshcar/hbase,mahak/hbase,justintung/hbase,apurtell/hbase,juwi/hbase,lshmouse/hbase,joshelser/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,lshmouse/hbase,toshimasa-nasu/hbase,francisliu/hbase,ibmsoe/hbase,mapr/hbase,StackVista/hbase,HubSpot/hbase,Eshcar/hbase,mahak/hbase,mapr/hbase,Apache9/hbase,gustavoanatoly/hbase,HubSpot/hbase,HubSpot/hbase,Guavus/hbase,Eshcar/hbase,Guavus/hbase,HubSpot/hbase,lshmouse/hbase,JingchengDu/hbase,intel-hadoop/hbase-rhino,bijugs/hbase,bijugs/hbase,JingchengDu/hbase,SeekerResource/hbase,Apache9/hbase,vincentpoon/hbase,gustavoanatoly/hbase,juwi/hbase,ultratendency/hbase,Apache9/hbase,gustavoanatoly/hbase,bijugs/hbase,SeekerResource/hbase,StackVista/hbase,drewpope/hbase,andrewmains12/hbase,narendragoyal/hbase,intel-hadoop/hbase-rhino,ChinmaySKulkarni/hbase,ibmsoe/hbase,mahak/hbase,narendragoyal/hbase,joshelser/hbase,intel-hadoop/hbase-rhino,narendragoyal/hbase,Eshcar/hbase,drewpope/hbase,juwi/hbase,apurtell/hbase,intel-hadoop/hbase-rhino,apurtell/hbase,drewpope/hbase,StackVista/hbase,ndimiduk/hbase,justintung/hbase,ibmsoe/hbase,ndimiduk/hbase,bijugs/hbase,amyvmiwei/hbase,apurtell/hbase,StackVista/hbase,Guavus/hbase,ndimiduk/hbase,bijugs/hbase,mahak/hbase,Apache9/hbase,ndimiduk/hbase,JingchengDu/hbase,bijugs/hbase,ibmsoe/hbase,StackVista/hbase,StackVista/hbase,amyvmiwei/hbase,amyvmiwei/hbase,HubSpot/hbase,joshelser/hbase,gustavoanatoly/hbase,amyvmiwei/hbase,intel-hadoop/hbase-rhino,ndimiduk/hbase,ultratendency/hbase,justintung/hbase,intel-hadoop/hbase-rhino,Eshcar/hbase,mapr/hbase,intel-hadoop/hbase-rhino,lshmouse/hbase,Apache9/hbase,gustavoanatoly/hbase,ChinmaySKulkarni/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,drewpope/hbase,Eshcar/hbase,apurtell/hbase,vincentpoon/hbase,apurtell/hbase,ndimiduk/hbase,gustavoanatoly/hbase,francisliu/hbase,StackVista/hbase | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.thrift;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CompatibilityFactory;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.filter.ParseFilter;
import org.apache.hadoop.hbase.test.MetricsAssertHelper;
import org.apache.hadoop.hbase.thrift.ThriftServerRunner.HBaseHandler;
import org.apache.hadoop.hbase.thrift.generated.BatchMutation;
import org.apache.hadoop.hbase.thrift.generated.ColumnDescriptor;
import org.apache.hadoop.hbase.thrift.generated.Hbase;
import org.apache.hadoop.hbase.thrift.generated.IOError;
import org.apache.hadoop.hbase.thrift.generated.Mutation;
import org.apache.hadoop.hbase.thrift.generated.TCell;
import org.apache.hadoop.hbase.thrift.generated.TScan;
import org.apache.hadoop.hbase.thrift.generated.TIncrement;
import org.apache.hadoop.hbase.thrift.generated.TRegionInfo;
import org.apache.hadoop.hbase.thrift.generated.TRowResult;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Unit testing for ThriftServerRunner.HBaseHandler, a part of the
* org.apache.hadoop.hbase.thrift package.
*/
@Category(MediumTests.class)
public class TestThriftServer {
private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
private static final Log LOG = LogFactory.getLog(TestThriftServer.class);
private static final MetricsAssertHelper metricsHelper = CompatibilityFactory
.getInstance(MetricsAssertHelper.class);
protected static final int MAXVERSIONS = 3;
private static ByteBuffer asByteBuffer(String i) {
return ByteBuffer.wrap(Bytes.toBytes(i));
}
private static ByteBuffer asByteBuffer(long l) {
return ByteBuffer.wrap(Bytes.toBytes(l));
}
// Static names for tables, columns, rows, and values
private static ByteBuffer tableAname = asByteBuffer("tableA");
private static ByteBuffer tableBname = asByteBuffer("tableB");
private static ByteBuffer columnAname = asByteBuffer("columnA:");
private static ByteBuffer columnAAname = asByteBuffer("columnA:A");
private static ByteBuffer columnBname = asByteBuffer("columnB:");
private static ByteBuffer rowAname = asByteBuffer("rowA");
private static ByteBuffer rowBname = asByteBuffer("rowB");
private static ByteBuffer valueAname = asByteBuffer("valueA");
private static ByteBuffer valueBname = asByteBuffer("valueB");
private static ByteBuffer valueCname = asByteBuffer("valueC");
private static ByteBuffer valueDname = asByteBuffer("valueD");
private static ByteBuffer valueEname = asByteBuffer(100l);
@BeforeClass
public static void beforeClass() throws Exception {
UTIL.getConfiguration().setBoolean(ThriftServerRunner.COALESCE_INC_KEY, true);
UTIL.startMiniCluster();
}
@AfterClass
public static void afterClass() throws Exception {
UTIL.shutdownMiniCluster();
}
/**
* Runs all of the tests under a single JUnit test method. We
* consolidate all testing to one method because HBaseClusterTestCase
* is prone to OutOfMemoryExceptions when there are three or more
* JUnit test methods.
*
* @throws Exception
*/
@Test
public void testAll() throws Exception {
// Run all tests
doTestTableCreateDrop();
doTestThriftMetrics();
doTestTableMutations();
doTestTableTimestampsAndColumns();
doTestTableScanners();
doTestGetTableRegions();
doTestFilterRegistration();
doTestGetRegionInfo();
doTestIncrements();
}
/**
* Tests for creating, enabling, disabling, and deleting tables. Also
* tests that creating a table with an invalid column name yields an
* IllegalArgument exception.
*
* @throws Exception
*/
public void doTestTableCreateDrop() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestTableCreateDrop(handler);
}
public static void doTestTableCreateDrop(Hbase.Iface handler) throws Exception {
createTestTables(handler);
dropTestTables(handler);
}
public static final class MySlowHBaseHandler extends ThriftServerRunner.HBaseHandler
implements Hbase.Iface {
protected MySlowHBaseHandler(Configuration c)
throws IOException {
super(c);
}
@Override
public List<ByteBuffer> getTableNames() throws IOError {
Threads.sleepWithoutInterrupt(3000);
return super.getTableNames();
}
}
/**
* TODO: These counts are supposed to be zero but sometimes they are not, they are equal to the
* passed in maybe. Investigate why. My guess is they are set by the test that runs just
* previous to this one. Sometimes they are cleared. Sometimes not.
* @param name
* @param maybe
* @param metrics
* @return
*/
private int getCurrentCount(final String name, final int maybe, final ThriftMetrics metrics) {
int currentCount = 0;
try {
metricsHelper.assertCounter(name, maybe, metrics.getSource());
LOG.info("Shouldn't this be null? name=" + name + ", equals=" + maybe);
currentCount = maybe;
} catch (AssertionError e) {
// Ignore
}
return currentCount;
}
/**
* Tests if the metrics for thrift handler work correctly
*/
public void doTestThriftMetrics() throws Exception {
LOG.info("START doTestThriftMetrics");
Configuration conf = UTIL.getConfiguration();
ThriftMetrics metrics = getMetrics(conf);
Hbase.Iface handler = getHandlerForMetricsTest(metrics, conf);
int currentCountCreateTable = getCurrentCount("createTable_num_ops", 2, metrics);
int currentCountDeleteTable = getCurrentCount("deleteTable_num_ops", 2, metrics);
int currentCountDisableTable = getCurrentCount("disableTable_num_ops", 2, metrics);
createTestTables(handler);
dropTestTables(handler);;
metricsHelper.assertCounter("createTable_num_ops", currentCountCreateTable + 2,
metrics.getSource());
metricsHelper.assertCounter("deleteTable_num_ops", currentCountDeleteTable + 2,
metrics.getSource());
metricsHelper.assertCounter("disableTable_num_ops", currentCountDisableTable + 2,
metrics.getSource());
handler.getTableNames(); // This will have an artificial delay.
// 3 to 6 seconds (to account for potential slowness), measured in nanoseconds
metricsHelper.assertGaugeGt("getTableNames_avg_time", 3L * 1000 * 1000 * 1000, metrics.getSource());
metricsHelper.assertGaugeLt("getTableNames_avg_time",6L * 1000 * 1000 * 1000, metrics.getSource());
}
private static Hbase.Iface getHandlerForMetricsTest(ThriftMetrics metrics, Configuration conf)
throws Exception {
Hbase.Iface handler = new MySlowHBaseHandler(conf);
return HbaseHandlerMetricsProxy.newInstance(handler, metrics, conf);
}
private static ThriftMetrics getMetrics(Configuration conf) throws Exception {
return new ThriftMetrics( conf, ThriftMetrics.ThriftServerType.ONE);
}
public static void createTestTables(Hbase.Iface handler) throws Exception {
// Create/enable/disable/delete tables, ensure methods act correctly
assertEquals(handler.getTableNames().size(), 0);
handler.createTable(tableAname, getColumnDescriptors());
assertEquals(handler.getTableNames().size(), 1);
assertEquals(handler.getColumnDescriptors(tableAname).size(), 2);
assertTrue(handler.isTableEnabled(tableAname));
handler.createTable(tableBname, new ArrayList<ColumnDescriptor>());
assertEquals(handler.getTableNames().size(), 2);
}
public static void checkTableList(Hbase.Iface handler) throws Exception {
assertTrue(handler.getTableNames().contains(tableAname));
}
public static void dropTestTables(Hbase.Iface handler) throws Exception {
handler.disableTable(tableBname);
assertFalse(handler.isTableEnabled(tableBname));
handler.deleteTable(tableBname);
assertEquals(handler.getTableNames().size(), 1);
handler.disableTable(tableAname);
assertFalse(handler.isTableEnabled(tableAname));
/* TODO Reenable.
assertFalse(handler.isTableEnabled(tableAname));
handler.enableTable(tableAname);
assertTrue(handler.isTableEnabled(tableAname));
handler.disableTable(tableAname);*/
handler.deleteTable(tableAname);
assertEquals(handler.getTableNames().size(), 0);
}
public void doTestIncrements() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
createTestTables(handler);
doTestIncrements(handler);
dropTestTables(handler);
}
public static void doTestIncrements(HBaseHandler handler) throws Exception {
List<Mutation> mutations = new ArrayList<Mutation>(1);
mutations.add(new Mutation(false, columnAAname, valueEname, true));
mutations.add(new Mutation(false, columnAname, valueEname, true));
handler.mutateRow(tableAname, rowAname, mutations, null);
handler.mutateRow(tableAname, rowBname, mutations, null);
List<TIncrement> increments = new ArrayList<TIncrement>();
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
int numIncrements = 60000;
for (int i = 0; i < numIncrements; i++) {
handler.increment(new TIncrement(tableAname, rowAname, columnAname, 2));
handler.incrementRows(increments);
}
Thread.sleep(1000);
long lv = handler.get(tableAname, rowAname, columnAname, null).get(0).value.getLong();
// Wait on all increments being flushed
while (handler.coalescer.getQueueSize() != 0) Threads.sleep(10);
assertEquals((100 + (2 * numIncrements)), lv );
lv = handler.get(tableAname, rowBname, columnAAname, null).get(0).value.getLong();
assertEquals((100 + (3 * 7 * numIncrements)), lv);
assertTrue(handler.coalescer.getSuccessfulCoalescings() > 0);
}
/**
* Tests adding a series of Mutations and BatchMutations, including a
* delete mutation. Also tests data retrieval, and getting back multiple
* versions.
*
* @throws Exception
*/
public void doTestTableMutations() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestTableMutations(handler);
}
public static void doTestTableMutations(Hbase.Iface handler) throws Exception {
// Setup
handler.createTable(tableAname, getColumnDescriptors());
// Apply a few Mutations to rowA
// mutations.add(new Mutation(false, columnAname, valueAname));
// mutations.add(new Mutation(false, columnBname, valueBname));
handler.mutateRow(tableAname, rowAname, getMutations(), null);
// Assert that the changes were made
assertEquals(valueAname,
handler.get(tableAname, rowAname, columnAname, null).get(0).value);
TRowResult rowResult1 = handler.getRow(tableAname, rowAname, null).get(0);
assertEquals(rowAname, rowResult1.row);
assertEquals(valueBname,
rowResult1.columns.get(columnBname).value);
// Apply a few BatchMutations for rowA and rowB
// rowAmutations.add(new Mutation(true, columnAname, null));
// rowAmutations.add(new Mutation(false, columnBname, valueCname));
// batchMutations.add(new BatchMutation(rowAname, rowAmutations));
// Mutations to rowB
// rowBmutations.add(new Mutation(false, columnAname, valueCname));
// rowBmutations.add(new Mutation(false, columnBname, valueDname));
// batchMutations.add(new BatchMutation(rowBname, rowBmutations));
handler.mutateRows(tableAname, getBatchMutations(), null);
// Assert that changes were made to rowA
List<TCell> cells = handler.get(tableAname, rowAname, columnAname, null);
assertFalse(cells.size() > 0);
assertEquals(valueCname, handler.get(tableAname, rowAname, columnBname, null).get(0).value);
List<TCell> versions = handler.getVer(tableAname, rowAname, columnBname, MAXVERSIONS, null);
assertEquals(valueCname, versions.get(0).value);
assertEquals(valueBname, versions.get(1).value);
// Assert that changes were made to rowB
TRowResult rowResult2 = handler.getRow(tableAname, rowBname, null).get(0);
assertEquals(rowBname, rowResult2.row);
assertEquals(valueCname, rowResult2.columns.get(columnAname).value);
assertEquals(valueDname, rowResult2.columns.get(columnBname).value);
// Apply some deletes
handler.deleteAll(tableAname, rowAname, columnBname, null);
handler.deleteAllRow(tableAname, rowBname, null);
// Assert that the deletes were applied
int size = handler.get(tableAname, rowAname, columnBname, null).size();
assertEquals(0, size);
size = handler.getRow(tableAname, rowBname, null).size();
assertEquals(0, size);
// Try null mutation
List<Mutation> mutations = new ArrayList<Mutation>();
mutations.add(new Mutation(false, columnAname, null, true));
handler.mutateRow(tableAname, rowAname, mutations, null);
TRowResult rowResult3 = handler.getRow(tableAname, rowAname, null).get(0);
assertEquals(rowAname, rowResult3.row);
assertEquals(0, rowResult3.columns.get(columnAname).value.remaining());
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* Similar to testTableMutations(), except Mutations are applied with
* specific timestamps and data retrieval uses these timestamps to
* extract specific versions of data.
*
* @throws Exception
*/
public void doTestTableTimestampsAndColumns() throws Exception {
// Setup
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
handler.createTable(tableAname, getColumnDescriptors());
// Apply timestamped Mutations to rowA
long time1 = System.currentTimeMillis();
handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null);
Thread.sleep(1000);
// Apply timestamped BatchMutations for rowA and rowB
long time2 = System.currentTimeMillis();
handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null);
// Apply an overlapping timestamped mutation to rowB
handler.mutateRowTs(tableAname, rowBname, getMutations(), time2, null);
// the getVerTs is [inf, ts) so you need to increment one.
time1 += 1;
time2 += 2;
// Assert that the timestamp-related methods retrieve the correct data
assertEquals(2, handler.getVerTs(tableAname, rowAname, columnBname, time2,
MAXVERSIONS, null).size());
assertEquals(1, handler.getVerTs(tableAname, rowAname, columnBname, time1,
MAXVERSIONS, null).size());
TRowResult rowResult1 = handler.getRowTs(tableAname, rowAname, time1, null).get(0);
TRowResult rowResult2 = handler.getRowTs(tableAname, rowAname, time2, null).get(0);
// columnA was completely deleted
//assertTrue(Bytes.equals(rowResult1.columns.get(columnAname).value, valueAname));
assertEquals(rowResult1.columns.get(columnBname).value, valueBname);
assertEquals(rowResult2.columns.get(columnBname).value, valueCname);
// ColumnAname has been deleted, and will never be visible even with a getRowTs()
assertFalse(rowResult2.columns.containsKey(columnAname));
List<ByteBuffer> columns = new ArrayList<ByteBuffer>();
columns.add(columnBname);
rowResult1 = handler.getRowWithColumns(tableAname, rowAname, columns, null).get(0);
assertEquals(rowResult1.columns.get(columnBname).value, valueCname);
assertFalse(rowResult1.columns.containsKey(columnAname));
rowResult1 = handler.getRowWithColumnsTs(tableAname, rowAname, columns, time1, null).get(0);
assertEquals(rowResult1.columns.get(columnBname).value, valueBname);
assertFalse(rowResult1.columns.containsKey(columnAname));
// Apply some timestamped deletes
// this actually deletes _everything_.
// nukes everything in columnB: forever.
handler.deleteAllTs(tableAname, rowAname, columnBname, time1, null);
handler.deleteAllRowTs(tableAname, rowBname, time2, null);
// Assert that the timestamp-related methods retrieve the correct data
int size = handler.getVerTs(tableAname, rowAname, columnBname, time1, MAXVERSIONS, null).size();
assertEquals(0, size);
size = handler.getVerTs(tableAname, rowAname, columnBname, time2, MAXVERSIONS, null).size();
assertEquals(1, size);
// should be available....
assertEquals(handler.get(tableAname, rowAname, columnBname, null).get(0).value, valueCname);
assertEquals(0, handler.getRow(tableAname, rowBname, null).size());
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* Tests the four different scanner-opening methods (with and without
* a stoprow, with and without a timestamp).
*
* @throws Exception
*/
public void doTestTableScanners() throws Exception {
// Setup
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
handler.createTable(tableAname, getColumnDescriptors());
// Apply timestamped Mutations to rowA
long time1 = System.currentTimeMillis();
handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null);
// Sleep to assure that 'time1' and 'time2' will be different even with a
// coarse grained system timer.
Thread.sleep(1000);
// Apply timestamped BatchMutations for rowA and rowB
long time2 = System.currentTimeMillis();
handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null);
time1 += 1;
// Test a scanner on all rows and all columns, no timestamp
int scanner1 = handler.scannerOpen(tableAname, rowAname, getColumnList(true, true), null);
TRowResult rowResult1a = handler.scannerGet(scanner1).get(0);
assertEquals(rowResult1a.row, rowAname);
// This used to be '1'. I don't know why when we are asking for two columns
// and when the mutations above would seem to add two columns to the row.
// -- St.Ack 05/12/2009
assertEquals(rowResult1a.columns.size(), 1);
assertEquals(rowResult1a.columns.get(columnBname).value, valueCname);
TRowResult rowResult1b = handler.scannerGet(scanner1).get(0);
assertEquals(rowResult1b.row, rowBname);
assertEquals(rowResult1b.columns.size(), 2);
assertEquals(rowResult1b.columns.get(columnAname).value, valueCname);
assertEquals(rowResult1b.columns.get(columnBname).value, valueDname);
closeScanner(scanner1, handler);
// Test a scanner on all rows and all columns, with timestamp
int scanner2 = handler.scannerOpenTs(tableAname, rowAname, getColumnList(true, true), time1, null);
TRowResult rowResult2a = handler.scannerGet(scanner2).get(0);
assertEquals(rowResult2a.columns.size(), 1);
// column A deleted, does not exist.
//assertTrue(Bytes.equals(rowResult2a.columns.get(columnAname).value, valueAname));
assertEquals(rowResult2a.columns.get(columnBname).value, valueBname);
closeScanner(scanner2, handler);
// Test a scanner on the first row and first column only, no timestamp
int scanner3 = handler.scannerOpenWithStop(tableAname, rowAname, rowBname,
getColumnList(true, false), null);
closeScanner(scanner3, handler);
// Test a scanner on the first row and second column only, with timestamp
int scanner4 = handler.scannerOpenWithStopTs(tableAname, rowAname, rowBname,
getColumnList(false, true), time1, null);
TRowResult rowResult4a = handler.scannerGet(scanner4).get(0);
assertEquals(rowResult4a.columns.size(), 1);
assertEquals(rowResult4a.columns.get(columnBname).value, valueBname);
// Test scanner using a TScan object once with sortColumns False and once with sortColumns true
TScan scanNoSortColumns = new TScan();
scanNoSortColumns.setStartRow(rowAname);
scanNoSortColumns.setStopRow(rowBname);
int scanner5 = handler.scannerOpenWithScan(tableAname , scanNoSortColumns, null);
TRowResult rowResult5 = handler.scannerGet(scanner5).get(0);
assertEquals(rowResult5.columns.size(), 1);
assertEquals(rowResult5.columns.get(columnBname).value, valueCname);
TScan scanSortColumns = new TScan();
scanSortColumns.setStartRow(rowAname);
scanSortColumns.setStopRow(rowBname);
scanSortColumns = scanSortColumns.setSortColumns(true);
int scanner6 = handler.scannerOpenWithScan(tableAname ,scanSortColumns, null);
TRowResult rowResult6 = handler.scannerGet(scanner6).get(0);
assertEquals(rowResult6.sortedColumns.size(), 1);
assertEquals(rowResult6.sortedColumns.get(0).getCell().value, valueCname);
List<Mutation> rowBmutations = new ArrayList<Mutation>();
for (int i = 0; i < 20; i++) {
rowBmutations.add(new Mutation(false, asByteBuffer("columnA:" + i), valueCname, true));
}
ByteBuffer rowC = asByteBuffer("rowC");
handler.mutateRow(tableAname, rowC, rowBmutations, null);
TScan scanSortMultiColumns = new TScan();
scanSortMultiColumns.setStartRow(rowC);
scanSortMultiColumns = scanSortMultiColumns.setSortColumns(true);
int scanner7 = handler.scannerOpenWithScan(tableAname, scanSortMultiColumns, null);
TRowResult rowResult7 = handler.scannerGet(scanner7).get(0);
ByteBuffer smallerColumn = asByteBuffer("columnA:");
for (int i = 0; i < 20; i++) {
ByteBuffer currentColumn = rowResult7.sortedColumns.get(i).columnName;
assertTrue(Bytes.compareTo(smallerColumn.array(), currentColumn.array()) < 0);
smallerColumn = currentColumn;
}
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* For HBASE-2556
* Tests for GetTableRegions
*
* @throws Exception
*/
public void doTestGetTableRegions() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestGetTableRegions(handler);
}
public static void doTestGetTableRegions(Hbase.Iface handler)
throws Exception {
assertEquals(handler.getTableNames().size(), 0);
handler.createTable(tableAname, getColumnDescriptors());
assertEquals(handler.getTableNames().size(), 1);
List<TRegionInfo> regions = handler.getTableRegions(tableAname);
int regionCount = regions.size();
assertEquals("empty table should have only 1 region, " +
"but found " + regionCount, regionCount, 1);
LOG.info("Region found:" + regions.get(0));
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
regionCount = handler.getTableRegions(tableAname).size();
assertEquals("non-existing table should have 0 region, " +
"but found " + regionCount, regionCount, 0);
}
public void doTestFilterRegistration() throws Exception {
Configuration conf = UTIL.getConfiguration();
conf.set("hbase.thrift.filters", "MyFilter:filterclass");
ThriftServerRunner.registerFilters(conf);
Map<String, String> registeredFilters = ParseFilter.getAllFilters();
assertEquals("filterclass", registeredFilters.get("MyFilter"));
}
public void doTestGetRegionInfo() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestGetRegionInfo(handler);
}
public static void doTestGetRegionInfo(Hbase.Iface handler) throws Exception {
// Create tableA and add two columns to rowA
handler.createTable(tableAname, getColumnDescriptors());
try {
handler.mutateRow(tableAname, rowAname, getMutations(), null);
byte[] searchRow = HRegionInfo.createRegionName(
TableName.valueOf(tableAname.array()), rowAname.array(),
HConstants.NINES, false);
TRegionInfo regionInfo = handler.getRegionInfo(ByteBuffer.wrap(searchRow));
assertTrue(Bytes.toStringBinary(regionInfo.getName()).startsWith(
Bytes.toStringBinary(tableAname)));
} finally {
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
}
/**
*
* @return a List of ColumnDescriptors for use in creating a table. Has one
* default ColumnDescriptor and one ColumnDescriptor with fewer versions
*/
private static List<ColumnDescriptor> getColumnDescriptors() {
ArrayList<ColumnDescriptor> cDescriptors = new ArrayList<ColumnDescriptor>();
// A default ColumnDescriptor
ColumnDescriptor cDescA = new ColumnDescriptor();
cDescA.name = columnAname;
cDescriptors.add(cDescA);
// A slightly customized ColumnDescriptor (only 2 versions)
ColumnDescriptor cDescB = new ColumnDescriptor(columnBname, 2, "NONE",
false, "NONE", 0, 0, false, -1);
cDescriptors.add(cDescB);
return cDescriptors;
}
/**
*
* @param includeA whether or not to include columnA
* @param includeB whether or not to include columnB
* @return a List of column names for use in retrieving a scanner
*/
private List<ByteBuffer> getColumnList(boolean includeA, boolean includeB) {
List<ByteBuffer> columnList = new ArrayList<ByteBuffer>();
if (includeA) columnList.add(columnAname);
if (includeB) columnList.add(columnBname);
return columnList;
}
/**
*
* @return a List of Mutations for a row, with columnA having valueA
* and columnB having valueB
*/
private static List<Mutation> getMutations() {
List<Mutation> mutations = new ArrayList<Mutation>();
mutations.add(new Mutation(false, columnAname, valueAname, true));
mutations.add(new Mutation(false, columnBname, valueBname, true));
return mutations;
}
/**
*
* @return a List of BatchMutations with the following effects:
* (rowA, columnA): delete
* (rowA, columnB): place valueC
* (rowB, columnA): place valueC
* (rowB, columnB): place valueD
*/
private static List<BatchMutation> getBatchMutations() {
List<BatchMutation> batchMutations = new ArrayList<BatchMutation>();
// Mutations to rowA. You can't mix delete and put anymore.
List<Mutation> rowAmutations = new ArrayList<Mutation>();
rowAmutations.add(new Mutation(true, columnAname, null, true));
batchMutations.add(new BatchMutation(rowAname, rowAmutations));
rowAmutations = new ArrayList<Mutation>();
rowAmutations.add(new Mutation(false, columnBname, valueCname, true));
batchMutations.add(new BatchMutation(rowAname, rowAmutations));
// Mutations to rowB
List<Mutation> rowBmutations = new ArrayList<Mutation>();
rowBmutations.add(new Mutation(false, columnAname, valueCname, true));
rowBmutations.add(new Mutation(false, columnBname, valueDname, true));
batchMutations.add(new BatchMutation(rowBname, rowBmutations));
return batchMutations;
}
/**
* Asserts that the passed scanner is exhausted, and then closes
* the scanner.
*
* @param scannerId the scanner to close
* @param handler the HBaseHandler interfacing to HBase
* @throws Exception
*/
private void closeScanner(
int scannerId, ThriftServerRunner.HBaseHandler handler) throws Exception {
handler.scannerGet(scannerId);
handler.scannerClose(scannerId);
}
}
| hbase-thrift/src/test/java/org/apache/hadoop/hbase/thrift/TestThriftServer.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.thrift;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CompatibilityFactory;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.filter.ParseFilter;
import org.apache.hadoop.hbase.test.MetricsAssertHelper;
import org.apache.hadoop.hbase.thrift.ThriftServerRunner.HBaseHandler;
import org.apache.hadoop.hbase.thrift.generated.BatchMutation;
import org.apache.hadoop.hbase.thrift.generated.ColumnDescriptor;
import org.apache.hadoop.hbase.thrift.generated.Hbase;
import org.apache.hadoop.hbase.thrift.generated.IOError;
import org.apache.hadoop.hbase.thrift.generated.Mutation;
import org.apache.hadoop.hbase.thrift.generated.TCell;
import org.apache.hadoop.hbase.thrift.generated.TScan;
import org.apache.hadoop.hbase.thrift.generated.TIncrement;
import org.apache.hadoop.hbase.thrift.generated.TRegionInfo;
import org.apache.hadoop.hbase.thrift.generated.TRowResult;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Unit testing for ThriftServerRunner.HBaseHandler, a part of the
* org.apache.hadoop.hbase.thrift package.
*/
@Category(MediumTests.class)
public class TestThriftServer {
private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
private static final Log LOG = LogFactory.getLog(TestThriftServer.class);
private static final MetricsAssertHelper metricsHelper = CompatibilityFactory
.getInstance(MetricsAssertHelper.class);
protected static final int MAXVERSIONS = 3;
private static ByteBuffer asByteBuffer(String i) {
return ByteBuffer.wrap(Bytes.toBytes(i));
}
private static ByteBuffer asByteBuffer(long l) {
return ByteBuffer.wrap(Bytes.toBytes(l));
}
// Static names for tables, columns, rows, and values
private static ByteBuffer tableAname = asByteBuffer("tableA");
private static ByteBuffer tableBname = asByteBuffer("tableB");
private static ByteBuffer columnAname = asByteBuffer("columnA:");
private static ByteBuffer columnAAname = asByteBuffer("columnA:A");
private static ByteBuffer columnBname = asByteBuffer("columnB:");
private static ByteBuffer rowAname = asByteBuffer("rowA");
private static ByteBuffer rowBname = asByteBuffer("rowB");
private static ByteBuffer valueAname = asByteBuffer("valueA");
private static ByteBuffer valueBname = asByteBuffer("valueB");
private static ByteBuffer valueCname = asByteBuffer("valueC");
private static ByteBuffer valueDname = asByteBuffer("valueD");
private static ByteBuffer valueEname = asByteBuffer(100l);
@BeforeClass
public static void beforeClass() throws Exception {
UTIL.getConfiguration().setBoolean(ThriftServerRunner.COALESCE_INC_KEY, true);
UTIL.startMiniCluster();
}
@AfterClass
public static void afterClass() throws Exception {
UTIL.shutdownMiniCluster();
}
/**
* Runs all of the tests under a single JUnit test method. We
* consolidate all testing to one method because HBaseClusterTestCase
* is prone to OutOfMemoryExceptions when there are three or more
* JUnit test methods.
*
* @throws Exception
*/
@Test
public void testAll() throws Exception {
// Run all tests
doTestTableCreateDrop();
doTestThriftMetrics();
doTestTableMutations();
doTestTableTimestampsAndColumns();
doTestTableScanners();
doTestGetTableRegions();
doTestFilterRegistration();
doTestGetRegionInfo();
doTestIncrements();
}
/**
* Tests for creating, enabling, disabling, and deleting tables. Also
* tests that creating a table with an invalid column name yields an
* IllegalArgument exception.
*
* @throws Exception
*/
public void doTestTableCreateDrop() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestTableCreateDrop(handler);
}
public static void doTestTableCreateDrop(Hbase.Iface handler) throws Exception {
createTestTables(handler);
dropTestTables(handler);
}
public static final class MySlowHBaseHandler extends ThriftServerRunner.HBaseHandler
implements Hbase.Iface {
protected MySlowHBaseHandler(Configuration c)
throws IOException {
super(c);
}
@Override
public List<ByteBuffer> getTableNames() throws IOError {
Threads.sleepWithoutInterrupt(3000);
return super.getTableNames();
}
}
/**
* Tests if the metrics for thrift handler work correctly
*/
public void doTestThriftMetrics() throws Exception {
LOG.info("START doTestThriftMetrics");
Configuration conf = UTIL.getConfiguration();
ThriftMetrics metrics = getMetrics(conf);
Hbase.Iface handler = getHandlerForMetricsTest(metrics, conf);
try {
metricsHelper.assertCounter("createTable_num_ops", 2, metrics.getSource());
LOG.info("SHOULD NOT BE HERE");
} catch (AssertionError e) {
// DEBUGGING
LOG.info("Got expected assertion error");
}
createTestTables(handler);
dropTestTables(handler);
metricsHelper.assertCounter("createTable_num_ops", 2, metrics.getSource());
metricsHelper.assertCounter("deleteTable_num_ops", 2, metrics.getSource());
metricsHelper.assertCounter("disableTable_num_ops", 2, metrics.getSource());
handler.getTableNames(); // This will have an artificial delay.
// 3 to 6 seconds (to account for potential slowness), measured in nanoseconds
metricsHelper.assertGaugeGt("getTableNames_avg_time", 3L * 1000 * 1000 * 1000, metrics.getSource());
metricsHelper.assertGaugeLt("getTableNames_avg_time",6L * 1000 * 1000 * 1000, metrics.getSource());
}
private static Hbase.Iface getHandlerForMetricsTest(ThriftMetrics metrics, Configuration conf)
throws Exception {
Hbase.Iface handler = new MySlowHBaseHandler(conf);
return HbaseHandlerMetricsProxy.newInstance(handler, metrics, conf);
}
private static ThriftMetrics getMetrics(Configuration conf) throws Exception {
return new ThriftMetrics( conf, ThriftMetrics.ThriftServerType.ONE);
}
public static void createTestTables(Hbase.Iface handler) throws Exception {
// Create/enable/disable/delete tables, ensure methods act correctly
assertEquals(handler.getTableNames().size(), 0);
handler.createTable(tableAname, getColumnDescriptors());
assertEquals(handler.getTableNames().size(), 1);
assertEquals(handler.getColumnDescriptors(tableAname).size(), 2);
assertTrue(handler.isTableEnabled(tableAname));
handler.createTable(tableBname, new ArrayList<ColumnDescriptor>());
assertEquals(handler.getTableNames().size(), 2);
}
public static void checkTableList(Hbase.Iface handler) throws Exception {
assertTrue(handler.getTableNames().contains(tableAname));
}
public static void dropTestTables(Hbase.Iface handler) throws Exception {
handler.disableTable(tableBname);
assertFalse(handler.isTableEnabled(tableBname));
handler.deleteTable(tableBname);
assertEquals(handler.getTableNames().size(), 1);
handler.disableTable(tableAname);
assertFalse(handler.isTableEnabled(tableAname));
/* TODO Reenable.
assertFalse(handler.isTableEnabled(tableAname));
handler.enableTable(tableAname);
assertTrue(handler.isTableEnabled(tableAname));
handler.disableTable(tableAname);*/
handler.deleteTable(tableAname);
assertEquals(handler.getTableNames().size(), 0);
}
public void doTestIncrements() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
createTestTables(handler);
doTestIncrements(handler);
dropTestTables(handler);
}
public static void doTestIncrements(HBaseHandler handler) throws Exception {
List<Mutation> mutations = new ArrayList<Mutation>(1);
mutations.add(new Mutation(false, columnAAname, valueEname, true));
mutations.add(new Mutation(false, columnAname, valueEname, true));
handler.mutateRow(tableAname, rowAname, mutations, null);
handler.mutateRow(tableAname, rowBname, mutations, null);
List<TIncrement> increments = new ArrayList<TIncrement>();
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7));
int numIncrements = 60000;
for (int i = 0; i < numIncrements; i++) {
handler.increment(new TIncrement(tableAname, rowAname, columnAname, 2));
handler.incrementRows(increments);
}
Thread.sleep(1000);
long lv = handler.get(tableAname, rowAname, columnAname, null).get(0).value.getLong();
// Wait on all increments being flushed
while (handler.coalescer.getQueueSize() != 0) Threads.sleep(10);
assertEquals((100 + (2 * numIncrements)), lv );
lv = handler.get(tableAname, rowBname, columnAAname, null).get(0).value.getLong();
assertEquals((100 + (3 * 7 * numIncrements)), lv);
assertTrue(handler.coalescer.getSuccessfulCoalescings() > 0);
}
/**
* Tests adding a series of Mutations and BatchMutations, including a
* delete mutation. Also tests data retrieval, and getting back multiple
* versions.
*
* @throws Exception
*/
public void doTestTableMutations() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestTableMutations(handler);
}
public static void doTestTableMutations(Hbase.Iface handler) throws Exception {
// Setup
handler.createTable(tableAname, getColumnDescriptors());
// Apply a few Mutations to rowA
// mutations.add(new Mutation(false, columnAname, valueAname));
// mutations.add(new Mutation(false, columnBname, valueBname));
handler.mutateRow(tableAname, rowAname, getMutations(), null);
// Assert that the changes were made
assertEquals(valueAname,
handler.get(tableAname, rowAname, columnAname, null).get(0).value);
TRowResult rowResult1 = handler.getRow(tableAname, rowAname, null).get(0);
assertEquals(rowAname, rowResult1.row);
assertEquals(valueBname,
rowResult1.columns.get(columnBname).value);
// Apply a few BatchMutations for rowA and rowB
// rowAmutations.add(new Mutation(true, columnAname, null));
// rowAmutations.add(new Mutation(false, columnBname, valueCname));
// batchMutations.add(new BatchMutation(rowAname, rowAmutations));
// Mutations to rowB
// rowBmutations.add(new Mutation(false, columnAname, valueCname));
// rowBmutations.add(new Mutation(false, columnBname, valueDname));
// batchMutations.add(new BatchMutation(rowBname, rowBmutations));
handler.mutateRows(tableAname, getBatchMutations(), null);
// Assert that changes were made to rowA
List<TCell> cells = handler.get(tableAname, rowAname, columnAname, null);
assertFalse(cells.size() > 0);
assertEquals(valueCname, handler.get(tableAname, rowAname, columnBname, null).get(0).value);
List<TCell> versions = handler.getVer(tableAname, rowAname, columnBname, MAXVERSIONS, null);
assertEquals(valueCname, versions.get(0).value);
assertEquals(valueBname, versions.get(1).value);
// Assert that changes were made to rowB
TRowResult rowResult2 = handler.getRow(tableAname, rowBname, null).get(0);
assertEquals(rowBname, rowResult2.row);
assertEquals(valueCname, rowResult2.columns.get(columnAname).value);
assertEquals(valueDname, rowResult2.columns.get(columnBname).value);
// Apply some deletes
handler.deleteAll(tableAname, rowAname, columnBname, null);
handler.deleteAllRow(tableAname, rowBname, null);
// Assert that the deletes were applied
int size = handler.get(tableAname, rowAname, columnBname, null).size();
assertEquals(0, size);
size = handler.getRow(tableAname, rowBname, null).size();
assertEquals(0, size);
// Try null mutation
List<Mutation> mutations = new ArrayList<Mutation>();
mutations.add(new Mutation(false, columnAname, null, true));
handler.mutateRow(tableAname, rowAname, mutations, null);
TRowResult rowResult3 = handler.getRow(tableAname, rowAname, null).get(0);
assertEquals(rowAname, rowResult3.row);
assertEquals(0, rowResult3.columns.get(columnAname).value.remaining());
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* Similar to testTableMutations(), except Mutations are applied with
* specific timestamps and data retrieval uses these timestamps to
* extract specific versions of data.
*
* @throws Exception
*/
public void doTestTableTimestampsAndColumns() throws Exception {
// Setup
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
handler.createTable(tableAname, getColumnDescriptors());
// Apply timestamped Mutations to rowA
long time1 = System.currentTimeMillis();
handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null);
Thread.sleep(1000);
// Apply timestamped BatchMutations for rowA and rowB
long time2 = System.currentTimeMillis();
handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null);
// Apply an overlapping timestamped mutation to rowB
handler.mutateRowTs(tableAname, rowBname, getMutations(), time2, null);
// the getVerTs is [inf, ts) so you need to increment one.
time1 += 1;
time2 += 2;
// Assert that the timestamp-related methods retrieve the correct data
assertEquals(2, handler.getVerTs(tableAname, rowAname, columnBname, time2,
MAXVERSIONS, null).size());
assertEquals(1, handler.getVerTs(tableAname, rowAname, columnBname, time1,
MAXVERSIONS, null).size());
TRowResult rowResult1 = handler.getRowTs(tableAname, rowAname, time1, null).get(0);
TRowResult rowResult2 = handler.getRowTs(tableAname, rowAname, time2, null).get(0);
// columnA was completely deleted
//assertTrue(Bytes.equals(rowResult1.columns.get(columnAname).value, valueAname));
assertEquals(rowResult1.columns.get(columnBname).value, valueBname);
assertEquals(rowResult2.columns.get(columnBname).value, valueCname);
// ColumnAname has been deleted, and will never be visible even with a getRowTs()
assertFalse(rowResult2.columns.containsKey(columnAname));
List<ByteBuffer> columns = new ArrayList<ByteBuffer>();
columns.add(columnBname);
rowResult1 = handler.getRowWithColumns(tableAname, rowAname, columns, null).get(0);
assertEquals(rowResult1.columns.get(columnBname).value, valueCname);
assertFalse(rowResult1.columns.containsKey(columnAname));
rowResult1 = handler.getRowWithColumnsTs(tableAname, rowAname, columns, time1, null).get(0);
assertEquals(rowResult1.columns.get(columnBname).value, valueBname);
assertFalse(rowResult1.columns.containsKey(columnAname));
// Apply some timestamped deletes
// this actually deletes _everything_.
// nukes everything in columnB: forever.
handler.deleteAllTs(tableAname, rowAname, columnBname, time1, null);
handler.deleteAllRowTs(tableAname, rowBname, time2, null);
// Assert that the timestamp-related methods retrieve the correct data
int size = handler.getVerTs(tableAname, rowAname, columnBname, time1, MAXVERSIONS, null).size();
assertEquals(0, size);
size = handler.getVerTs(tableAname, rowAname, columnBname, time2, MAXVERSIONS, null).size();
assertEquals(1, size);
// should be available....
assertEquals(handler.get(tableAname, rowAname, columnBname, null).get(0).value, valueCname);
assertEquals(0, handler.getRow(tableAname, rowBname, null).size());
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* Tests the four different scanner-opening methods (with and without
* a stoprow, with and without a timestamp).
*
* @throws Exception
*/
public void doTestTableScanners() throws Exception {
// Setup
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
handler.createTable(tableAname, getColumnDescriptors());
// Apply timestamped Mutations to rowA
long time1 = System.currentTimeMillis();
handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null);
// Sleep to assure that 'time1' and 'time2' will be different even with a
// coarse grained system timer.
Thread.sleep(1000);
// Apply timestamped BatchMutations for rowA and rowB
long time2 = System.currentTimeMillis();
handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null);
time1 += 1;
// Test a scanner on all rows and all columns, no timestamp
int scanner1 = handler.scannerOpen(tableAname, rowAname, getColumnList(true, true), null);
TRowResult rowResult1a = handler.scannerGet(scanner1).get(0);
assertEquals(rowResult1a.row, rowAname);
// This used to be '1'. I don't know why when we are asking for two columns
// and when the mutations above would seem to add two columns to the row.
// -- St.Ack 05/12/2009
assertEquals(rowResult1a.columns.size(), 1);
assertEquals(rowResult1a.columns.get(columnBname).value, valueCname);
TRowResult rowResult1b = handler.scannerGet(scanner1).get(0);
assertEquals(rowResult1b.row, rowBname);
assertEquals(rowResult1b.columns.size(), 2);
assertEquals(rowResult1b.columns.get(columnAname).value, valueCname);
assertEquals(rowResult1b.columns.get(columnBname).value, valueDname);
closeScanner(scanner1, handler);
// Test a scanner on all rows and all columns, with timestamp
int scanner2 = handler.scannerOpenTs(tableAname, rowAname, getColumnList(true, true), time1, null);
TRowResult rowResult2a = handler.scannerGet(scanner2).get(0);
assertEquals(rowResult2a.columns.size(), 1);
// column A deleted, does not exist.
//assertTrue(Bytes.equals(rowResult2a.columns.get(columnAname).value, valueAname));
assertEquals(rowResult2a.columns.get(columnBname).value, valueBname);
closeScanner(scanner2, handler);
// Test a scanner on the first row and first column only, no timestamp
int scanner3 = handler.scannerOpenWithStop(tableAname, rowAname, rowBname,
getColumnList(true, false), null);
closeScanner(scanner3, handler);
// Test a scanner on the first row and second column only, with timestamp
int scanner4 = handler.scannerOpenWithStopTs(tableAname, rowAname, rowBname,
getColumnList(false, true), time1, null);
TRowResult rowResult4a = handler.scannerGet(scanner4).get(0);
assertEquals(rowResult4a.columns.size(), 1);
assertEquals(rowResult4a.columns.get(columnBname).value, valueBname);
// Test scanner using a TScan object once with sortColumns False and once with sortColumns true
TScan scanNoSortColumns = new TScan();
scanNoSortColumns.setStartRow(rowAname);
scanNoSortColumns.setStopRow(rowBname);
int scanner5 = handler.scannerOpenWithScan(tableAname , scanNoSortColumns, null);
TRowResult rowResult5 = handler.scannerGet(scanner5).get(0);
assertEquals(rowResult5.columns.size(), 1);
assertEquals(rowResult5.columns.get(columnBname).value, valueCname);
TScan scanSortColumns = new TScan();
scanSortColumns.setStartRow(rowAname);
scanSortColumns.setStopRow(rowBname);
scanSortColumns = scanSortColumns.setSortColumns(true);
int scanner6 = handler.scannerOpenWithScan(tableAname ,scanSortColumns, null);
TRowResult rowResult6 = handler.scannerGet(scanner6).get(0);
assertEquals(rowResult6.sortedColumns.size(), 1);
assertEquals(rowResult6.sortedColumns.get(0).getCell().value, valueCname);
List<Mutation> rowBmutations = new ArrayList<Mutation>();
for (int i = 0; i < 20; i++) {
rowBmutations.add(new Mutation(false, asByteBuffer("columnA:" + i), valueCname, true));
}
ByteBuffer rowC = asByteBuffer("rowC");
handler.mutateRow(tableAname, rowC, rowBmutations, null);
TScan scanSortMultiColumns = new TScan();
scanSortMultiColumns.setStartRow(rowC);
scanSortMultiColumns = scanSortMultiColumns.setSortColumns(true);
int scanner7 = handler.scannerOpenWithScan(tableAname, scanSortMultiColumns, null);
TRowResult rowResult7 = handler.scannerGet(scanner7).get(0);
ByteBuffer smallerColumn = asByteBuffer("columnA:");
for (int i = 0; i < 20; i++) {
ByteBuffer currentColumn = rowResult7.sortedColumns.get(i).columnName;
assertTrue(Bytes.compareTo(smallerColumn.array(), currentColumn.array()) < 0);
smallerColumn = currentColumn;
}
// Teardown
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
/**
* For HBASE-2556
* Tests for GetTableRegions
*
* @throws Exception
*/
public void doTestGetTableRegions() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestGetTableRegions(handler);
}
public static void doTestGetTableRegions(Hbase.Iface handler)
throws Exception {
assertEquals(handler.getTableNames().size(), 0);
handler.createTable(tableAname, getColumnDescriptors());
assertEquals(handler.getTableNames().size(), 1);
List<TRegionInfo> regions = handler.getTableRegions(tableAname);
int regionCount = regions.size();
assertEquals("empty table should have only 1 region, " +
"but found " + regionCount, regionCount, 1);
LOG.info("Region found:" + regions.get(0));
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
regionCount = handler.getTableRegions(tableAname).size();
assertEquals("non-existing table should have 0 region, " +
"but found " + regionCount, regionCount, 0);
}
public void doTestFilterRegistration() throws Exception {
Configuration conf = UTIL.getConfiguration();
conf.set("hbase.thrift.filters", "MyFilter:filterclass");
ThriftServerRunner.registerFilters(conf);
Map<String, String> registeredFilters = ParseFilter.getAllFilters();
assertEquals("filterclass", registeredFilters.get("MyFilter"));
}
public void doTestGetRegionInfo() throws Exception {
ThriftServerRunner.HBaseHandler handler =
new ThriftServerRunner.HBaseHandler(UTIL.getConfiguration());
doTestGetRegionInfo(handler);
}
public static void doTestGetRegionInfo(Hbase.Iface handler) throws Exception {
// Create tableA and add two columns to rowA
handler.createTable(tableAname, getColumnDescriptors());
try {
handler.mutateRow(tableAname, rowAname, getMutations(), null);
byte[] searchRow = HRegionInfo.createRegionName(
TableName.valueOf(tableAname.array()), rowAname.array(),
HConstants.NINES, false);
TRegionInfo regionInfo = handler.getRegionInfo(ByteBuffer.wrap(searchRow));
assertTrue(Bytes.toStringBinary(regionInfo.getName()).startsWith(
Bytes.toStringBinary(tableAname)));
} finally {
handler.disableTable(tableAname);
handler.deleteTable(tableAname);
}
}
/**
*
* @return a List of ColumnDescriptors for use in creating a table. Has one
* default ColumnDescriptor and one ColumnDescriptor with fewer versions
*/
private static List<ColumnDescriptor> getColumnDescriptors() {
ArrayList<ColumnDescriptor> cDescriptors = new ArrayList<ColumnDescriptor>();
// A default ColumnDescriptor
ColumnDescriptor cDescA = new ColumnDescriptor();
cDescA.name = columnAname;
cDescriptors.add(cDescA);
// A slightly customized ColumnDescriptor (only 2 versions)
ColumnDescriptor cDescB = new ColumnDescriptor(columnBname, 2, "NONE",
false, "NONE", 0, 0, false, -1);
cDescriptors.add(cDescB);
return cDescriptors;
}
/**
*
* @param includeA whether or not to include columnA
* @param includeB whether or not to include columnB
* @return a List of column names for use in retrieving a scanner
*/
private List<ByteBuffer> getColumnList(boolean includeA, boolean includeB) {
List<ByteBuffer> columnList = new ArrayList<ByteBuffer>();
if (includeA) columnList.add(columnAname);
if (includeB) columnList.add(columnBname);
return columnList;
}
/**
*
* @return a List of Mutations for a row, with columnA having valueA
* and columnB having valueB
*/
private static List<Mutation> getMutations() {
List<Mutation> mutations = new ArrayList<Mutation>();
mutations.add(new Mutation(false, columnAname, valueAname, true));
mutations.add(new Mutation(false, columnBname, valueBname, true));
return mutations;
}
/**
*
* @return a List of BatchMutations with the following effects:
* (rowA, columnA): delete
* (rowA, columnB): place valueC
* (rowB, columnA): place valueC
* (rowB, columnB): place valueD
*/
private static List<BatchMutation> getBatchMutations() {
List<BatchMutation> batchMutations = new ArrayList<BatchMutation>();
// Mutations to rowA. You can't mix delete and put anymore.
List<Mutation> rowAmutations = new ArrayList<Mutation>();
rowAmutations.add(new Mutation(true, columnAname, null, true));
batchMutations.add(new BatchMutation(rowAname, rowAmutations));
rowAmutations = new ArrayList<Mutation>();
rowAmutations.add(new Mutation(false, columnBname, valueCname, true));
batchMutations.add(new BatchMutation(rowAname, rowAmutations));
// Mutations to rowB
List<Mutation> rowBmutations = new ArrayList<Mutation>();
rowBmutations.add(new Mutation(false, columnAname, valueCname, true));
rowBmutations.add(new Mutation(false, columnBname, valueDname, true));
batchMutations.add(new BatchMutation(rowBname, rowBmutations));
return batchMutations;
}
/**
* Asserts that the passed scanner is exhausted, and then closes
* the scanner.
*
* @param scannerId the scanner to close
* @param handler the HBaseHandler interfacing to HBase
* @throws Exception
*/
private void closeScanner(
int scannerId, ThriftServerRunner.HBaseHandler handler) throws Exception {
handler.scannerGet(scannerId);
handler.scannerClose(scannerId);
}
}
| HBASE-9610 TestThriftServer.testAll failing
git-svn-id: 949c06ec81f1cb709fd2be51dd530a930344d7b3@1526281 13f79535-47bb-0310-9956-ffa450edef68
| hbase-thrift/src/test/java/org/apache/hadoop/hbase/thrift/TestThriftServer.java | HBASE-9610 TestThriftServer.testAll failing |
|
Java | apache-2.0 | cb21da8b2120ea39d16b949ce4267bd44c3a427e | 0 | dslomov/bazel-windows,variac/bazel,dslomov/bazel-windows,kchodorow/bazel,dropbox/bazel,akira-baruah/bazel,safarmer/bazel,meteorcloudy/bazel,perezd/bazel,dropbox/bazel,Asana/bazel,akira-baruah/bazel,aehlig/bazel,ulfjack/bazel,perezd/bazel,davidzchen/bazel,ulfjack/bazel,Asana/bazel,LuminateWireless/bazel,dslomov/bazel-windows,juhalindfors/bazel-patches,hermione521/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,kchodorow/bazel,meteorcloudy/bazel,aehlig/bazel,cushon/bazel,spxtr/bazel,kchodorow/bazel,katre/bazel,spxtr/bazel,meteorcloudy/bazel,bazelbuild/bazel,hermione521/bazel,juhalindfors/bazel-patches,dslomov/bazel-windows,juhalindfors/bazel-patches,davidzchen/bazel,akira-baruah/bazel,ulfjack/bazel,katre/bazel,twitter-forks/bazel,twitter-forks/bazel,damienmg/bazel,meteorcloudy/bazel,LuminateWireless/bazel,werkt/bazel,dslomov/bazel,davidzchen/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,spxtr/bazel,juhalindfors/bazel-patches,werkt/bazel,cushon/bazel,dslomov/bazel,cushon/bazel,safarmer/bazel,werkt/bazel,ButterflyNetwork/bazel,damienmg/bazel,twitter-forks/bazel,meteorcloudy/bazel,snnn/bazel,dslomov/bazel,bazelbuild/bazel,variac/bazel,dslomov/bazel-windows,akira-baruah/bazel,perezd/bazel,kchodorow/bazel,ulfjack/bazel,Asana/bazel,ulfjack/bazel,LuminateWireless/bazel,bazelbuild/bazel,twitter-forks/bazel,aehlig/bazel,snnn/bazel,akira-baruah/bazel,dslomov/bazel,davidzchen/bazel,dropbox/bazel,variac/bazel,aehlig/bazel,snnn/bazel,kchodorow/bazel-1,meteorcloudy/bazel,Asana/bazel,safarmer/bazel,dropbox/bazel,aehlig/bazel,cushon/bazel,safarmer/bazel,perezd/bazel,spxtr/bazel,werkt/bazel,damienmg/bazel,snnn/bazel,kchodorow/bazel,Asana/bazel,werkt/bazel,perezd/bazel,spxtr/bazel,katre/bazel,kchodorow/bazel,damienmg/bazel,kchodorow/bazel-1,juhalindfors/bazel-patches,aehlig/bazel,hermione521/bazel,perezd/bazel,damienmg/bazel,variac/bazel,LuminateWireless/bazel,LuminateWireless/bazel,variac/bazel,dropbox/bazel,twitter-forks/bazel,werkt/bazel,ButterflyNetwork/bazel,safarmer/bazel,kchodorow/bazel-1,aehlig/bazel,kchodorow/bazel-1,bazelbuild/bazel,hermione521/bazel,snnn/bazel,damienmg/bazel,safarmer/bazel,kchodorow/bazel-1,davidzchen/bazel,variac/bazel,meteorcloudy/bazel,dropbox/bazel,Asana/bazel,katre/bazel,hermione521/bazel,hermione521/bazel,snnn/bazel,ulfjack/bazel,dslomov/bazel,juhalindfors/bazel-patches,ulfjack/bazel,damienmg/bazel,ButterflyNetwork/bazel,juhalindfors/bazel-patches,dslomov/bazel,perezd/bazel,twitter-forks/bazel,variac/bazel,katre/bazel,Asana/bazel,katre/bazel,snnn/bazel,kchodorow/bazel-1,spxtr/bazel,dslomov/bazel,kchodorow/bazel,cushon/bazel,LuminateWireless/bazel,davidzchen/bazel,cushon/bazel,davidzchen/bazel,dslomov/bazel-windows,bazelbuild/bazel,akira-baruah/bazel,spxtr/bazel | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.buildjar.javac;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import javax.annotation.Nullable;
import javax.annotation.processing.Processor;
/**
* Arguments to a single compilation performed by {@link BlazeJavacMain}.
*
* <p>This includes a subset of arguments to {@link javax.tools.JavaCompiler#getTask} and {@link
* javax.tools.StandardFileManager#setLocation} for a single compilation, with sensible defaults and
* a builder.
*/
@AutoValue
public abstract class BlazeJavacArguments {
/** The sources to compile. */
public abstract ImmutableList<Path> sourceFiles();
/** Javac options, not including location settings. */
public abstract ImmutableList<String> javacOptions();
/** The compilation classpath. */
public abstract ImmutableList<Path> classPath();
/** The compilation bootclasspath. */
public abstract ImmutableList<Path> bootClassPath();
/** The classpath to load processors from. */
public abstract ImmutableList<Path> processorPath();
/**
* Annotation processor classes. In production builds, processors are specified by string class
* name in {@link javacOptions}; this is used for tests that instantate processors directly.
*/
@Nullable
public abstract ImmutableList<Processor> processors();
/** The class output directory (-d). */
public abstract Path classOutput();
/** The generated source output directory (-s). */
@Nullable
public abstract Path sourceOutput();
public static Builder builder() {
return new AutoValue_BlazeJavacArguments.Builder()
.classPath(ImmutableList.of())
.classOutput(null)
.bootClassPath(ImmutableList.of())
.javacOptions(ImmutableList.of())
.sourceFiles(ImmutableList.of())
.processors(null)
.sourceOutput(null)
.processorPath(ImmutableList.of());
}
/** {@link BlazeJavacArguments}Builder. */
@AutoValue.Builder
public interface Builder {
Builder classPath(ImmutableList<Path> classPath);
Builder classOutput(Path classOutput);
Builder bootClassPath(ImmutableList<Path> bootClassPath);
Builder javacOptions(ImmutableList<String> javacOptions);
Builder sourceFiles(ImmutableList<Path> sourceFiles);
Builder processors(ImmutableList<Processor> processors);
Builder sourceOutput(Path sourceOutput);
Builder processorPath(ImmutableList<Path> processorPath);
BlazeJavacArguments build();
}
}
| src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/BlazeJavacArguments.java | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.buildjar.javac;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import javax.annotation.Nullable;
import javax.annotation.processing.Processor;
/**
* Arguments to a single compilation performed by {@link BlazeJavacMain}.
*
* <p>This includes a subset of arguments to {@link javax.tools.JavaCompiler#getTask} and {@link
* javax.tools.StandardFileManager#setLocation} for a single compilation, with sensible defaults and
* a builder.
*/
@AutoValue
public abstract class BlazeJavacArguments {
/** The sources to compile. */
public abstract ImmutableList<Path> sourceFiles();
/** Javac options, not including location settings. */
public abstract ImmutableList<String> javacOptions();
/** The compilation classpath. */
public abstract ImmutableList<Path> classPath();
/** The compilation bootclasspath. */
public abstract ImmutableList<Path> bootClassPath();
/** The classpath to load processors from. */
public abstract ImmutableList<Path> processorPath();
/**
* Annotation processor classes. In production builds, processors are specified by string class
* name in {@link javacOptions}; this is used for tests that instantate processors directly.
*/
@Nullable
public abstract ImmutableList<Processor> processors();
/** The class output directory (-d). */
public abstract Path classOutput();
/** The generated source output directory (-s). */
@Nullable
public abstract Path sourceOutput();
public static Builder builder() {
return new AutoValue_BlazeJavacArguments.Builder()
.classPath(ImmutableList.<Path>of())
.classOutput(null)
.bootClassPath(ImmutableList.<Path>of())
.javacOptions(ImmutableList.<String>of())
.sourceFiles(ImmutableList.<Path>of())
.processors(null)
.sourceOutput(null)
.processorPath(ImmutableList.<Path>of());
}
/** {@link BlazeJavacArguments}Builder. */
@AutoValue.Builder
public interface Builder {
Builder classPath(ImmutableList<Path> classPath);
Builder classOutput(Path classOutput);
Builder bootClassPath(ImmutableList<Path> bootClassPath);
Builder javacOptions(ImmutableList<String> javacOptions);
Builder sourceFiles(ImmutableList<Path> sourceFiles);
Builder processors(ImmutableList<Processor> processors);
Builder sourceOutput(Path sourceOutput);
Builder processorPath(ImmutableList<Path> processorPath);
BlazeJavacArguments build();
}
}
| Rollback of commit aad9b44898cf1562765755d475463145466ea7ae.
*** Reason for rollback ***
bazelbuild/bazel#2123 is fixed
*** Original change description ***
Add explicit type annotations in BlazeJavacArguments.java
Fixes bazel-tests for java 7 after commit 3c5e55ff8e058b624ce26e803ff00434c70d4b91
--
PiperOrigin-RevId: 144453400
MOS_MIGRATED_REVID=144453400
| src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/BlazeJavacArguments.java | Rollback of commit aad9b44898cf1562765755d475463145466ea7ae. |
|
Java | apache-2.0 | 32d5271cd57232a281a4b1eaa5566d14412195c1 | 0 | thusithathilina/carbon-transports,wggihan/carbon-transports,shafreenAnfar/carbon-transports,wso2/carbon-transports,chanakaudaya/carbon-transports | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.transport.file.connector.server;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.UriParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.messaging.CarbonMessage;
import org.wso2.carbon.messaging.CarbonMessageProcessor;
import org.wso2.carbon.messaging.StreamingCarbonMessage;
import org.wso2.carbon.messaging.exceptions.ServerConnectorException;
import org.wso2.carbon.transport.file.connector.server.exception.FileServerConnectorException;
import org.wso2.carbon.transport.file.connector.server.util.Constants;
import org.wso2.carbon.transport.file.connector.server.util.FileTransportUtils;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* Provides the capability to process a file and delete it afterwards.
*/
public class FileConsumer {
private static final Logger log = LoggerFactory.getLogger(FileConsumer.class);
private Map<String, String> fileProperties;
private FileSystemManager fsManager = null;
private String serviceName;
private CarbonMessageProcessor messageProcessor;
private String fileURI;
private FileObject fileObject;
private FileSystemOptions fso;
/**
* Time-out interval (in mill-seconds) to wait for the callback.
*/
private long timeOutInterval = 30000;
public FileConsumer(String id, Map<String, String> fileProperties,
CarbonMessageProcessor messageProcessor)
throws ServerConnectorException {
this.serviceName = id;
this.fileProperties = fileProperties;
this.messageProcessor = messageProcessor;
setupParams();
try {
StandardFileSystemManager fsm = new StandardFileSystemManager();
fsm.setConfiguration(getClass().getClassLoader().getResource("providers.xml"));
fsm.init();
fsManager = fsm;
} catch (FileSystemException e) {
throw new ServerConnectorException("Could not initialize File System Manager from " +
"the configuration: providers.xml", e);
}
fso = FileTransportUtils.attachFileSystemOptions(parseSchemeFileOptions(fileURI), fsManager);
try {
fileObject = fsManager.resolveFile(fileURI, fso);
} catch (FileSystemException e) {
throw new FileServerConnectorException("Failed to resolve fileURI: "
+ FileTransportUtils.maskURLPassword(fileURI), e);
}
}
/**
* Do the file processing operation for the given set of properties. Do the
* checks and pass the control to processFile method
*/
public void consume() throws FileServerConnectorException {
if (log.isDebugEnabled()) {
log.debug("Polling for directory or file : " +
FileTransportUtils.maskURLPassword(fileURI));
}
// If file/folder found proceed to the processing stage
try {
boolean isFileExists;
try {
isFileExists = fileObject.exists();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
+ FileTransportUtils.maskURLPassword(fileURI) + " exists. " + e);
}
boolean isFileReadable;
try {
isFileReadable = fileObject.isReadable();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
+ FileTransportUtils.maskURLPassword(fileURI) + " is readable. " + e);
}
if (isFileExists && isFileReadable) {
FileObject[] children = null;
try {
children = fileObject.getChildren();
} catch (FileSystemException ignored) {
if (log.isDebugEnabled()) {
log.debug("The file does not exist, or is not a folder, or an error " +
"has occurred when trying to list the children. File URI : "
+ FileTransportUtils.maskURLPassword(fileURI), ignored);
}
}
// if this is a file that would translate to a single message
if (children == null || children.length == 0) {
processFile(fileObject);
deleteFile(fileObject);
} else {
directoryHandler(children);
}
} else {
throw new FileServerConnectorException("Unable to access or read file or directory : "
+ FileTransportUtils.maskURLPassword(fileURI)
+ ". Reason: "
+ (isFileExists ? (isFileReadable ? "Unknown reason"
: "The file can not be read!") : "The file does not exist!"));
}
} finally {
try {
fileObject.close();
} catch (FileSystemException e) {
log.warn("Could not close file at URI: " + FileTransportUtils.maskURLPassword(fileURI), e);
}
}
if (log.isDebugEnabled()) {
log.debug("End : Scanning directory or file : " + FileTransportUtils.maskURLPassword(fileURI));
}
}
/**
* Setup the required transport parameters
*/
private void setupParams() throws ServerConnectorException {
fileURI = fileProperties.get(Constants.TRANSPORT_FILE_FILE_URI);
if (fileURI == null) {
throw new ServerConnectorException(Constants.TRANSPORT_FILE_FILE_URI + " is a " +
"mandatory parameter for " + Constants.PROTOCOL_NAME + " transport.");
}
if (fileURI.trim().equals("")) {
throw new ServerConnectorException(Constants.TRANSPORT_FILE_FILE_URI + " parameter " +
"cannot be empty for " + Constants.PROTOCOL_NAME + " transport.");
}
String timeOut = fileProperties.get(Constants.FILE_ACKNOWLEDGEMENT_TIME_OUT);
if (timeOut != null) {
try {
timeOutInterval = Long.parseLong(timeOut);
} catch (NumberFormatException e) {
log.error("Provided "+ Constants.FILE_ACKNOWLEDGEMENT_TIME_OUT +" is invalid. Using the default callback timeout, " +
timeOutInterval + " milliseconds", e);
}
}
}
private Map<String, String> parseSchemeFileOptions(String fileURI) {
String scheme = UriParser.extractScheme(fileURI);
if (scheme == null) {
return null;
}
HashMap<String, String> schemeFileOptions = new HashMap<>();
schemeFileOptions.put(Constants.SCHEME, scheme);
addOptions(scheme, schemeFileOptions);
return schemeFileOptions;
}
private void addOptions(String scheme, Map<String, String> schemeFileOptions) {
if (scheme.equals(Constants.SCHEME_SFTP)) {
for (Constants.SftpFileOption option : Constants.SftpFileOption.values()) {
String strValue = fileProperties.get(Constants.SFTP_PREFIX + option.toString());
if (strValue != null && !strValue.equals("")) {
schemeFileOptions.put(option.toString(), strValue);
}
}
}
}
/**
* Handle directory with chile elements
*
* @param children
* @return
* @throws FileSystemException
*/
private void directoryHandler(FileObject[] children) throws FileServerConnectorException {
// Sort the files
String strSortParam = fileProperties.get(Constants.FILE_SORT_PARAM);
if (strSortParam != null && !"NONE".equals(strSortParam)) {
log.debug("Starting to sort the files in folder: " + FileTransportUtils.maskURLPassword(fileURI));
String strSortOrder = fileProperties.get(Constants.FILE_SORT_ORDER);
boolean bSortOrderAscending = true;
if (strSortOrder != null) {
try {
bSortOrderAscending = Boolean.parseBoolean(strSortOrder);
} catch (RuntimeException re) {
log.warn(Constants.FILE_SORT_ORDER + " parameter should be either " +
"\"true\" or \"false\". Found: " + strSortOrder +
". Assigning default value \"true\".", re);
}
}
if (log.isDebugEnabled()) {
log.debug("Sorting the files by : " + strSortOrder + ". (" +
bSortOrderAscending + ")");
}
if (strSortParam.equals(Constants.FILE_SORT_VALUE_NAME) && bSortOrderAscending) {
Arrays.sort(children, new FileNameAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_NAME)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileNameDesComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_SIZE)
&& bSortOrderAscending) {
Arrays.sort(children, new FileSizeAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_SIZE)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileSizeDesComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
&& bSortOrderAscending) {
Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
}
if (log.isDebugEnabled()) {
log.debug("End sorting the files.");
}
}
for (FileObject child : children) {
processFile(child);
deleteFile(child);
//close the file system after processing
try {
child.close();
} catch (FileSystemException e) {
log.warn("Could not close the file: " + child.getName().getPath(), e);
}
}
}
/**
* Actual processing of the file/folder
*
* @param file
* @return
*/
private FileObject processFile(FileObject file) throws FileServerConnectorException {
FileContent content;
String fileURI;
String fileName = file.getName().getBaseName();
String filePath = file.getName().getPath();
fileURI = file.getName().getURI();
try {
content = file.getContent();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Could not read content of file at URI: "
+ FileTransportUtils.maskURLPassword(fileURI) + ". ", e);
}
InputStream inputStream;
try {
inputStream = content.getInputStream();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when trying to get " +
"input stream from file at URI :" + FileTransportUtils.maskURLPassword(fileURI), e);
}
CarbonMessage cMessage = new StreamingCarbonMessage(inputStream);
cMessage.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.PROTOCOL_NAME);
cMessage.setProperty(Constants.FILE_TRANSPORT_PROPERTY_SERVICE_NAME, serviceName);
cMessage.setHeader(Constants.FILE_PATH, filePath);
cMessage.setHeader(Constants.FILE_NAME, fileName);
cMessage.setHeader(Constants.FILE_URI, fileURI);
try {
cMessage.setHeader(Constants.FILE_LENGTH, Long.toString(content.getSize()));
cMessage.setHeader(Constants.LAST_MODIFIED, Long.toString(content.getLastModifiedTime()));
} catch (FileSystemException e) {
log.warn("Unable to set file length or last modified date header.", e);
}
FileServerConnectorCallback callback = new FileServerConnectorCallback();
try {
messageProcessor.receive(cMessage, callback);
} catch (Exception e) {
throw new FileServerConnectorException("Failed to send stream from file: "
+ FileTransportUtils.maskURLPassword(fileURI) + " to message processor. ", e);
}
try {
callback.waitTillDone(timeOutInterval);
} catch (InterruptedException e) {
throw new FileServerConnectorException("Error occurred while waiting for message " +
"processor to consume the file input stream. Input stream may be closed " +
"before the Message processor reads it. ", e);
}
return file;
}
/**
* Do the post processing actions
*
* @param fileObject
*/
private void deleteFile(FileObject fileObject) throws FileServerConnectorException {
if (log.isDebugEnabled()) {
log.debug("Deleting file :" + FileTransportUtils.
maskURLPassword(fileObject.getName().getBaseName()));
}
try {
if (!fileObject.delete()) {
throw new FileServerConnectorException("Could not delete file : "
+ FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
}
} catch (FileSystemException e) {
throw new FileServerConnectorException("Could not delete file : "
+ FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()), e);
}
}
/**
* Comparator classed used to sort the files according to user input
*/
static class FileNameAscComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
return o1.getName().compareTo(o2.getName());
}
}
static class FileLastmodifiedtimestampAscComparator
implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o1.getContent().getLastModifiedTime()
- o2.getContent().getLastModifiedTime();
} catch (FileSystemException e) {
log.warn("Unable to compare last modified timestamp of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileSizeAscComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o1.getContent().getSize() - o2.getContent().getSize();
} catch (FileSystemException e) {
log.warn("Unable to compare size of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileNameDesComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
return o2.getName().compareTo(o1.getName());
}
}
static class FileLastmodifiedtimestampDesComparator
implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o2.getContent().getLastModifiedTime()
- o1.getContent().getLastModifiedTime();
} catch (FileSystemException e) {
log.warn("Unable to compare last modified timestamp of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileSizeDesComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o2.getContent().getSize() - o1.getContent().getSize();
} catch (FileSystemException e) {
log.warn("Unable to compare size of the two files.", e);
}
return lDiff.intValue();
}
}
}
| file/org.wso2.carbon.transport.file/src/main/java/org/wso2/carbon/transport/file/connector/server/FileConsumer.java | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.transport.file.connector.server;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.UriParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.messaging.CarbonMessage;
import org.wso2.carbon.messaging.CarbonMessageProcessor;
import org.wso2.carbon.messaging.StreamingCarbonMessage;
import org.wso2.carbon.messaging.exceptions.ServerConnectorException;
import org.wso2.carbon.transport.file.connector.server.exception.FileServerConnectorException;
import org.wso2.carbon.transport.file.connector.server.util.Constants;
import org.wso2.carbon.transport.file.connector.server.util.FileTransportUtils;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* Provides the capability to process a file and delete it afterwards.
*/
public class FileConsumer {
private static final Logger log = LoggerFactory.getLogger(FileConsumer.class);
private Map<String, String> fileProperties;
private FileSystemManager fsManager = null;
private String serviceName;
private CarbonMessageProcessor messageProcessor;
private String fileURI;
private FileObject fileObject;
private FileSystemOptions fso;
/**
* Time-out interval (in mill-seconds) to wait for the callback.
*/
private long timeOutInterval = 30000;
public FileConsumer(String id, Map<String, String> fileProperties,
CarbonMessageProcessor messageProcessor)
throws ServerConnectorException {
this.serviceName = id;
this.fileProperties = fileProperties;
this.messageProcessor = messageProcessor;
setupParams();
try {
StandardFileSystemManager fsm = new StandardFileSystemManager();
fsm.setConfiguration(getClass().getClassLoader().getResource("providers.xml"));
fsm.init();
fsManager = fsm;
} catch (FileSystemException e) {
throw new ServerConnectorException("Could not initialize File System Manager from " +
"the configuration: providers.xml", e);
}
fso = FileTransportUtils.attachFileSystemOptions(parseSchemeFileOptions(fileURI), fsManager);
try {
fileObject = fsManager.resolveFile(fileURI, fso);
} catch (FileSystemException e) {
throw new FileServerConnectorException("Failed to resolve fileURI: "
+ FileTransportUtils.maskURLPassword(fileURI), e);
}
}
/**
* Do the file processing operation for the given set of properties. Do the
* checks and pass the control to processFile method
*/
public void consume() throws FileServerConnectorException {
if (log.isDebugEnabled()) {
log.debug("Polling for directory or file : " +
FileTransportUtils.maskURLPassword(fileURI));
}
// If file/folder found proceed to the processing stage
try {
boolean isFileExists;
try {
isFileExists = fileObject.exists();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
+ FileTransportUtils.maskURLPassword(fileURI) + " exists. " + e);
}
boolean isFileReadable;
try {
isFileReadable = fileObject.isReadable();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
+ FileTransportUtils.maskURLPassword(fileURI) + " is readable. " + e);
}
if (isFileExists && isFileReadable) {
FileObject[] children = null;
try {
children = fileObject.getChildren();
} catch (FileSystemException ignored) {
if (log.isDebugEnabled()) {
log.debug("The file does not exist, or is not a folder, or an error " +
"has occurred when trying to list the children. File URI : "
+ FileTransportUtils.maskURLPassword(fileURI), ignored);
}
}
// if this is a file that would translate to a single message
if (children == null || children.length == 0) {
processFile(fileObject);
deleteFile(fileObject);
} else {
directoryHandler(children);
}
} else {
throw new FileServerConnectorException("Unable to access or read file or directory : "
+ FileTransportUtils.maskURLPassword(fileURI)
+ ". Reason: "
+ (isFileExists ? (isFileReadable ? "Unknown reason"
: "The file can not be read!") : "The file does not exist!"));
}
} finally {
try {
fileObject.close();
} catch (FileSystemException e) {
log.warn("Could not close file at URI: " + FileTransportUtils.maskURLPassword(fileURI), e);
}
}
if (log.isDebugEnabled()) {
log.debug("End : Scanning directory or file : " + FileTransportUtils.maskURLPassword(fileURI));
}
}
/**
* Setup the required transport parameters
*/
private void setupParams() throws ServerConnectorException {
fileURI = fileProperties.get(Constants.TRANSPORT_FILE_FILE_URI);
if (fileURI == null) {
throw new ServerConnectorException(Constants.TRANSPORT_FILE_FILE_URI + " is a " +
"mandatory parameter for " + Constants.PROTOCOL_NAME + " transport.");
}
if (fileURI.trim().equals("")) {
throw new ServerConnectorException(Constants.TRANSPORT_FILE_FILE_URI + " parameter " +
"cannot be empty for " + Constants.PROTOCOL_NAME + " transport.");
}
String timeOut = fileProperties.get(Constants.FILE_ACKNOWLEDGEMENT_TIME_OUT);
try {
timeOutInterval = Long.parseLong(timeOut);
} catch (NumberFormatException e) {
log.error("Provided fileCallbackTimeOut is invalid. Using the default callback timeout, " +
timeOutInterval + " milliseconds", e);
}
}
private Map<String, String> parseSchemeFileOptions(String fileURI) {
String scheme = UriParser.extractScheme(fileURI);
if (scheme == null) {
return null;
}
HashMap<String, String> schemeFileOptions = new HashMap<>();
schemeFileOptions.put(Constants.SCHEME, scheme);
addOptions(scheme, schemeFileOptions);
return schemeFileOptions;
}
private void addOptions(String scheme, Map<String, String> schemeFileOptions) {
if (scheme.equals(Constants.SCHEME_SFTP)) {
for (Constants.SftpFileOption option : Constants.SftpFileOption.values()) {
String strValue = fileProperties.get(Constants.SFTP_PREFIX + option.toString());
if (strValue != null && !strValue.equals("")) {
schemeFileOptions.put(option.toString(), strValue);
}
}
}
}
/**
* Handle directory with chile elements
*
* @param children
* @return
* @throws FileSystemException
*/
private void directoryHandler(FileObject[] children) throws FileServerConnectorException {
// Sort the files
String strSortParam = fileProperties.get(Constants.FILE_SORT_PARAM);
if (strSortParam != null && !"NONE".equals(strSortParam)) {
log.debug("Starting to sort the files in folder: " + FileTransportUtils.maskURLPassword(fileURI));
String strSortOrder = fileProperties.get(Constants.FILE_SORT_ORDER);
boolean bSortOrderAscending = true;
if (strSortOrder != null) {
try {
bSortOrderAscending = Boolean.parseBoolean(strSortOrder);
} catch (RuntimeException re) {
log.warn(Constants.FILE_SORT_ORDER + " parameter should be either " +
"\"true\" or \"false\". Found: " + strSortOrder +
". Assigning default value \"true\".", re);
}
}
if (log.isDebugEnabled()) {
log.debug("Sorting the files by : " + strSortOrder + ". (" +
bSortOrderAscending + ")");
}
if (strSortParam.equals(Constants.FILE_SORT_VALUE_NAME) && bSortOrderAscending) {
Arrays.sort(children, new FileNameAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_NAME)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileNameDesComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_SIZE)
&& bSortOrderAscending) {
Arrays.sort(children, new FileSizeAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_SIZE)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileSizeDesComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
&& bSortOrderAscending) {
Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
} else if (strSortParam.equals(Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
&& !bSortOrderAscending) {
Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
}
if (log.isDebugEnabled()) {
log.debug("End sorting the files.");
}
}
for (FileObject child : children) {
processFile(child);
deleteFile(child);
//close the file system after processing
try {
child.close();
} catch (FileSystemException e) {
log.warn("Could not close the file: " + child.getName().getPath(), e);
}
}
}
/**
* Actual processing of the file/folder
*
* @param file
* @return
*/
private FileObject processFile(FileObject file) throws FileServerConnectorException {
FileContent content;
String fileURI;
String fileName = file.getName().getBaseName();
String filePath = file.getName().getPath();
fileURI = file.getName().getURI();
try {
content = file.getContent();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Could not read content of file at URI: "
+ FileTransportUtils.maskURLPassword(fileURI) + ". ", e);
}
InputStream inputStream;
try {
inputStream = content.getInputStream();
} catch (FileSystemException e) {
throw new FileServerConnectorException("Error occurred when trying to get " +
"input stream from file at URI :" + FileTransportUtils.maskURLPassword(fileURI), e);
}
CarbonMessage cMessage = new StreamingCarbonMessage(inputStream);
cMessage.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.PROTOCOL_NAME);
cMessage.setProperty(Constants.FILE_TRANSPORT_PROPERTY_SERVICE_NAME, serviceName);
cMessage.setHeader(Constants.FILE_PATH, filePath);
cMessage.setHeader(Constants.FILE_NAME, fileName);
cMessage.setHeader(Constants.FILE_URI, fileURI);
try {
cMessage.setHeader(Constants.FILE_LENGTH, Long.toString(content.getSize()));
cMessage.setHeader(Constants.LAST_MODIFIED, Long.toString(content.getLastModifiedTime()));
} catch (FileSystemException e) {
log.warn("Unable to set file length or last modified date header.", e);
}
FileServerConnectorCallback callback = new FileServerConnectorCallback();
try {
messageProcessor.receive(cMessage, callback);
} catch (Exception e) {
throw new FileServerConnectorException("Failed to send stream from file: "
+ FileTransportUtils.maskURLPassword(fileURI) + " to message processor. ", e);
}
try {
callback.waitTillDone(timeOutInterval);
} catch (InterruptedException e) {
throw new FileServerConnectorException("Error occurred while waiting for message " +
"processor to consume the file input stream. Input stream may be closed " +
"before the Message processor reads it. ", e);
}
return file;
}
/**
* Do the post processing actions
*
* @param fileObject
*/
private void deleteFile(FileObject fileObject) throws FileServerConnectorException {
if (log.isDebugEnabled()) {
log.debug("Deleting file :" + FileTransportUtils.
maskURLPassword(fileObject.getName().getBaseName()));
}
try {
if (!fileObject.delete()) {
throw new FileServerConnectorException("Could not delete file : "
+ FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
}
} catch (FileSystemException e) {
throw new FileServerConnectorException("Could not delete file : "
+ FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()), e);
}
}
/**
* Comparator classed used to sort the files according to user input
*/
static class FileNameAscComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
return o1.getName().compareTo(o2.getName());
}
}
static class FileLastmodifiedtimestampAscComparator
implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o1.getContent().getLastModifiedTime()
- o2.getContent().getLastModifiedTime();
} catch (FileSystemException e) {
log.warn("Unable to compare last modified timestamp of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileSizeAscComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o1.getContent().getSize() - o2.getContent().getSize();
} catch (FileSystemException e) {
log.warn("Unable to compare size of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileNameDesComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
return o2.getName().compareTo(o1.getName());
}
}
static class FileLastmodifiedtimestampDesComparator
implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o2.getContent().getLastModifiedTime()
- o1.getContent().getLastModifiedTime();
} catch (FileSystemException e) {
log.warn("Unable to compare last modified timestamp of the two files.", e);
}
return lDiff.intValue();
}
}
static class FileSizeDesComparator implements Comparator<FileObject>, Serializable {
private static final long serialVersionUID = 1;
@Override
public int compare(FileObject o1, FileObject o2) {
Long lDiff = 0L;
try {
lDiff = o2.getContent().getSize() - o1.getContent().getSize();
} catch (FileSystemException e) {
log.warn("Unable to compare size of the two files.", e);
}
return lDiff.intValue();
}
}
}
| Avoiding casting of null to long.
| file/org.wso2.carbon.transport.file/src/main/java/org/wso2/carbon/transport/file/connector/server/FileConsumer.java | Avoiding casting of null to long. |
|
Java | apache-2.0 | error: pathspec 'hsweb-system/hsweb-system-dynamic-form/hsweb-system-dynamic-form-service/hsweb-system-dynamic-form-service-simple/src/main/java/org/hswebframework/web/service/form/simple/SimpleDynamicFormOperationService.java' did not match any file(s) known to git
| 17756b0cccc19ecbb29306bfdef5c5433476dd63 | 1 | asiaon123/hsweb-framework,hs-web/hsweb-framework,asiaon123/hsweb-framework,asiaon123/hsweb-framework,hs-web/hsweb-framework,hs-web/hsweb-framework | package org.hswebframework.web.service.form.simple;
import org.hsweb.ezorm.core.Delete;
import org.hsweb.ezorm.core.Update;
import org.hsweb.ezorm.rdb.RDBDatabase;
import org.hsweb.ezorm.rdb.RDBQuery;
import org.hsweb.ezorm.rdb.RDBTable;
import org.hswebframework.web.NotFoundException;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.DeleteParamEntity;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.commons.entity.param.UpdateParamEntity;
import org.hswebframework.web.entity.form.DynamicFormEntity;
import org.hswebframework.web.service.form.DatabaseRepository;
import org.hswebframework.web.service.form.DynamicFormOperationService;
import org.hswebframework.web.service.form.DynamicFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import java.util.List;
@Service("dynamicFormOperationService")
@Transactional
public class SimpleDynamicFormOperationService implements DynamicFormOperationService {
private DynamicFormService dynamicFormService;
private DatabaseRepository databaseRepository;
@Autowired
public void setDynamicFormService(DynamicFormService dynamicFormService) {
this.dynamicFormService = dynamicFormService;
}
@Autowired
public void setDatabaseRepository(DatabaseRepository databaseRepository) {
this.databaseRepository = databaseRepository;
}
protected <T> RDBTable<T> getTable(String formId){
DynamicFormEntity entity= dynamicFormService.selectByPk(formId);
if(null==entity)throw new NotFoundException("表单不存在");
RDBDatabase database=entity.getDataSourceId()==null?databaseRepository.getDatabase(entity.getDataSourceId()):
databaseRepository.getDefaultDatabase();
return database.getTable(entity.getTableName());
};
@Override
public <T> PagerResult<T> selectPager(String formId, QueryParamEntity paramEntity) {
RDBTable<T> table=getTable(formId);
try {
RDBQuery<T> query=table.createQuery();
int total= query.setParam(paramEntity).total();
if(total==0){
return PagerResult.empty();
}
paramEntity.rePaging(total);
List<T> list =query.setParam(paramEntity).list();
return PagerResult.of(total,list);
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
@Override
public <T> List<T> select(String formId, QueryParamEntity paramEntity) {
RDBTable<T> table=getTable(formId);
try {
RDBQuery<T> query=table.createQuery();
return query.setParam(paramEntity).list();
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
@Override
public <T> T selectSingle(String formId, QueryParamEntity paramEntity) {
RDBTable<T> table=getTable(formId);
try {
RDBQuery<T> query=table.createQuery();
return query.setParam(paramEntity).single();
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
@Override
public int count(String formId, QueryParamEntity paramEntity) {
RDBTable table=getTable(formId);
try {
RDBQuery query=table.createQuery();
return query.setParam(paramEntity).total();
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
@Override
public <T> int update(String formId, UpdateParamEntity<T> paramEntity) {
RDBTable table=getTable(formId);
try {
Update<T> update=table.createUpdate();
return update.setParam(paramEntity).exec();
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
@Override
public int delete(String formId, DeleteParamEntity paramEntity) {
RDBTable table=getTable(formId);
try {
Delete delete=table.createDelete();
return delete.setParam(paramEntity).exec();
} catch (SQLException e) {
//todo custom exception
throw new RuntimeException(e);
}
}
}
| hsweb-system/hsweb-system-dynamic-form/hsweb-system-dynamic-form-service/hsweb-system-dynamic-form-service-simple/src/main/java/org/hswebframework/web/service/form/simple/SimpleDynamicFormOperationService.java | 新增动态表单操作实现
| hsweb-system/hsweb-system-dynamic-form/hsweb-system-dynamic-form-service/hsweb-system-dynamic-form-service-simple/src/main/java/org/hswebframework/web/service/form/simple/SimpleDynamicFormOperationService.java | 新增动态表单操作实现 |
|
Java | apache-2.0 | error: pathspec 'src/main/java/site/upload/PackageUpload.java' did not match any file(s) known to git
| c631fbfcdff876f70a01f2774e5c5470f02fe760 | 1 | cescoffier/wisdom-documentation,cescoffier/wisdom-documentation,cescoffier/wisdom-documentation | package site.upload;
import com.google.common.base.Strings;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisdom.api.DefaultController;
import org.wisdom.api.annotations.Attribute;
import org.wisdom.api.annotations.Controller;
import org.wisdom.api.annotations.Route;
import org.wisdom.api.configuration.ApplicationConfiguration;
import org.wisdom.api.http.FileItem;
import org.wisdom.api.http.HttpMethod;
import org.wisdom.api.http.Result;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Manages the upload of the documentation packages (mojo site, reference documentation, javadoc)
* It parses the version from the file name so it must be a valid Maven artifact using the convention
* artifactId-version.
*/
@Controller
public class PackageUpload extends DefaultController {
public final static String DOCUMENTATION_ARTIFACT_ID = "documentation";
public final static String MOJO_ARTIFACT_ID = "wisdom-maven-plugin";
public final static String MOJO_CLASSIFIER = "site";
public final static String JAVADOC_ARTIFACT_ID = "wisdom-framework";
public final static String JAVADOC_CLASSIFIER = "javadoc";
public final static Logger LOGGER = LoggerFactory.getLogger(PackageUpload.class);
@Requires
ApplicationConfiguration configuration;
File root;
private File referenceRoot;
private File javadocRoot;
private File mojoRoot;
private File storage;
@Validate
public void validate() {
root = new File(configuration.getBaseDir(), "documentation");
referenceRoot = new File(root, "reference");
javadocRoot = new File(root, "apidocs");
mojoRoot = new File(root, "wisdom-maven-plugin");
storage = new File(root, "storage");
LOGGER.debug("Creating {} : {}", referenceRoot.getAbsolutePath(), referenceRoot.mkdirs());
LOGGER.debug("Creating {} : {}", javadocRoot.getAbsolutePath(), javadocRoot.mkdirs());
LOGGER.debug("Creating {} : {}", mojoRoot.getAbsolutePath(), mojoRoot.mkdirs());
LOGGER.debug("Creating {} : {}", storage.getAbsolutePath(), storage.mkdirs());
}
@Route(method = HttpMethod.POST, uri = "/upload/reference")
public Result uploadReferenceDocumentation(@Attribute("upload") final FileItem upload) throws IOException {
String fileName = upload.name();
LOGGER.info("Uploading reference documentation : " + fileName);
if (!fileName.startsWith(DOCUMENTATION_ARTIFACT_ID)) {
return badRequest("The upload file does not look like the reference documentation");
}
final String version = fileName.substring(DOCUMENTATION_ARTIFACT_ID.length() + 1, fileName.length() - ".jar".length());
LOGGER.info("Extracting version from " + fileName + " : " + version);
if (Strings.isNullOrEmpty(version)) {
return badRequest("The upload file does not look like the reference documentation - malformed version");
}
// Start asynchronous from here
return async(
new Callable<Result>() {
@Override
public Result call() throws Exception {
File docRoot = new File(referenceRoot, version);
if (docRoot.isDirectory()) {
LOGGER.info("The directory {} already exists - cleanup", docRoot.getAbsolutePath());
FileUtils.deleteQuietly(docRoot);
}
LOGGER.debug("Creating {} : {}", docRoot.getAbsolutePath(), docRoot.mkdirs());
// Unpacking /assets/ to docRoot
unpack(upload.stream(), "assets/", docRoot);
store(upload);
return ok("Reference Documentation " + version + " uploaded");
}
}
);
}
@Route(method = HttpMethod.POST, uri = "/upload/mojo")
public Result uploadMojoDocumentation(@Attribute("upload") final FileItem upload) throws IOException {
String fileName = upload.name();
LOGGER.info("Uploading mojo documentation : " + fileName);
if (!fileName.startsWith(MOJO_ARTIFACT_ID)) {
return badRequest("The upload file does not look like the mojo documentation");
}
final String version = fileName.substring(MOJO_ARTIFACT_ID.length() + 1,
fileName.length() - ("-" + MOJO_CLASSIFIER + ".jar").length());
LOGGER.info("Extracting version from " + fileName + " : " + version);
if (Strings.isNullOrEmpty(version)) {
return badRequest("The upload file does not look like the mojo documentation - malformed version");
}
// Start asynchronous from here
return async(
new Callable<Result>() {
@Override
public Result call() throws Exception {
File docRoot = new File(mojoRoot, version);
if (docRoot.isDirectory()) {
LOGGER.info("The directory {} already exists - cleanup", docRoot.getAbsolutePath());
FileUtils.deleteQuietly(docRoot);
}
LOGGER.debug("Creating {} : {}", docRoot.getAbsolutePath(), docRoot.mkdirs());
// No prefix.
unpack(upload.stream(), "", docRoot);
store(upload);
return ok("Mojo Documentation " + version + " uploaded");
}
}
);
}
@Route(method = HttpMethod.POST, uri = "/upload/javadoc")
public Result uploadJavadoc(@Attribute("upload") final FileItem upload) throws IOException {
String fileName = upload.name();
LOGGER.info("Uploading JavaDoc : " + fileName);
if (!fileName.startsWith(JAVADOC_ARTIFACT_ID)) {
return badRequest("The upload file does not look like the JavaDoc package");
}
final String version = fileName.substring(JAVADOC_ARTIFACT_ID.length() + 1,
fileName.length() - ("-" + JAVADOC_CLASSIFIER + ".jar").length());
LOGGER.info("Extracting version from " + fileName + " : " + version);
if (Strings.isNullOrEmpty(version)) {
return badRequest("The upload file does not look like the JavaDoc package - malformed version");
}
// Start asynchronous from here
return async(
new Callable<Result>() {
@Override
public Result call() throws Exception {
File docRoot = new File(javadocRoot, version);
if (docRoot.isDirectory()) {
LOGGER.info("The directory {} already exists - cleanup", docRoot.getAbsolutePath());
FileUtils.deleteQuietly(docRoot);
}
LOGGER.debug("Creating {} : {}", docRoot.getAbsolutePath(), docRoot.mkdirs());
// No prefix.
unpack(upload.stream(), "", docRoot);
store(upload);
return ok("JavaDoc " + version + " uploaded");
}
}
);
}
private void unpack(InputStream stream, String prefix, File destination) throws IOException {
try {
ZipInputStream zis = new ZipInputStream(stream);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String entryName = ze.getName();
if ((prefix == null || entryName.startsWith(prefix)) && !entryName.endsWith("/")) {
String stripped;
if (prefix != null) {
stripped = entryName.substring(prefix.length());
} else {
stripped = entryName;
}
LOGGER.info("Extracting " + entryName + " -> " + destination + File.separator + stripped + "...");
File f = new File(destination + File.separator + stripped);
f.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(f);
int len;
byte buffer[] = new byte[1024];
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} finally {
IOUtils.closeQuietly(stream);
}
}
private void store(FileItem upload) throws IOException {
LOGGER.info("Storing " + upload.name());
File stored = new File(storage, upload.name());
FileUtils.writeByteArrayToFile(stored, upload.bytes());
}
}
| src/main/java/site/upload/PackageUpload.java | Provide documentation upload facilities
Signed-off-by: Clement Escoffier <[email protected]>
| src/main/java/site/upload/PackageUpload.java | Provide documentation upload facilities |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/conger/test/ExceptionTest.java' did not match any file(s) known to git
| 3368778bff2f4ae353dcdee152e13fdbe26bb41b | 1 | hellojinjie/try | package com.conger.test;
public class ExceptionTest {
public static void main(String[] args) {
System.out.println(new Exception().getStackTrace()[0]);
}
}
| src/main/java/com/conger/test/ExceptionTest.java | test exception stacktrace | src/main/java/com/conger/test/ExceptionTest.java | test exception stacktrace |
|
Java | apache-2.0 | error: pathspec 'main/src/com/pathtomani/managers/input/Mover.java' did not match any file(s) known to git
| 6624c4d9361b089d1ee932edee3157c3c12e013d | 1 | BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani | /*
* Copyright 2016 BurntGameProductions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pathtomani.managers.input;
import com.badlogic.gdx.math.Vector2;
import com.pathtomani.common.ManiMath;
import com.pathtomani.game.ManiGame;
import com.pathtomani.entities.planet.Planet;
import com.pathtomani.entities.ship.ManiShip;
import com.pathtomani.common.Const;
public class Mover {
public static final float MIN_MOVE_AAD = 2f;
public static final float MIN_ANGLE_TO_ACC = 5f;
public static final float MIN_PLANET_MOVE_AAD = 2f;
public static final float MAX_ABS_SPD_DEV = .1f;
public static final float MAX_REL_SPD_DEV = .05f;
private final BigObjAvoider myBigObjAvoider;
private final SmallObjAvoider mySmallObjAvoider;
private boolean myUp;
private boolean myLeft;
private boolean myRight;
private Vector2 myDesiredSpd;
public Mover() {
myBigObjAvoider = new BigObjAvoider();
mySmallObjAvoider = new SmallObjAvoider();
myDesiredSpd = new Vector2();
}
public void update(ManiGame game, ManiShip ship, Vector2 dest, Planet np,
float maxIdleDist, boolean hasEngine, boolean avoidBigObjs, float desiredSpdLen, boolean stopNearDest,
Vector2 destSpd) {
myUp = false;
myLeft = false;
myRight = false;
if (!hasEngine || dest == null) return;
Vector2 shipPos = ship.getPosition();
float toDestLen = shipPos.dst(dest);
if (toDestLen < maxIdleDist) {
if (!stopNearDest) return;
myDesiredSpd.set(destSpd);
} else {
updateDesiredSpd(game, ship, dest, toDestLen, stopNearDest, np, avoidBigObjs, desiredSpdLen, destSpd);
}
Vector2 shipSpd = ship.getSpd();
float spdDeviation = shipSpd.dst(myDesiredSpd);
if (spdDeviation < MAX_ABS_SPD_DEV || spdDeviation < MAX_REL_SPD_DEV * shipSpd.len()) return;
float shipAngle = ship.getAngle();
float rotSpd = ship.getRotSpd();
float rotAcc = ship.getRotAcc();
float desiredAngle = ManiMath.angle(shipSpd, myDesiredSpd);
float angleDiff = ManiMath.angleDiff(desiredAngle, shipAngle);
myUp = angleDiff < MIN_ANGLE_TO_ACC;
Boolean ntt = needsToTurn(shipAngle, desiredAngle, rotSpd, rotAcc, MIN_MOVE_AAD);
if (ntt != null) {
if (ntt) myRight = true; else myLeft = true;
}
}
private void updateDesiredSpd(ManiGame game, ManiShip ship, Vector2 dest, float toDestLen, boolean stopNearDest,
Planet np, boolean avoidBigObjs, float desiredSpdLen, Vector2 destSpd)
{
float toDestAngle = getToDestAngle(game, ship, dest, avoidBigObjs, np);
if (stopNearDest) {
float tangentSpd = ManiMath.project(ship.getSpd(), toDestAngle);
float turnWay = tangentSpd * ship.calcTimeToTurn(toDestAngle + 180);
float breakWay = tangentSpd * tangentSpd / ship.getAcc() / 2;
boolean needsToBreak = toDestLen < .5f * tangentSpd + turnWay + breakWay;
if (needsToBreak) {
myDesiredSpd.set(destSpd);
return;
}
}
ManiMath.fromAl(myDesiredSpd, toDestAngle, desiredSpdLen);
}
public void rotateOnIdle(ManiShip ship, Planet np, Vector2 dest, boolean stopNearDest, float maxIdleDist) {
if (isActive() || dest == null) return;
Vector2 shipPos = ship.getPosition();
float shipAngle = ship.getAngle();
float toDestLen = shipPos.dst(dest);
float desiredAngle;
float allowedAngleDiff;
boolean nearFinalDest = stopNearDest && toDestLen < maxIdleDist;
float dstToPlanet = np.getPos().dst(shipPos);
if (nearFinalDest) {
if (np.getFullHeight() < dstToPlanet) return; // stopping in space, don't care of angle
// stopping on planet
desiredAngle = ManiMath.angle(np.getPos(), shipPos);
allowedAngleDiff = MIN_PLANET_MOVE_AAD;
} else {
// flying somewhere
if (dstToPlanet < np.getFullHeight() + Const.ATM_HEIGHT) return; // near planet, don't care of angle
desiredAngle = ManiMath.angle(ship.getSpd());
allowedAngleDiff = MIN_MOVE_AAD;
}
Boolean ntt = needsToTurn(shipAngle, desiredAngle, ship.getRotSpd(), ship.getRotAcc(), allowedAngleDiff);
if (ntt != null) {
if (ntt) myRight = true; else myLeft = true;
}
}
private float getToDestAngle(ManiGame game, ManiShip ship, Vector2 dest, boolean avoidBigObjs, Planet np) {
Vector2 shipPos = ship.getPosition();
float toDestAngle = ManiMath.angle(shipPos, dest);
if (avoidBigObjs) {
toDestAngle = myBigObjAvoider.avoid(game, shipPos, dest, toDestAngle);
}
toDestAngle = mySmallObjAvoider.avoid(game, ship, toDestAngle, np);
return toDestAngle;
}
public static Boolean needsToTurn(float angle, float destAngle, float rotSpd, float rotAcc, float allowedAngleDiff) {
if (ManiMath.angleDiff(destAngle, angle) < allowedAngleDiff || rotAcc == 0) return null;
float breakWay = rotSpd * rotSpd / rotAcc / 2;
float angleAfterBreak = angle + breakWay * ManiMath.toInt(rotSpd > 0);
float relAngle = ManiMath.norm(angle - destAngle);
float relAngleAfterBreak = ManiMath.norm(angleAfterBreak - destAngle);
if (relAngle > 0 == relAngleAfterBreak > 0) return relAngle < 0;
return relAngle > 0;
}
public boolean isUp() {
return myUp;
}
public boolean isLeft() {
return myLeft;
}
public boolean isRight() {
return myRight;
}
public boolean isActive() {
return myUp || myLeft || myRight;
}
public BigObjAvoider getBigObjAvoider() {
return myBigObjAvoider;
}
}
| main/src/com/pathtomani/managers/input/Mover.java | Moving files to Managers.
| main/src/com/pathtomani/managers/input/Mover.java | Moving files to Managers. |
|
Java | apache-2.0 | error: pathspec 'app/src/main/java/co/gobd/tracker/network/RegisterApi.java' did not match any file(s) known to git
| e558a96b717ca05c1fe0ba0c73215878e9e25d66 | 1 | NerdCats/SwatKat | package co.gobd.tracker.network;
/**
* Created by fahad on 4/26/16.
*/
public interface RegisterApi {
}
| app/src/main/java/co/gobd/tracker/network/RegisterApi.java | Adds register endpoint to config and a RegisterApi
| app/src/main/java/co/gobd/tracker/network/RegisterApi.java | Adds register endpoint to config and a RegisterApi |
|
Java | apache-2.0 | error: pathspec 'feluca-core/src/main/java/org/shanbo/feluca/node/leader/LeaderModule.java' did not match any file(s) known to git
| def74c0c727c65d8ce59e0ba33305d360d605dbb | 1 | lgnlgn/feluca,lgnlgn/feluca | package org.shanbo.feluca.node.leader;
import org.shanbo.feluca.node.RoleModule;
public class LeaderModule extends RoleModule{
}
| feluca-core/src/main/java/org/shanbo/feluca/node/leader/LeaderModule.java | leader | feluca-core/src/main/java/org/shanbo/feluca/node/leader/LeaderModule.java | leader |
|
Java | apache-2.0 | error: pathspec 'proteus/src/main/java/com/treelogic/proteus/flink/sink/WebsocketSink.java' did not match any file(s) known to git
| 0f9b308f6d2a7f12977195f6847c371e296bedde | 1 | proteus-h2020/proteus-backend,proteus-h2020/proteus-backend | package com.treelogic.proteus.flink.sink;
public class WebsocketSink {
}
| proteus/src/main/java/com/treelogic/proteus/flink/sink/WebsocketSink.java | Add skeleton for flink classes
| proteus/src/main/java/com/treelogic/proteus/flink/sink/WebsocketSink.java | Add skeleton for flink classes |
|
Java | apache-2.0 | error: pathspec 'src/main/java/de/slackspace/openkeepass/stream/HashedBlockInputStream.java' did not match any file(s) known to git
| 142a914c95467b4ec522365f7192a4618e5f77f5 | 1 | knowhowlab/openkeepass,cternes/openkeepass | package de.slackspace.openkeepass.stream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;
import de.slackspace.openkeepass.util.ByteUtil;
public class HashedBlockInputStream extends InputStream {
private final static int HASH_SIZE = 32;
private InputStream baseStream;
private int bufferPos = 0;
private byte[] buffer = new byte[0];
private long bufferIndex = 0;
private boolean atEnd = false;
public HashedBlockInputStream(InputStream is) {
baseStream = is;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int offset, int length) throws IOException {
if (atEnd)
return -1;
int remaining = length;
while (remaining > 0) {
if (bufferPos == buffer.length) {
// Get more from the source into the buffer
if (!ReadHashedBlock()) {
return length - remaining;
}
}
// Copy from buffer out
int copyLen = Math.min(buffer.length - bufferPos, remaining);
System.arraycopy(buffer, bufferPos, b, offset, copyLen);
offset += copyLen;
bufferPos += copyLen;
remaining -= copyLen;
}
return length;
}
/**
* @return false, when the end of the source stream is reached
* @throws IOException
*/
private boolean ReadHashedBlock() throws IOException {
if (atEnd)
return false;
bufferPos = 0;
long index = ByteUtil.readUnsignedInt(baseStream);
if (index != bufferIndex) {
throw new IOException("Invalid data format");
}
bufferIndex++;
byte[] storedHash = new byte[32];
IOUtils.read(baseStream, storedHash);
if (storedHash == null || storedHash.length != HASH_SIZE) {
throw new IOException("Invalid data format");
}
int bufferSize = ByteUtil.readInt(baseStream);
if (bufferSize < 0) {
throw new IOException("Invalid data format");
}
if (bufferSize == 0) {
for (int hash = 0; hash < HASH_SIZE; hash++) {
if (storedHash[hash] != 0) {
throw new IOException("Invalid data format");
}
}
atEnd = true;
buffer = new byte[0];
return false;
}
buffer = new byte[bufferSize];
IOUtils.read(baseStream, buffer);
if (buffer == null || buffer.length != bufferSize) {
throw new IOException("Invalid data format");
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IOException("SHA-256 not implemented here.");
}
byte[] computedHash = md.digest(buffer);
if (computedHash == null || computedHash.length != HASH_SIZE) {
throw new IOException("Hash wrong size");
}
if (!Arrays.equals(storedHash, computedHash)) {
throw new IOException("Hashes didn't match.");
}
return true;
}
@Override
public long skip(long n) throws IOException {
return 0;
}
@Override
public int read() throws IOException {
if (atEnd)
return -1;
if (bufferPos == buffer.length) {
if (!ReadHashedBlock())
return -1;
}
int output = buffer[bufferPos];
bufferPos++;
return output;
}
@Override
public void close() throws IOException {
baseStream.close();
}
}
| src/main/java/de/slackspace/openkeepass/stream/HashedBlockInputStream.java | Added hashed block inputStream
| src/main/java/de/slackspace/openkeepass/stream/HashedBlockInputStream.java | Added hashed block inputStream |
|
Java | apache-2.0 | error: pathspec 'src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java' did not match any file(s) known to git
| 55a2df687be219e127614f1b19ba9e395e6bb56a | 1 | ContaAzul/redisson,jackygurui/redisson,zhoffice/redisson,mrniko/redisson,redisson/redisson | /**
* Copyright 2014 Nikita Koksharov, Nickolay Borbit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.connection.balancer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.redisson.connection.ClientConnectionsEntry;
import org.redisson.misc.URIBuilder;
import io.netty.util.internal.PlatformDependent;
/**
* Weighted Round Robin balancer.
*
* @author Nikita Koksharov
*
*/
public class WeightedRoundRobinBalancer implements LoadBalancer {
static class WeightEntry {
final int weight;
int weightCounter;
WeightEntry(int weight) {
this.weight = weight;
this.weightCounter = weight;
}
public boolean isWeightCounterZero() {
return weightCounter == 0;
}
public void decWeightCounter() {
weightCounter--;
}
public void resetWeightCounter() {
weightCounter = weight;
}
}
private final AtomicInteger index = new AtomicInteger(-1);
private final Map<InetSocketAddress, WeightEntry> weights = PlatformDependent.newConcurrentHashMap();
private final int defaultWeight;
/**
* Creates weighted round robin balancer.
*
* @param weights - weight mapped by slave node addr in <code>host:port</code> format
* @param defaultWeight - default weight value assigns to slaves not defined in weights map
*/
public WeightedRoundRobinBalancer(Map<String, Integer> weights, int defaultWeight) {
for (Entry<String, Integer> entry : weights.entrySet()) {
URI uri = URIBuilder.create(entry.getKey());
InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
if (entry.getValue() <= 0) {
throw new IllegalArgumentException("Weight can't be less than or equal zero");
}
this.weights.put(addr, new WeightEntry(entry.getValue()));
}
if (defaultWeight <= 0) {
throw new IllegalArgumentException("Weight can't be less than or equal zero");
}
this.defaultWeight = defaultWeight;
}
private Set<InetSocketAddress> getAddresses(List<ClientConnectionsEntry> clients) {
Set<InetSocketAddress> result = new HashSet<InetSocketAddress>();
for (ClientConnectionsEntry entry : clients) {
if (entry.isFreezed()) {
continue;
}
result.add(entry.getClient().getAddr());
}
return result;
}
@Override
public ClientConnectionsEntry getEntry(List<ClientConnectionsEntry> clients) {
Set<InetSocketAddress> addresses = getAddresses(clients);
if (!addresses.equals(weights.keySet())) {
Set<InetSocketAddress> newAddresses = new HashSet<InetSocketAddress>(addresses);
newAddresses.removeAll(weights.keySet());
for (InetSocketAddress addr : newAddresses) {
weights.put(addr, new WeightEntry(defaultWeight));
}
}
Map<InetSocketAddress, WeightEntry> weightsCopy = new HashMap<InetSocketAddress, WeightEntry>(weights);
List<ClientConnectionsEntry> clientsCopy = new ArrayList<ClientConnectionsEntry>();
synchronized (this) {
for (Iterator<WeightEntry> iterator = weightsCopy.values().iterator(); iterator.hasNext();) {
WeightEntry entry = iterator.next();
if (entry.isWeightCounterZero()) {
iterator.remove();
}
}
if (weightsCopy.isEmpty()) {
for (WeightEntry entry : weights.values()) {
entry.resetWeightCounter();
}
weightsCopy = weights;
}
for (InetSocketAddress addr : weightsCopy.keySet()) {
for (ClientConnectionsEntry clientConnectionsEntry : clients) {
if (clientConnectionsEntry.getClient().getAddr().equals(addr)
&& !clientConnectionsEntry.isFreezed()) {
clientsCopy.add(clientConnectionsEntry);
break;
}
}
}
int ind = Math.abs(index.incrementAndGet() % clientsCopy.size());
ClientConnectionsEntry entry = clientsCopy.get(ind);
WeightEntry weightEntry = weights.get(entry.getClient().getAddr());
weightEntry.decWeightCounter();
return entry;
}
}
}
| src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java | WeightedRoundRobinBalancer added. #344
| src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java | WeightedRoundRobinBalancer added. #344 |
|
Java | apache-2.0 | error: pathspec 'src/main/java/net/finmath/finitedifference/experimental/LocalVolatilityTheta.java' did not match any file(s) known to git
| dfe2b41b56dd2eab8f912de2448632cd25b6cf43 | 1 | finmath/finmath-lib,finmath/finmath-lib | package net.finmath.finitedifference.experimental;
import org.apache.commons.math3.linear.*;
/**
* Implementation of the Theta-scheme for a one-dimensional local volatility model (still experimental).
*
* @author Ralph Rudd
* @author Christian Fries
* @author Jörg Kienitz
* @version 1.0
*/
public class LocalVolatilityTheta {
// Model Parameters
private double volatility = 0.4;
private double riskFreeRate = 0.06;
private double alpha = 0.9;
private double localVolatility(double stockPrice, double currentTime) {
return volatility * Math.pow(stockPrice, alpha - 1);
}
// Option Parameters
private double optionStrike = 40;
private double optionMaturity = 1;
// Mesh Parameters
private double minimumStock = 0;
private double maximumStock = 160;
private int numStockSteps = 160;
private int numTimeSteps = 80;
private double deltaStock = (maximumStock - minimumStock) / numStockSteps;
private double deltaTau = optionMaturity / numTimeSteps;
// Algorithm Parameters
private double theta = 0.5;
// Call Option Boundary Conditions
/*private double V_T(double stockPrice) {
return Math.max(stockPrice - optionStrike, 0);
}
private double V_0(double stockPrice, double currentTime) {
return 0;
}
private double V_inf(double stockPrice, double currentTime) {
return stockPrice - optionStrike * Math.exp(-riskFreeRate*(optionMaturity - currentTime));
}*/
// Put Option Boundary Conditions
private double V_terminal(double stockPrice) {
return Math.max(optionStrike - stockPrice, 0);
}
private double V_minimumStock(double stockPrice, double currentTime) {
return optionStrike * Math.exp(-riskFreeRate*(optionMaturity - currentTime)) - stockPrice;
}
private double V_maximumStock(double stockPrice, double currentTime) {
return 0;
}
// Time-reversed Boundary Conditions
private double U_initial(double stockPrice) {return V_terminal(stockPrice); }
private double U_minimumStock(double stockPrice, double tau) {
return V_minimumStock(stockPrice, optionMaturity - tau);
}
private double U_maximumStock(double stockPrice, double tau) {
return V_maximumStock(stockPrice, optionMaturity - tau);
}
public double[][] solve() {
// Create interior spatial array of stock prices
int len = numStockSteps - 1;
double[] stock = new double[len];
for (int i = 0; i < len; i++){
stock[i] = minimumStock + (i + 1) * deltaStock;
}
// Create time-reversed tau array
double[] tau = new double[numTimeSteps + 1];
for (int i = 0; i < numTimeSteps + 1; i++) {
tau[i] = i * deltaTau;
}
// Create constant matrices
RealMatrix eye = MatrixUtils.createRealIdentityMatrix(len);
RealMatrix D1 = MatrixUtils.createRealMatrix(len, len);
RealMatrix D2 = MatrixUtils.createRealMatrix(len, len);
RealMatrix T1 = MatrixUtils.createRealMatrix(len, len);
RealMatrix T2 = MatrixUtils.createRealMatrix(len, len);
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (i == j) {
D1.setEntry(i, j, minimumStock/deltaStock + (i + 1));
D2.setEntry(i, j, Math.pow(minimumStock/deltaStock + (i + 1), 2));
T2.setEntry(i, j, -2);
} else if (i == j - 1) {
T1.setEntry(i, j, 1);
T2.setEntry(i, j, 1);
} else if (i == j + 1) {
T1.setEntry(i, j, -1);
T2.setEntry(i, j, 1);
} else {
D1.setEntry(i, j, 0);
D2.setEntry(i, j, 0);
T1.setEntry(i, j, 0);
T2.setEntry(i, j, 0);
}
}
}
RealMatrix F1 = eye.scalarMultiply(1 - riskFreeRate * deltaTau);
RealMatrix F2 = D1.scalarMultiply(0.5 * riskFreeRate * deltaTau).multiply(T1);
RealMatrix F3 = D2.scalarMultiply(0.5 * deltaTau).multiply(T2);
RealMatrix G1 = eye.scalarMultiply(1 + riskFreeRate * deltaTau);
RealMatrix G2 = F2.scalarMultiply(-1);
RealMatrix G3 = F3.scalarMultiply(-1);
// Initialize boundary and solution vectors
RealMatrix b = MatrixUtils.createRealMatrix(len, 1);
RealMatrix b2 = MatrixUtils.createRealMatrix(len, 1);
RealMatrix U = MatrixUtils.createRealMatrix(len, 1);
for (int i = 0; i < len; i++) {
b.setEntry(i,0,0);
b2.setEntry(i, 0, 0);
U.setEntry(i,1, U_initial(stock[i]));
}
// Theta finite difference method
for (int m = 0; m < numTimeSteps; m++) {
double[] sigma = new double[len];
double[] sigma2 = new double[len];
for (int i = 0; i < len; i++) {
sigma[i] = localVolatility(minimumStock + (i + 1) * deltaStock,
optionMaturity - m * deltaTau);
sigma2[i] = localVolatility(minimumStock + (i + 1) * deltaStock,
optionMaturity - (m + 1) * deltaTau);
}
RealMatrix Sigma = MatrixUtils.createRealDiagonalMatrix(sigma);
RealMatrix Sigma2 = MatrixUtils.createRealDiagonalMatrix(sigma2);
RealMatrix F = F1.add(F2).add(Sigma.multiply(F3));
RealMatrix G = G1.add(G2).add(Sigma2.multiply(G3));
RealMatrix H = G.scalarMultiply(theta).add(eye.scalarMultiply(1 - theta));
DecompositionSolver solver = new LUDecomposition(H).getSolver();
double Sl = (minimumStock / deltaStock + 1);
double Su = (maximumStock / deltaStock - 1);
double vl = localVolatility(minimumStock + deltaStock,
optionMaturity - m * deltaTau);
double vu = localVolatility(maximumStock - deltaStock,
optionMaturity - m * deltaTau);
double vl2 = localVolatility(minimumStock + deltaStock,
optionMaturity - (m + 1) * deltaTau);
double vu2 = localVolatility(maximumStock - deltaStock,
optionMaturity - (m + 1) * deltaTau);
b.setEntry(0,0,
0.5 * deltaTau * Sl * (vl * Sl - riskFreeRate) * U_minimumStock(minimumStock, tau[m]));
b.setEntry(len - 1, 0,
0.5 * deltaTau * Su * (vu * Su - riskFreeRate) * U_maximumStock(maximumStock, tau[m]));
b2.setEntry(0,0,
0.5 * deltaTau * Sl * (vl2 * Sl - riskFreeRate) * U_minimumStock(minimumStock, tau[m + 1]));
b2.setEntry(len - 1, 0,
0.5 * deltaTau * Su * (vu2 * Su - riskFreeRate) * U_maximumStock(maximumStock, tau[m + 1]));
RealMatrix U1 = (F.scalarMultiply(1 - theta).add(eye.scalarMultiply(theta))).multiply(U);
RealMatrix U2 = b.scalarMultiply(1 + theta).add(b2.scalarMultiply(theta));
U = solver.solve(U1.add(U2));
}
double[] optionPrice = U.getColumn(0);
double[][] stockAndOptionPrice = new double[2][len];
stockAndOptionPrice[0] = stock;
stockAndOptionPrice[1] = optionPrice;
return stockAndOptionPrice;
}
}
| src/main/java/net/finmath/finitedifference/experimental/LocalVolatilityTheta.java | First implementation of theta-method for time-reversed local volatility PDE.
| src/main/java/net/finmath/finitedifference/experimental/LocalVolatilityTheta.java | First implementation of theta-method for time-reversed local volatility PDE. |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/liferay/arquillian/processor/BndApplicationArchiveProcessor.java' did not match any file(s) known to git
| 3604b379d6d017d588c2f7f47a56d64795665953 | 1 | csierra/arquillian-deployment-generator-bnd | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.arquillian.processor;
import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Jar;
import java.io.ByteArrayOutputStream;
import java.util.jar.Manifest;
import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* This processor analyzes the jar after adding the test to fix the imports
* when needed.
*
* @author Carlos Sierra Andrés
*/
public class BndApplicationArchiveProcessor implements ApplicationArchiveProcessor {
public static final String MANIFEST_PATH = "META-INF/MANIFEST.MF";
@Override
public void process(Archive<?> applicationArchive, TestClass testClass) {
JavaArchive javaArchive = applicationArchive.as(JavaArchive.class);
javaArchive.addClass(testClass.getJavaClass());
Analyzer analyzer = new Analyzer();
try {
Manifest manifest = new Manifest(applicationArchive.get(MANIFEST_PATH).getAsset().openStream());
String exportPackage = manifest.getMainAttributes().getValue("Export-Package");
if (exportPackage == null || exportPackage.isEmpty()) {
exportPackage = testClass.getJavaClass().getPackage().getName();
}
else {
exportPackage += "," + testClass.getJavaClass().getPackage().getName();
}
manifest.getMainAttributes().putValue("Export-Package", exportPackage);
analyzer.mergeManifest(manifest);
ZipExporter zipExporter = applicationArchive.as(ZipExporter.class);
Jar jar = new Jar(applicationArchive.getName(), zipExporter.exportAsInputStream());
analyzer.setJar(jar);
manifest = analyzer.calcManifest();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
ByteArrayAsset byteArrayAsset = new ByteArrayAsset(
baos.toByteArray());
replaceManifest(applicationArchive, byteArrayAsset);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
analyzer.close();
}
}
private void replaceManifest(
Archive<?> archive, ByteArrayAsset byteArrayAsset) {
archive.delete(MANIFEST_PATH);
archive.add(byteArrayAsset, MANIFEST_PATH);
}
} | src/main/java/com/liferay/arquillian/processor/BndApplicationArchiveProcessor.java | Add an ApplicationArchiveProcessor to calculate the final Manifest
taking into accout the test class
| src/main/java/com/liferay/arquillian/processor/BndApplicationArchiveProcessor.java | Add an ApplicationArchiveProcessor to calculate the final Manifest taking into accout the test class |
|
Java | apache-2.0 | error: pathspec 'src/de/mrapp/android/adapter/expandablelist/selectable/ExpandableListSelectionListener.java' did not match any file(s) known to git
| 9d594bc91436e88aefc772da9b7a87bca93f6177 | 1 | michael-rapp/AndroidAdapters | /*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package de.mrapp.android.adapter.expandablelist.selectable;
/**
* Defines the interface, all listeners, which should be notified when the
* selection of a group or child item of a {@link ExpandableListAdapter} has
* been modified, must implement.
*
* @param <GroupType>
* The type of the underlying data of the observed adapter's group
* items
* @param <ChildType>
* The type of the underlying data of the observed adapter's child
* items
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public interface ExpandableListSelectionListener<GroupType, ChildType> {
/**
* The method, which is invoked, when a group item has been selected.
*
* @param group
* The group item, which has been selected, as an instance of the
* generic type GroupType. The group item may not be null
* @param index
* The index of the group item, which has been selected, as an
* {@link Integer} value
*/
void onGroupSelected(GroupType group, int index);
/**
* The method, which is invoked, when a group item has been unselected.
*
* @param group
* The group item, which has been unselected, as an instance of
* the generic type GroupType. The group item may not be null
* @param index
* The index of the group item, which has been unselected, as an
* {@link Integer} value
*/
void onGroupUnselected(GroupType group, int index);
/**
* The method, which is invoked, when a child item has been selected.
*
* @param child
* The child item, which has been selected, as an instance of the
* generic type ChildType. The child item may not be null
* @param childIndex
* The index of the child item, which has been selected, as an
* {@link Integer} value
* @param group
* The group item, the child, which has been selected, belongs
* to, as an instance of the generic type GroupType. The group
* item may not be null
* @param groupIndex
* The index of the group item, the child, which has been
* selected, belongs to, as an {@link Integer} value
*/
void onChildSelected(ChildType child, int childIndex, GroupType group,
int groupIndex);
/**
* The method, which is invoked, when a child item has been unselected.
*
* @param child
* The child item, which has been unselected, as an instance of
* the generic type ChildType. The child item may not be null
* @param childIndex
* The index of the child item, which has been unselected, as an
* {@link Integer} value
* @param group
* The group item, the child, which has been unselected, belongs
* to, as an instance of the generic type GroupType. The group
* item may not be null
* @param groupIndex
* The index of the group item, the child, which has been
* unselected, belongs to, as an {@link Integer} value
*/
void onChildUnselected(ChildType child, int childIndex, GroupType group,
int groupIndex);
} | src/de/mrapp/android/adapter/expandablelist/selectable/ExpandableListSelectionListener.java | Added the interface ExpandableListSelectionListener.
| src/de/mrapp/android/adapter/expandablelist/selectable/ExpandableListSelectionListener.java | Added the interface ExpandableListSelectionListener. |
|
Java | apache-2.0 | error: pathspec 'rice-middleware/sampleapp/src/it/java/edu/samplu/krad/labs/lookups/DemoLabsLookupMultipleCriteriaColumnSmokeTest.java' did not match any file(s) known to git
| b5708e1f96517932b5a550a88ed5be3a7b53abc3 | 1 | rojlarge/rice-kc,UniversityOfHawaiiORS/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,bhutchinson/rice,kuali/kc-rice,gathreya/rice-kc,kuali/kc-rice,bsmith83/rice-1,cniesen/rice,sonamuthu/rice-1,shahess/rice,jwillia/kc-rice1,ewestfal/rice-svn2git-test,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,ewestfal/rice,shahess/rice,ewestfal/rice,smith750/rice,shahess/rice,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,rojlarge/rice-kc,ewestfal/rice,jwillia/kc-rice1,sonamuthu/rice-1,ewestfal/rice-svn2git-test,bhutchinson/rice,bhutchinson/rice,gathreya/rice-kc,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,bhutchinson/rice,cniesen/rice,bsmith83/rice-1,smith750/rice,rojlarge/rice-kc,smith750/rice,bhutchinson/rice,rojlarge/rice-kc,kuali/kc-rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,jwillia/kc-rice1,kuali/kc-rice,bsmith83/rice-1,gathreya/rice-kc,bsmith83/rice-1,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,ewestfal/rice,shahess/rice,UniversityOfHawaiiORS/rice,cniesen/rice,cniesen/rice,ewestfal/rice-svn2git-test,gathreya/rice-kc,smith750/rice,cniesen/rice,ewestfal/rice,shahess/rice,kuali/kc-rice,smith750/rice,geothomasp/kualico-rice-kc,jwillia/kc-rice1 | /*
* Copyright 2006-2012 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.samplu.krad.labs.lookups;
import org.junit.Test;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoLabsLookupMultipleCriteriaColumnSmokeTest extends DemoLabsLookupBase {
/**
* /kr-krad/lookup?methodToCall=start&viewId=LabsLookup-MultipleColumnsCriteriaView&hideReturnLink=true
*/
public static final String BOOKMARK_URL = "/kr-krad/lookup?methodToCall=start&viewId=LabsLookup-MultipleColumnsCriteriaView&hideReturnLink=true";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
navigateToLookup("Lookup Multiple Criteria Columns");
}
@Test
public void testLabsLookupMultipleCriteriaColumnBookmark() throws Exception {
testLabsLookupMultipleCriteriaColumn();
passed();
}
@Test
public void testLabsLookupMultipleCriteriaColumnNav() throws Exception {
testLabsLookupMultipleCriteriaColumn();
passed();
}
protected void testLabsLookupMultipleCriteriaColumn()throws Exception {
waitForElementPresentByXpath("//table[@class='table table-condensed table-bordered uif-gridLayout']/tbody/tr/th");
waitForElementPresentByXpath("//table[@class='table table-condensed table-bordered uif-gridLayout']/tbody/tr/th[2]");
}
}
| rice-middleware/sampleapp/src/it/java/edu/samplu/krad/labs/lookups/DemoLabsLookupMultipleCriteriaColumnSmokeTest.java | KULRICE-10792 : Create Functional Test for KRAD Demo Labs Lookups - Multiple Criteria Columns Completed
| rice-middleware/sampleapp/src/it/java/edu/samplu/krad/labs/lookups/DemoLabsLookupMultipleCriteriaColumnSmokeTest.java | KULRICE-10792 : Create Functional Test for KRAD Demo Labs Lookups - Multiple Criteria Columns Completed |