answer
stringlengths 17
10.2M
|
|---|
package org.neo4j.server.logging;
import org.apache.log4j.Level;
import org.apache.log4j.Priority;
public class Logger
{
public static Logger log = Logger.getLogger(Logger.class);
org.apache.log4j.Logger logger;
public static Logger getLogger(Class<?> clazz) {
return new Logger(clazz);
}
public static Logger getLogger(String logger) {
return new Logger(logger);
}
public Logger(Class<?> clazz) {
logger = org.apache.log4j.Logger.getLogger(clazz);
}
public Logger(String str) {
logger = org.apache.log4j.Logger.getLogger(str);
}
public void log(Priority priority, String message, Throwable throwable) {
logger.log(priority, message, throwable);
}
public void log(Level level, String message, Object... parameters) {
if (logger.isEnabledFor(level)) {
logger.log(level, String.format(message, parameters));
}
}
public void fatal(String message, Object... parameters) {
log(Level.FATAL, message, parameters);
}
public void error(String message, Object... parameters) {
log(Level.ERROR, message, parameters);
}
public void error(Throwable e) {
log(Level.ERROR, "", e);
}
public void warn(Throwable e) {
log(Level.WARN, "", e);
}
public void warn(String message, Object... parameters) {
log(Level.WARN, message, parameters);
}
public void info(String message, Object... parameters) {
log(Level.INFO, message, parameters);
}
public void debug(String message, Object... parameters) {
log(Level.DEBUG, message, parameters);
}
public void trace(String message, Object... parameters) {
log(Level.TRACE, message, parameters);
}
}
|
package com.github.ambry.rest;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.DefaultCookie;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Test;
public class NettyUtilsTest {
@Test
public void convertHttpToJavaCookiesTest() {
Cookie cookie = new DefaultCookie("CookieKey1", "CookieValue1");
cookie.setVersion(1);
cookie.setHttpOnly(true);
cookie.setDomain("domain1");
cookie.setComment("comment1");
cookie.setCommentUrl("commentUrl1");
cookie.setPath("path1Dir1/path1File1");
int maxAge = new Random().nextInt(10000);
cookie.setMaxAge(maxAge);
cookie.setDiscard(false);
Set<Cookie> cookies = new HashSet<Cookie>();
cookies.add(cookie);
Set<javax.servlet.http.Cookie> javaCookies = NettyUtils.convertHttpToJavaCookies(cookies);
Assert.assertEquals("Size mistmatch ", cookies.size(), javaCookies.size());
compareCookies(cookies, javaCookies);
cookie = new DefaultCookie("CookieKey2", "CookieValue2");
cookie.setVersion(1);
cookie.setHttpOnly(false);
cookie.setDomain("domain2");
cookie.setComment("comment2");
cookie.setCommentUrl("commentUrl2");
cookie.setPath("path1Dir2/path1File2");
maxAge = new Random().nextInt(10000);
cookie.setMaxAge(maxAge);
cookie.setDiscard(false);
cookies.add(cookie);
javaCookies = NettyUtils.convertHttpToJavaCookies(cookies);
Assert.assertEquals("Size mistmatch ", cookies.size(), javaCookies.size());
compareCookies(cookies, javaCookies);
}
/**
* Compares a set of {@link Cookie} with that of {@link javax.servlet.http.Cookie}s for equality
* @param httpCookies Set of {@link Cookie}s to be compared with the {@code javaCookies}
* @param javaCookies Set of {@link javax.servlet.http.Cookie}s to be compared with those of {@code httpCookies}
*/
static void compareCookies(Set<Cookie> httpCookies, Set<javax.servlet.http.Cookie> javaCookies) {
if (httpCookies.size() != javaCookies.size()) {
org.junit.Assert.fail("Size of cookies didn't match");
} else {
HashMap<String, Cookie> cookieHashMap = new HashMap<String, Cookie>();
for (Cookie cookie : httpCookies) {
cookieHashMap.put(cookie.getName(), cookie);
}
HashMap<String, javax.servlet.http.Cookie> javaCookiesHashMap = new HashMap<String, javax.servlet.http.Cookie>();
for (javax.servlet.http.Cookie cookie : javaCookies) {
javaCookiesHashMap.put(cookie.getName(), cookie);
}
for (String cookieName : cookieHashMap.keySet()) {
Cookie cookie = cookieHashMap.get(cookieName);
compareCookie(cookie, javaCookiesHashMap.get(cookieName));
javaCookiesHashMap.remove(cookieName);
}
org.junit.Assert.assertEquals("More Cookies found in NettyRequest ", 0, javaCookiesHashMap.size());
}
}
/**
* Compare {@link Cookie} with {@link javax.servlet.http.Cookie}
* @param httpCookie {@link javax.servlet.http.Cookie} to be compared with {@code javaCookie}
* @param javaCookie {@link javax.servlet.http.Cookie} to be compared with {@code httpCookie}
*/
static void compareCookie(Cookie httpCookie, javax.servlet.http.Cookie javaCookie) {
org.junit.Assert.assertEquals("Value field didn't match ", httpCookie.getValue(), javaCookie.getValue());
org.junit.Assert.assertEquals("Secure field didn't match ", httpCookie.isSecure(), javaCookie.getSecure());
org.junit.Assert.assertEquals("Max Age field didn't match ", httpCookie.getMaxAge(), javaCookie.getMaxAge());
org.junit.Assert.assertEquals("Max Age field didn't match ", httpCookie.isHttpOnly(), javaCookie.isHttpOnly());
org.junit.Assert.assertEquals("Max Age field didn't match ", httpCookie.getVersion(), javaCookie.getVersion());
if (httpCookie.getPath() != null) {
org.junit.Assert.assertEquals("Path field didn't match ", httpCookie.getPath(), javaCookie.getPath());
} else {
org.junit.Assert.assertTrue("Path field didn't match", (javaCookie.getPath() == null));
}
if (httpCookie.getComment() != null) {
org.junit.Assert.assertEquals("Comment field didn't match ", httpCookie.getComment(), javaCookie.getComment());
} else {
org.junit.Assert.assertTrue("Comment field didn't match ", (javaCookie.getComment() == null));
}
if (httpCookie.getDomain() != null) {
org.junit.Assert.assertEquals("Domain field didn't match ", httpCookie.getDomain(), javaCookie.getDomain());
} else {
org.junit.Assert.assertTrue("Domain field didn't match ", (javaCookie.getDomain() == null));
}
}
}
|
package com.tavultesoft.kmea;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.inputmethodservice.InputMethodService;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.tavultesoft.kmea.KeyboardEventHandler.EventType;
import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardDownloadEventListener;
import com.tavultesoft.kmea.KeyboardEventHandler.OnKeyboardEventListener;
public final class KMManager {
private static final String KMEngineVersion = "2.4.3";
// Keyboard types
public enum KeyboardType {
KEYBOARD_TYPE_UNDEFINED,
KEYBOARD_TYPE_INAPP,
KEYBOARD_TYPE_SYSTEM;
}
// Keyboard states
public enum KeyboardState {
KEYBOARD_STATE_UNDEFINED,
KEYBOARD_STATE_NEEDS_DOWNLOAD,
KEYBOARD_STATE_NEEDS_UPDATE,
KEYBOARD_STATE_UP_TO_DATE;
}
// Globe key actions
public enum GlobeKeyAction {
GLOBE_KEY_ACTION_SHOW_MENU,
GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD,
GLOBE_KEY_ACTION_DO_NOTHING,
}
private static InputMethodService IMService;
private static boolean debugMode = false;
private static boolean shouldAllowSetKeyboard = true;
private static ArrayList<OnKeyboardDownloadEventListener> kbDownloadEventListeners = null;
private static boolean didCopyAssets = false;
private static GlobeKeyAction inappKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU;
private static GlobeKeyAction sysKbGlobeKeyAction = GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU;
protected static boolean InAppKeyboardLoaded = false;
protected static boolean SystemKeyboardLoaded = false;
protected static boolean InAppKeyboardShouldIgnoreTextChange = false;
protected static boolean InAppKeyboardShouldIgnoreSelectionChange = false;
protected static boolean SystemKeyboardShouldIgnoreTextChange = false;
protected static boolean SystemKeyboardShouldIgnoreSelectionChange = false;
protected static KMKeyboard InAppKeyboard = null;
protected static KMKeyboard SystemKeyboard = null;
protected static final String kKeymanApiBaseURL = "https://r.keymanweb.com/api/3.0/";
private static final String kKeymanApiRemoteURL = "https://r.keymanweb.com/api/2.0/remote?url=";
// Keyman public keys
public static final String KMKey_ID = "id";
public static final String KMKey_Name = "name";
public static final String KMKey_LanguageID = "langId";
public static final String KMKey_LanguageName = "langName";
public static final String KMKey_KeyboardID = "kbId";
public static final String KMKey_KeyboardName = "kbName";
public static final String KMKey_KeyboardVersion = "version";
public static final String KMKey_Keyboard = "keyboard";
public static final String KMKey_LanguageKeyboards = "keyboards";
public static final String KMKey_KeyboardFileSize = "fileSize";
public static final String KMKey_Font = "font";
public static final String KMKey_OskFont = "oskFont";
public static final String KMKey_FontFamily = "family";
public static final String KMKey_FontSource = "source";
public static final String KMKey_FontFiles = "files";
public static final String KMKey_Options = "options";
public static final String KMKey_Language = "language";
public static final String KMKey_Languages = "languages";
public static final String KMKey_Filename = "filename";
public static final String KMKey_KeyboardModified = "lastModified";
public static final String KMKey_KeyboardRTL = "rtl";
public static final String KMKey_CustomKeyboard = "CustomKeyboard";
public static final String KMKey_CustomHelpLink = "CustomHelpLink";
public static final String KMKey_UserKeyboardIndex = "UserKeyboardIndex";
// Keyman internal keys
protected static final String KMKey_KeyboardBaseURI = "keyboardBaseUri";
protected static final String KMKey_FontBaseURI = "fontBaseUri";
protected static final String KMKey_ShouldShowHelpBubble = "ShouldShowHelpBubble";
// Default Keyboard Info
public static final String KMDefault_KeyboardID = "european2";
public static final String KMDefault_LanguageID = "eng";
public static final String KMDefault_KeyboardName = "EuroLatin2 Keyboard";
public static final String KMDefault_LanguageName = "English";
public static final String KMDefault_KeyboardFont = "{\"family\":\"LatinWeb\",\"source\":[\"DejaVuSans.ttf\"]}";
// Keyman files
protected static final String KMFilename_KeyboardHtml = "keyboard.html";
protected static final String KMFilename_JSEngine = "keyman.js";
protected static final String KMFilename_KmwCss = "kmwosk.css";
protected static final String KMFilename_Osk_Ttf_Font = "keymanweb-osk.ttf";
protected static final String KMFilename_Osk_Woff_Font = "keymanweb-osk.woff";
public static final String KMFilename_KeyboardsList = "keyboards_list.dat";
private static Context appContext;
public static String getVersion() {
return KMEngineVersion;
}
public static void initialize(Context context, KeyboardType keyboardType) {
appContext = context.getApplicationContext();
if (!didCopyAssets) {
copyAssets(appContext);
renameOldKeyboardFiles(appContext);
updateOldKeyboardsList(appContext);
didCopyAssets = true;
}
if (keyboardType == KeyboardType.KEYBOARD_TYPE_INAPP) {
initInAppKeyboard(appContext);
} else if (keyboardType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
initSystemKeyboard(appContext);
} else {
Log.w("KMManager", "Cannot initialize: Invalid keyboard type");
}
}
public static void setInputMethodService(InputMethodService service) {
IMService = service;
}
public static boolean executeHardwareKeystroke(int code, int shift) {
if (SystemKeyboard != null) {
return executeHardwareKeystroke(code, shift, KeyboardType.KEYBOARD_TYPE_SYSTEM);
} else if (InAppKeyboard != null) {
return executeHardwareKeystroke(code, shift, KeyboardType.KEYBOARD_TYPE_INAPP);
}
return false;
}
public static boolean executeHardwareKeystroke(int code, int shift, KeyboardType keyboard) {
if (keyboard == KeyboardType.KEYBOARD_TYPE_INAPP) {
InAppKeyboard.executeHardwareKeystroke(code, shift);
return true;
} else if (keyboard == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
SystemKeyboard.executeHardwareKeystroke(code, shift);
return true;
}
return false;
}
private static void initInAppKeyboard(Context appContext) {
if (InAppKeyboard == null) {
if (isDebugMode())
Log.d("KMManager", "Initializing In-App Keyboard...");
int kbHeight = appContext.getResources().getDimensionPixelSize(R.dimen.keyboard_height);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, kbHeight);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
InAppKeyboard = new KMKeyboard(appContext, KeyboardType.KEYBOARD_TYPE_INAPP);
InAppKeyboard.setLayoutParams(params);
InAppKeyboard.setVerticalScrollBarEnabled(false);
InAppKeyboard.setHorizontalScrollBarEnabled(false);
InAppKeyboard.setWebViewClient(new KMInAppKeyboardWebViewClient(appContext));
InAppKeyboard.addJavascriptInterface(new KMInAppKeyboardJSHandler(appContext), "jsInterface");
InAppKeyboard.loadKeyboard();
}
}
private static void initSystemKeyboard(Context appContext) {
if (SystemKeyboard == null) {
if (isDebugMode())
Log.d("KMManager", "Initializing System Keyboard...");
int kbHeight = appContext.getResources().getDimensionPixelSize(R.dimen.keyboard_height);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, kbHeight);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
SystemKeyboard = new KMKeyboard(appContext, KeyboardType.KEYBOARD_TYPE_SYSTEM);
SystemKeyboard.setLayoutParams(params);
SystemKeyboard.setVerticalScrollBarEnabled(false);
SystemKeyboard.setHorizontalScrollBarEnabled(false);
SystemKeyboard.setWebViewClient(new KMSystemKeyboardWebViewClient(appContext));
SystemKeyboard.addJavascriptInterface(new KMSystemKeyboardJSHandler(appContext), "jsInterface");
SystemKeyboard.loadKeyboard();
}
}
@SuppressLint("InflateParams")
public static View createInputView(InputMethodService inputMethodService) {
//final Context context = appContext;
IMService = inputMethodService;
Context appContext = IMService.getApplicationContext();
final FrameLayout mainLayout = new FrameLayout(appContext);
mainLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
RelativeLayout keyboardLayout = new RelativeLayout(appContext);
keyboardLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
ViewGroup parent = (ViewGroup) SystemKeyboard.getParent();
if (parent != null)
parent.removeView(SystemKeyboard);
keyboardLayout.addView(SystemKeyboard);
/*
final RelativeLayout overlayLayout = new RelativeLayout(appContext);
overlayLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout overlayView = (RelativeLayout) inflater.inflate(R.layout.overlay_layout, null, false);
overlayView.setLayoutParams(SystemKeyboard.getLayoutParams());
overlayView.setBackgroundColor(Color.argb(192, 0, 0, 0));
overlayView.setClickable(true);
overlayLayout.addView(overlayView);
Button activateButton = (Button) overlayView.findViewById(R.id.button1);
activateButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mainLayout.removeView(overlayLayout);
Toast.makeText(context, "Reactivated", Toast.LENGTH_LONG).show();
}
});
*/
mainLayout.addView(keyboardLayout);
//mainLayout.addView(overlayLayout);
return mainLayout;
}
public static void onStartInput(EditorInfo attribute, boolean restarting) {
if (!restarting) {
String packageName = attribute.packageName;
int inputType = attribute.inputType;
if (packageName.equals("android") && inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
SystemKeyboard.keyboardPickerEnabled = false;
} else {
SystemKeyboard.keyboardPickerEnabled = true;
}
}
}
public static void onResume() {
if (InAppKeyboard != null) {
InAppKeyboard.onResume();
}
if (SystemKeyboard != null) {
SystemKeyboard.onResume();
}
}
public static void onPause() {
if (InAppKeyboard != null) {
InAppKeyboard.onPause();
}
if (SystemKeyboard != null) {
SystemKeyboard.onPause();
}
}
public static void onDestroy() {
if (InAppKeyboard != null) {
InAppKeyboard.onDestroy();
}
if (SystemKeyboard != null) {
SystemKeyboard.onDestroy();
}
}
public static void onConfigurationChanged(Configuration newConfig) {
// KMKeyboard
if (InAppKeyboard != null) {
InAppKeyboard.onConfigurationChanged(newConfig);
}
if (SystemKeyboard != null) {
SystemKeyboard.onConfigurationChanged(newConfig);
}
}
public static boolean hasConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
private static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
File file;
try {
// Copy main files
copyAsset(context, KMFilename_KeyboardHtml, "", true);
copyAsset(context, KMFilename_JSEngine, "", true);
copyAsset(context, KMFilename_KmwCss, "", true);
copyAsset(context, KMFilename_Osk_Ttf_Font, "", true);
copyAsset(context, KMFilename_Osk_Woff_Font, "", true);
// Copy languages
file = new File(context.getDir("data", Context.MODE_PRIVATE) + "/languages");
if (!file.exists())
file.mkdir();
String[] languageFiles = assetManager.list("languages");
for (String filename : languageFiles) {
copyAsset(context, filename, "languages", true);
}
// Copy fonts
file = new File(context.getDir("data", Context.MODE_PRIVATE) + "/fonts");
if (!file.exists())
file.mkdir();
String[] fontFiles = assetManager.list("fonts");
for (String filename : fontFiles) {
copyAsset(context, filename, "fonts", false);
}
} catch (Exception e) {
Log.e("Failed to copy assets", "Error: " + e);
}
}
private static int copyAsset(Context context, String filename, String directory, boolean overwrite) {
int result;
AssetManager assetManager = context.getAssets();
try {
if (directory == null)
directory = "";
directory = directory.trim();
String dirPath;
if (directory.length() != 0) {
directory = directory + "/";
dirPath = context.getDir("data", Context.MODE_PRIVATE) + "/" + directory;
} else {
dirPath = context.getDir("data", Context.MODE_PRIVATE).toString();
}
File file = new File(dirPath, filename);
if (!file.exists() || overwrite) {
InputStream inputStream = assetManager.open(directory + filename);
FileOutputStream outputStream = new FileOutputStream(file);
copyFile(inputStream, outputStream);
result = 1;
} else {
result = 0;
}
} catch (Exception e) {
Log.e("Failed to copy asset", "Error: " + e);
result = -1;
}
return result;
}
private static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
}
private static void renameOldKeyboardFiles(Context context) {
String path = context.getDir("data", Context.MODE_PRIVATE) + "/languages/";
File dir = new File(path);
String[] files = dir.list();
for (String filename : files) {
if (filename.lastIndexOf("-") < 0) {
if (filename.equals("us.js")) {
File kbFile = new File(path, filename);
kbFile.delete();
} else {
String newFilename = filename.substring(0, filename.lastIndexOf(".js")) + "-1.0.js";
File kbFile = new File(path, filename);
kbFile.renameTo(new File(path, newFilename));
}
} else {
String oldFilename = filename.substring(0, filename.lastIndexOf("-")) + ".js";
File kbFile = new File(path, oldFilename);
if (kbFile.exists())
kbFile.delete();
}
}
}
public static void updateOldKeyboardsList(Context context) {
ArrayList<HashMap<String, String>> kbList = KeyboardPickerActivity.getKeyboardsList(context);
if (kbList != null && kbList.size() > 0) {
boolean shouldUpdateList = false;
boolean shouldClearCache = false;
HashMap<String, String> kbInfo = kbList.get(0);
String kbID = kbInfo.get(KMKey_KeyboardID);
if (kbID.equals("us")) {
HashMap<String, String> newKbInfo = new HashMap<String, String>();
newKbInfo.put(KMManager.KMKey_KeyboardID, KMManager.KMDefault_KeyboardID);
newKbInfo.put(KMManager.KMKey_LanguageID, KMManager.KMDefault_LanguageID);
newKbInfo.put(KMManager.KMKey_KeyboardName, KMManager.KMDefault_KeyboardName);
newKbInfo.put(KMManager.KMKey_LanguageName, KMManager.KMDefault_LanguageName);
newKbInfo.put(KMManager.KMKey_KeyboardVersion, getLatestKeyboardFileVersion(context, KMManager.KMDefault_KeyboardID));
newKbInfo.put(KMManager.KMKey_CustomKeyboard, "N");
newKbInfo.put(KMManager.KMKey_Font, KMManager.KMDefault_KeyboardFont);
kbList.set(0, newKbInfo);
shouldUpdateList = true;
shouldClearCache = true;
}
int index2Remove = -1;
int kblCount = kbList.size();
for (int i = 0; i < kblCount; i++) {
kbInfo = kbList.get(i);
kbID = kbInfo.get(KMKey_KeyboardID);
String langID = kbInfo.get(KMKey_LanguageID);
String kbVersion = kbInfo.get(KMManager.KMKey_KeyboardVersion);
String latestKbVersion = getLatestKeyboardFileVersion(context, kbID);
if (kbVersion == null || !kbVersion.equals(latestKbVersion)) {
kbInfo.put(KMManager.KMKey_KeyboardVersion, latestKbVersion);
kbList.set(i, kbInfo);
shouldUpdateList = true;
}
String isCustom = kbInfo.get(KMManager.KMKey_CustomKeyboard);
if (isCustom == null || isCustom.equals("U")) {
String kbKey = String.format("%s_%s", langID, kbID);
kbInfo.put(KMManager.KMKey_CustomKeyboard, isCustomKeyboard(context, kbKey));
kbList.set(i, kbInfo);
shouldUpdateList = true;
}
if (kbID.equals(KMManager.KMDefault_KeyboardID) && langID.equals(KMManager.KMDefault_LanguageID)) {
int defKbIndex = KMManager.getKeyboardIndex(context, KMManager.KMDefault_KeyboardID, KMManager.KMDefault_LanguageID);
if (defKbIndex == 0 && i > 0)
index2Remove = i;
}
}
if (index2Remove > 0) {
kbList.remove(index2Remove);
SharedPreferences prefs = appContext.getSharedPreferences(appContext.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int index = prefs.getInt(KMManager.KMKey_UserKeyboardIndex, 0);
if (index == index2Remove) {
index = 0;
} else if (index > index2Remove) {
index
}
editor.putInt(KMManager.KMKey_UserKeyboardIndex, index);
editor.commit();
shouldUpdateList = true;
}
if (shouldUpdateList) {
KeyboardPickerActivity.updateKeyboardsList(context, kbList);
}
if (shouldClearCache) {
File cache = LanguageListActivity.getCacheFile(appContext);
if (cache.exists()) {
cache.delete();
}
}
}
}
private static String isCustomKeyboard(Context context, String keyboardKey) {
String isCustom = "U";
HashMap<String, HashMap<String, String>> keyboardsInfo = LanguageListActivity.getKeyboardsInfo(context);
if (keyboardsInfo != null) {
HashMap<String, String> kbInfo = keyboardsInfo.get(keyboardKey);
if (kbInfo != null) {
isCustom = "N";
} else {
isCustom = "Y";
}
}
return isCustom;
}
public static Typeface getFontTypeface(Context context, String fontFilename) {
Typeface font = null;
if (fontFilename != null) {
if (fontFilename.endsWith(".ttf") || fontFilename.endsWith(".otf")) {
File file = new File(context.getDir("data", Context.MODE_PRIVATE) + "/fonts/" + fontFilename);
if (file.exists()) {
font = Typeface.createFromFile(file);
} else {
font = null;
}
}
}
return font;
}
public static ArrayList<HashMap<String, String>> getKeyboardsList(Context context) {
return KeyboardPickerActivity.getKeyboardsList(context);
}
public static final class KMKeyboardDownloader {
public static void download(final Context context, final int languageIndex, final int keyboardIndex, final boolean showProgressDialog) {
new AsyncTask<Void, Integer, Integer>() {
private ProgressDialog progressDialog;
private String languageID = "";
private String keyboardID = "";
private String languageName = "";
private String keyboardName = "";
private String kbVersion = "1.0";
private String isCustom = "N";
private String font = "";
private String oskFont = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
if (showProgressDialog) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading keyboard...");
progressDialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
progressDialog.show();
} else {
cancel(true);
progressDialog = null;
}
}
}
@Override
protected Integer doInBackground(Void... voids) {
int ret = -1;
ArrayList<String> urls = new ArrayList<String>();
if (isCancelled())
return ret;
try {
JSONArray languages = LanguageListActivity.languages();
JSONObject options = LanguageListActivity.options();
if (languages == null || options == null) {
throw new Exception("Language list is empty");
}
JSONObject language = languages.getJSONObject(languageIndex);
JSONArray keyboards = language.getJSONArray(KMKey_LanguageKeyboards);
JSONObject keyboard = keyboards.getJSONObject(keyboardIndex);
keyboardID = keyboard.getString(KMKey_ID);
languageID = language.getString(KMKey_ID);
keyboardName = keyboard.getString(KMKey_Name);
languageName = language.getString(KMKey_Name);
kbVersion = keyboard.optString(KMKey_KeyboardVersion, "1.0");
font = keyboard.optString(KMKey_Font, "");
oskFont = keyboard.optString(KMKey_OskFont, null);
String kbFilename = keyboard.optString(KMKey_Filename, "");
String kbUrl = options.getString(KMKey_KeyboardBaseURI) + kbFilename;
urls.add(kbUrl);
JSONObject jsonFont = keyboard.optJSONObject(KMKey_Font);
JSONObject jsonOskFont = keyboard.optJSONObject(KMKey_OskFont);
String fontBaseUri = options.getString(KMKey_FontBaseURI);
ArrayList<String> fontUrls = fontUrls(jsonFont, fontBaseUri, true);
ArrayList<String> oskFontUrls = fontUrls(jsonOskFont, fontBaseUri, true);
if (fontUrls != null)
urls.addAll(fontUrls);
if (oskFontUrls != null) {
for (String url : oskFontUrls) {
if (!urls.contains(url))
urls.add(url);
}
}
// Notify listeners: onDownloadStarted
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null)
keyboardInfo.put(KMKey_OskFont, oskFont);
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_STARTED, keyboardInfo, 0);
}
ret = 1;
int result = 0;
for (String url : urls) {
String directory = "";
String filename = "";
if (url.endsWith(".js")) {
directory = "languages";
int start = kbFilename.lastIndexOf("/");
if (start < 0) {
start = 0;
} else {
start++;
}
if (!kbFilename.contains("-")) {
filename = kbFilename.substring(start, kbFilename.length() - 3) + "-" + kbVersion + ".js";
} else {
filename = kbFilename.substring(start);
}
} else {
directory = "fonts";
filename = "";
}
result = FileDownloader.download(context, url, directory, filename);
if (result < 0) {
ret = -1;
break;
}
}
} catch (Exception e) {
ret = -1;
Log.e("Keyboard download", "Error: " + e);
}
return ret;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Do nothing
}
@Override
protected void onPostExecute(Integer result) {
if (showProgressDialog) {
if (progressDialog != null && progressDialog.isShowing()) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception e) {
progressDialog = null;
}
}
}
// Notify listeners: onDownloadFinished
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null)
keyboardInfo.put(KMKey_OskFont, oskFont);
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_FINISHED, keyboardInfo, result);
}
}
}.execute();
}
public static void download(final Context context, final String keyboardID, final String languageID, final boolean showProgressDialog) {
new AsyncTask<Void, Integer, Integer>() {
private ProgressDialog progressDialog;
private String languageName = "";
private String keyboardName = "";
private String kbVersion = "1.0";
private String isCustom = "N";
private String font = "";
private String oskFont = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
if (showProgressDialog) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading keyboard...");
progressDialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
progressDialog.show();
} else {
cancel(true);
progressDialog = null;
}
}
}
@Override
protected Integer doInBackground(Void... voids) {
int ret = -1;
ArrayList<String> urls = new ArrayList<String>();
if (isCancelled())
return ret;
try {
String exceptionStr = "Invalid keyboard";
if (languageID == null || languageID.trim().isEmpty() || keyboardID == null || keyboardID.trim().isEmpty())
throw new Exception(exceptionStr);
String deviceType = context.getResources().getString(R.string.device_type);
if (deviceType.equals("AndroidTablet")) {
deviceType = "androidtablet";
} else {
deviceType = "androidphone";
}
String jsonUrl = String.format("%slanguages/%s/%s?device=%s", kKeymanApiBaseURL, languageID, keyboardID, deviceType);
JSONParser jsonParser = new JSONParser();
JSONObject kbData = jsonParser.getJSONObjectFromUrl(jsonUrl);
exceptionStr = "Could not reach Keyman server";
if (kbData == null) {
throw new Exception(exceptionStr);
}
JSONObject options = kbData.optJSONObject(KMKey_Options);
JSONObject language = kbData.optJSONObject(KMKey_Language);
exceptionStr = "The keyboard could not be installed";
if (options == null || language == null) {
throw new Exception(exceptionStr);
}
JSONArray keyboards = language.getJSONArray(KMKey_LanguageKeyboards);
String kbBaseUri = options.optString(KMKey_KeyboardBaseURI, "");
String fontBaseUri = options.optString(KMKey_FontBaseURI, "");
if (keyboards == null || kbBaseUri.isEmpty())
throw new Exception(exceptionStr);
JSONObject keyboard = keyboards.getJSONObject(0);
if (keyboard == null)
throw new Exception(exceptionStr);
languageName = language.optString(KMKey_Name, "");
keyboardName = keyboard.optString(KMKey_Name, "");
kbVersion = keyboard.optString(KMKey_KeyboardVersion, "1.0");
font = keyboard.optString(KMKey_Font, "");
oskFont = keyboard.optString(KMKey_OskFont, null);
String kbFilename = keyboard.optString(KMKey_Filename, "");
if (keyboardName.isEmpty() || languageName.isEmpty() || kbFilename.isEmpty())
throw new Exception(exceptionStr);
String kbUrl = kbBaseUri + kbFilename;
urls.add(kbUrl);
JSONObject jsonFont = keyboard.optJSONObject(KMKey_Font);
JSONObject jsonOskFont = keyboard.optJSONObject(KMKey_OskFont);
ArrayList<String> fontUrls = fontUrls(jsonFont, fontBaseUri, true);
ArrayList<String> oskFontUrls = fontUrls(jsonOskFont, fontBaseUri, true);
if (fontUrls != null)
urls.addAll(fontUrls);
if (oskFontUrls != null) {
for (String url : oskFontUrls) {
if (!urls.contains(url))
urls.add(url);
}
}
// Notify listeners: onDownloadStarted
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null)
keyboardInfo.put(KMKey_OskFont, oskFont);
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_STARTED, keyboardInfo, 0);
}
ret = 1;
int result = 0;
for (String url : urls) {
String directory = "";
String filename = "";
if (url.endsWith(".js")) {
directory = "languages";
int start = kbFilename.lastIndexOf("/");
if (start < 0) {
start = 0;
} else {
start++;
}
if (!kbFilename.contains("-")) {
filename = kbFilename.substring(start, kbFilename.length() - 3) + "-" + kbVersion + ".js";
} else {
filename = kbFilename.substring(start);
}
} else {
directory = "fonts";
filename = "";
}
result = FileDownloader.download(context, url, directory, filename);
if (result < 0) {
ret = -1;
break;
}
}
} catch (Exception e) {
ret = -1;
Log.e("Keyboard download", "Error: " + e);
}
return ret;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Do nothing
}
@Override
protected void onPostExecute(Integer result) {
if (showProgressDialog) {
if (progressDialog != null && progressDialog.isShowing()) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception e) {
progressDialog = null;
}
}
}
// Notify listeners: onDownloadFinished
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null)
keyboardInfo.put(KMKey_OskFont, oskFont);
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_FINISHED, keyboardInfo, result);
}
}
}.execute();
}
private static ArrayList<String> fontUrls(JSONObject jsonFont, String baseUri, boolean isOskFont) {
if (jsonFont == null)
return null;
ArrayList<String> urls = new ArrayList<String>();
JSONArray fontSource = jsonFont.optJSONArray(KMKey_FontSource);
if (fontSource != null) {
int fcCount = fontSource.length();
for (int i = 0; i < fcCount; i++) {
String fontSourceString;
try {
fontSourceString = fontSource.getString(i);
if (fontSourceString.endsWith(".ttf") || fontSourceString.endsWith(".otf")) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && (fontSourceString.endsWith(".svg") || fontSourceString.endsWith(".woff"))) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && fontSourceString.contains(".svg
String fontFilename = fontSourceString.substring(0, fontSourceString.indexOf(".svg
urls.add(baseUri + fontFilename);
}
} catch (JSONException e) {
return null;
}
}
} else {
String fontSourceString;
try {
fontSourceString = jsonFont.getString(KMKey_FontSource);
if (fontSourceString.endsWith(".ttf") || fontSourceString.endsWith(".otf")) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && (fontSourceString.endsWith(".svg") || fontSourceString.endsWith(".woff"))) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && fontSourceString.contains(".svg
String fontFilename = fontSourceString.substring(0, fontSourceString.indexOf(".svg
urls.add(baseUri + fontFilename);
}
} catch (JSONException e) {
return null;
}
}
return urls;
}
}
public static final class KMCustomKeyboardDownloader {
public static void download(final Context context, final String jsonUrl, final boolean isDirect, final boolean showProgressDialog) {
new AsyncTask<Void, Integer, Integer>() {
private ProgressDialog progressDialog;
private String keyboardID = "";
private String languageID = "";
private String keyboardName = "";
private String languageName = "";
private String kbVersion = "1.0";
private String isCustom = "Y";
private String font = "";
private String oskFont = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
if (showProgressDialog) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading keyboard...");
progressDialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
progressDialog.show();
} else {
cancel(true);
progressDialog = null;
}
}
}
@Override
protected Integer doInBackground(Void... voids) {
int ret = -1;
ArrayList<String> urls = new ArrayList<String>();
if (isCancelled())
return ret;
try {
JSONParser jsonParser = new JSONParser();
JSONObject customKb = null;
if (isDirect) {
customKb = jsonParser.getJSONObjectFromUrl(jsonUrl);
} else {
String deviceType = context.getResources().getString(R.string.device_type);
if (deviceType.equals("AndroidTablet")) {
deviceType = "androidtablet";
} else {
deviceType = "androidphone";
}
String encodedUrl = URLEncoder.encode(jsonUrl, "utf-8");
String remoteUrl = String.format("%s%s&device=%s", kKeymanApiRemoteURL, encodedUrl, deviceType);
customKb = jsonParser.getJSONObjectFromUrl(remoteUrl);
}
String exceptionStr = "Failed to fetch JSON object from the URL";
if (customKb == null) {
throw new Exception(exceptionStr);
}
JSONObject options = customKb.optJSONObject(KMKey_Options);
exceptionStr = "The keyboard could not be installed";
if (options == null) {
throw new Exception(exceptionStr);
}
String kbBaseUri = options.optString(KMKey_KeyboardBaseURI, "");
String fontBaseUri = options.optString(KMKey_FontBaseURI, "");
JSONObject keyboard = customKb.getJSONObject(KMKey_Keyboard);
if (keyboard == null || kbBaseUri.isEmpty()) {
throw new Exception(exceptionStr);
}
JSONArray languages = keyboard.optJSONArray(KMKey_Languages);
keyboardID = keyboard.optString(KMKey_ID, "");
keyboardName = keyboard.optString(KMKey_Name, "");
kbVersion = keyboard.optString(KMKey_KeyboardVersion, "1.0");
font = keyboard.optString(KMKey_Font, "").replace("\"" + KMManager.KMKey_Filename + "\"", "\"" + KMManager.KMKey_FontSource + "\"");
oskFont = keyboard.optString(KMKey_OskFont, "").replace("\"" + KMManager.KMKey_Filename + "\"", "\"" + KMManager.KMKey_FontSource + "\"");
if (oskFont.isEmpty()) {
oskFont = null;
}
String kbFilename = keyboard.optString(KMKey_Filename, "");
if (languages == null || keyboardID.isEmpty() || keyboardName.isEmpty() || kbFilename.isEmpty()) {
throw new Exception(exceptionStr);
}
String kbUrl = kbBaseUri + kbFilename;
urls.add(kbUrl);
JSONObject jsonFont = keyboard.optJSONObject(KMKey_Font);
JSONObject jsonOskFont = keyboard.optJSONObject(KMKey_OskFont);
ArrayList<String> fontUrls = fontUrls(jsonFont, fontBaseUri, true);
ArrayList<String> oskFontUrls = fontUrls(jsonOskFont, fontBaseUri, true);
if (fontUrls != null) {
urls.addAll(fontUrls);
}
if (oskFontUrls != null) {
for (String url : oskFontUrls) {
if (!urls.contains(url)) {
urls.add(url);
}
}
}
languageID = "";
languageName = "";
int langCount = languages.length();
for (int i = 0; i < langCount; i++) {
languageID += languages.getJSONObject(i).getString(KMKey_ID);
languageName += languages.getJSONObject(i).getString(KMKey_Name);
if (i < langCount - 1) {
languageID += ";";
languageName += ";";
}
}
// Notify listeners: onDownloadStarted
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null) {
keyboardInfo.put(KMKey_OskFont, oskFont);
}
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_STARTED, keyboardInfo, 0);
}
ret = 1;
int result = 0;
for (String url : urls) {
String directory = "";
String filename = "";
if (url.endsWith(".js")) {
directory = "languages";
int start = kbFilename.lastIndexOf("/");
if (start < 0) {
start = 0;
} else {
start++;
}
if (!kbFilename.contains("-")) {
filename = kbFilename.substring(start, kbFilename.length() - 3) + "-" + kbVersion + ".js";
} else {
filename = kbFilename.substring(start);
}
} else {
directory = "fonts";
filename = "";
}
result = FileDownloader.download(context, url, directory, filename);
if (result < 0) {
ret = -1;
break;
}
}
} catch (Exception e) {
ret = -1;
Log.e("Keyboard download", "Error: " + e);
e.printStackTrace();
}
return ret;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Do nothing
}
@Override
protected void onPostExecute(Integer result) {
if (showProgressDialog) {
if (progressDialog != null && progressDialog.isShowing()) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception e) {
progressDialog = null;
}
}
}
// Notify listeners: onDownloadFinished
if (kbDownloadEventListeners != null) {
HashMap<String, String> keyboardInfo = new HashMap<String, String>();
keyboardInfo.put(KMKey_KeyboardID, keyboardID);
keyboardInfo.put(KMKey_LanguageID, languageID);
keyboardInfo.put(KMKey_KeyboardName, keyboardName);
keyboardInfo.put(KMKey_LanguageName, languageName);
keyboardInfo.put(KMKey_KeyboardVersion, kbVersion);
keyboardInfo.put(KMKey_CustomKeyboard, isCustom);
keyboardInfo.put(KMKey_Font, font);
if (oskFont != null)
keyboardInfo.put(KMKey_OskFont, oskFont);
KeyboardEventHandler.notifyListeners(kbDownloadEventListeners, EventType.KEYBOARD_DOWNLOAD_FINISHED, keyboardInfo, result);
}
if (result > 0) {
if (KMManager.InAppKeyboard != null)
KMManager.InAppKeyboard.loadKeyboard();
if (KMManager.SystemKeyboard != null)
KMManager.SystemKeyboard.loadKeyboard();
}
}
}.execute();
}
private static ArrayList<String> fontUrls(JSONObject jsonFont, String baseUri, boolean isOskFont) {
if (jsonFont == null)
return null;
ArrayList<String> urls = new ArrayList<String>();
JSONArray fontSource = jsonFont.optJSONArray(KMKey_FontSource);
if (fontSource == null)
fontSource = jsonFont.optJSONArray(KMKey_Filename); // Font filename is deprecated
if (fontSource != null) {
int fcCount = fontSource.length();
for (int i = 0; i < fcCount; i++) {
String fontSourceString;
try {
fontSourceString = fontSource.getString(i);
if (fontSourceString.endsWith(".ttf") || fontSourceString.endsWith(".otf")) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && (fontSourceString.endsWith(".svg") || fontSourceString.endsWith(".woff"))) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && fontSourceString.contains(".svg
String fontFilename = fontSourceString.substring(0, fontSourceString.indexOf(".svg
urls.add(baseUri + fontFilename);
}
} catch (JSONException e) {
return null;
}
}
} else {
String fontSourceString;
try {
fontSourceString = jsonFont.optString(KMKey_FontSource, null);
if (fontSourceString == null)
fontSourceString = jsonFont.getString(KMKey_Filename); // Font filename is deprecated
if (fontSourceString.endsWith(".ttf") || fontSourceString.endsWith(".otf")) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && (fontSourceString.endsWith(".svg") || fontSourceString.endsWith(".woff"))) {
urls.add(baseUri + fontSourceString);
} else if (isOskFont && fontSourceString.contains(".svg
String fontFilename = fontSourceString.substring(0, fontSourceString.indexOf(".svg
urls.add(baseUri + fontFilename);
}
} catch (JSONException e) {
return null;
}
}
return urls;
}
}
private static final class FileDownloader {
public static int download(Context context, String urlStr, String directory, String filename) {
int ret = -1;
HttpURLConnection urlConnection = null;
String fileName = "";
String tmpFileName = "";
File tmpFile = null;
File file = null;
try {
if (directory == null)
directory = "";
directory = directory.trim();
String dirPath;
if (directory.length() != 0) {
directory = directory + "/";
dirPath = context.getDir("data", Context.MODE_PRIVATE) + "/" + directory;
} else {
dirPath = context.getDir("data", Context.MODE_PRIVATE).toString();
}
URL url = new URL(urlStr);
filename = filename.trim();
if (filename == null || filename.isEmpty()) {
fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
if (fileName.lastIndexOf(".js") > 0 && !fileName.contains("-")) {
fileName = fileName.substring(0, filename.lastIndexOf(".js")) + "-1.0.js";
}
} else {
fileName = filename;
}
tmpFileName = String.format("%s.tmp", fileName);
file = new File(dirPath, fileName);
tmpFile = new File(dirPath, tmpFileName);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
InputStream binStream = new BufferedInputStream(urlConnection.getInputStream(), 4096);
byte[] buff = new byte[4096];
FileOutputStream fos = new FileOutputStream(tmpFile);
int len;
while ((len = binStream.read(buff)) != -1) {
fos.write(buff, 0, len);
}
fos.flush();
fos.close();
binStream.close();
ret = 1;
} catch (Exception e) {
ret = -1;
Log.e("FD: Download failed!", "Error: " + e);
} finally {
if (ret > 0) {
if (tmpFile.exists()) {
if (file.exists()) {
file.delete();
}
if (!tmpFile.renameTo(file)) {
ret = -1;
} else if (isDebugMode()) {
Log.d("FD: Download finished", "Filename = " + file.toString());
}
} else {
ret = -1;
}
} else {
if (file.exists()) {
file.delete();
}
if (tmpFile.exists()) {
tmpFile.delete();
}
if (isDebugMode()) {
Log.d("FD: Could not download", "Filename = " + file.toString());
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return ret;
}
}
public static boolean addKeyboard(Context context, HashMap<String, String> keyboardInfo) {
return KeyboardPickerActivity.addKeyboard(context, keyboardInfo);
}
public static boolean removeKeyboard(Context context, int position) {
return KeyboardPickerActivity.removeKeyboard(context, position);
}
public static boolean setKeyboard(String keyboardID, String languageID) {
boolean result1 = false;
boolean result2 = false;
if (InAppKeyboard != null && InAppKeyboardLoaded)
result1 = InAppKeyboard.setKeyboard(keyboardID, languageID);
if (SystemKeyboard != null && SystemKeyboardLoaded)
result2 = SystemKeyboard.setKeyboard(keyboardID, languageID);
return (result1 || result2);
}
public static boolean setKeyboard(String keyboardID, String languageID, String keyboardName, String languageName, String kFont, String kOskFont) {
boolean result1 = false;
boolean result2 = false;
if (InAppKeyboard != null && InAppKeyboardLoaded)
result1 = InAppKeyboard.setKeyboard(keyboardID, languageID, keyboardName, languageName, kFont, kOskFont);
if (SystemKeyboard != null && SystemKeyboardLoaded)
result2 = SystemKeyboard.setKeyboard(keyboardID, languageID, keyboardName, languageName, kFont, kOskFont);
return (result1 || result2);
}
public static boolean setKeyboard(Context context, int position) {
HashMap<String, String> keyboardInfo = KeyboardPickerActivity.getKeyboardInfo(context, position);
if (keyboardInfo == null)
return false;
String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID);
String langId = keyboardInfo.get(KMManager.KMKey_LanguageID);
String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName);
String langName = keyboardInfo.get(KMManager.KMKey_LanguageName);
String kFont = keyboardInfo.get(KMManager.KMKey_Font);
String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont);
return setKeyboard(kbId, langId, kbName, langName, kFont, kOskFont);
}
public static void switchToNextKeyboard(Context context) {
int index = KeyboardPickerActivity.getCurrentKeyboardIndex(context);
index++;
HashMap<String, String> kbInfo = KeyboardPickerActivity.getKeyboardInfo(context, index);
if (kbInfo == null) {
index = 0;
kbInfo = KeyboardPickerActivity.getKeyboardInfo(context, index);
}
String kbId = kbInfo.get(KMManager.KMKey_KeyboardID);
String langId = kbInfo.get(KMManager.KMKey_LanguageID);
String kbName = kbInfo.get(KMManager.KMKey_KeyboardName);
String langName = kbInfo.get(KMManager.KMKey_LanguageName);
String kFont = kbInfo.get(KMManager.KMKey_Font);
String kOskFont = kbInfo.get(KMManager.KMKey_OskFont);
if (InAppKeyboard != null)
InAppKeyboard.setKeyboard(kbId, langId, kbName, langName, kFont, kOskFont);
if (SystemKeyboard != null)
SystemKeyboard.setKeyboard(kbId, langId, kbName, langName, kFont, kOskFont);
}
public static String getKeyboardTextFontFilename() {
return KMKeyboard.textFontFilename();
}
public static Typeface getKeyboardTextFontTypeface(Context context) {
return getFontTypeface(context, getKeyboardTextFontFilename());
}
public static String getKeyboardOskFontFilename() {
return KMKeyboard.oskFontFilename();
}
public static Typeface getKeyboardOskFontTypeface(Context context) {
return getFontTypeface(context, getKeyboardOskFontFilename());
}
public static KeyboardState getKeyboardState(Context context, String keyboardID, String languageID) {
KeyboardState kbState = KeyboardState.KEYBOARD_STATE_UNDEFINED;
if (keyboardID == null || languageID == null)
return kbState;
keyboardID = keyboardID.trim();
languageID = languageID.trim();
if (keyboardID.isEmpty() || languageID.isEmpty())
return kbState;
String latestVersion = getLatestKeyboardFileVersion(context, keyboardID);
if (latestVersion == null) {
kbState = KeyboardState.KEYBOARD_STATE_NEEDS_DOWNLOAD;
} else {
kbState = KeyboardState.KEYBOARD_STATE_UP_TO_DATE;
HashMap<String, HashMap<String, String>> keyboardsInfo = LanguageListActivity.getKeyboardsInfo(context);
if (keyboardsInfo != null) {
// Check version
String kbKey = String.format("%s_%s", languageID, keyboardID);
HashMap<String, String> kbInfo = keyboardsInfo.get(kbKey);
String kbVersion = "1.0";
if (kbInfo != null)
kbVersion = kbInfo.get(KMManager.KMKey_KeyboardVersion);
try {
if (kbVersion != null && compareVersions(kbVersion, latestVersion) > 0)
kbState = KeyboardState.KEYBOARD_STATE_NEEDS_UPDATE;
} catch (Exception e) {
Log.e("getKeyboardState", "Error: " + e);
}
}
}
return kbState;
}
public static String getLatestKeyboardFileVersion(Context context, String keyboardID) {
String kbFileVersion = null;
String path = context.getDir("data", Context.MODE_PRIVATE) + "/languages/";
File dir = new File(path);
String[] files = dir.list();
if (files == null)
return kbFileVersion;
for (String file : files) {
if (!file.endsWith(".js"))
continue;
String base = String.format("%s-", keyboardID);
int index = file.indexOf(base);
if (index == 0) {
int firstIndex = base.length();
int lastIndex = file.lastIndexOf(".js");
String v = file.substring(firstIndex, lastIndex);
if (kbFileVersion != null) {
if (compareVersions(v, kbFileVersion) > 0) {
kbFileVersion = v;
}
} else if (compareVersions(v, v) == 0) {
kbFileVersion = v;
}
}
}
return kbFileVersion;
}
public static int compareVersions(String v1, String v2) {
// returns;
// -2 if v1 or v2 is invalid
// 0 if v1 = v2
// -1 if v1 < v2
// 1 if v1 > v2
if (v1 == null || v2 == null) {
return -2;
}
if (v1.isEmpty() || v2.isEmpty()) {
return -2;
}
String[] v1Values = v1.split("\\.");
String[] v2Values = v2.split("\\.");
int len = (v1Values.length >= v2Values.length ? v1Values.length : v2Values.length);
for (int i = 0; i < len; i++) {
String vStr1 = "0";
if (i < v1Values.length) {
vStr1 = v1Values[i];
}
String vStr2 = "0";
if (i < v2Values.length) {
vStr2 = v2Values[i];
}
Integer vInt1 = parseInteger(vStr1);
Integer vInt2 = parseInteger(vStr2);
int iV1, iV2, iV1_, iV2_;
if (vInt1 != null) {
iV1 = vInt1.intValue();
iV1_ = 0;
} else {
iV1 = 0;
iV1_ = 0;
}
if (vInt2 != null) {
iV2 = vInt2.intValue();
iV2_ = 0;
} else {
iV2 = 0;
iV2_ = 0;
}
if (vInt1 == null) {
if (i != (v1Values.length - 1)) {
return -2;
}
if (vStr1.toLowerCase().endsWith("b")) {
Integer vInt1_ = parseInteger(vStr1.substring(0, vStr1.length() - 1));
if (vInt1_ == null) {
return -2;
}
iV1 = vInt1_.intValue();
iV1_ = -100;
} else if (vStr1.toLowerCase().endsWith("a")) {
Integer vInt1_ = parseInteger(vStr1.substring(0, vStr1.length() - 1));
if (vInt1_ == null) {
return -2;
}
iV1 = vInt1_.intValue();
iV1_ = -200;
} else {
return -2;
}
}
if (vInt2 == null) {
if (i != (v2Values.length - 1)) {
return -2;
}
if (vStr2.toLowerCase().endsWith("b")) {
Integer vInt2_ = parseInteger(vStr2.substring(0, vStr2.length() - 1));
if (vInt2_ == null) {
return -2;
}
iV2 = vInt2_.intValue();
iV2_ = -100;
} else if (vStr2.toLowerCase().endsWith("a")) {
Integer vInt2_ = parseInteger(vStr2.substring(0, vStr2.length() - 1));
if (vInt2_ == null) {
return -2;
}
iV2 = vInt2_.intValue();
iV2_ = -200;
} else {
return -2;
}
}
if (iV1 == iV2) {
if (iV1_ == iV2_) {
continue;
}
if (iV1_ < iV2_) {
return -1;
}
if (iV1_ > iV2_) {
return 1;
}
} else if (iV1 < iV2) {
return -1;
} else if (iV1 > iV2) {
return 1;
}
}
return 0;
}
private static Integer parseInteger(String s) {
Integer retVal = null;
try {
int i = Integer.parseInt(s);
retVal = new Integer(i);
} catch (Exception e) {
retVal = null;
}
return retVal;
}
public static void addKeyboardEventListener(OnKeyboardEventListener listener) {
KMTextView.addOnKeyboardEventListener(listener);
KMKeyboard.addOnKeyboardEventListener(listener);
}
public static void removeKeyboardEventListener(OnKeyboardEventListener listener) {
KMTextView.removeOnKeyboardEventListener(listener);
KMKeyboard.removeOnKeyboardEventListener(listener);
}
public static void addKeyboardDownloadEventListener(OnKeyboardDownloadEventListener listener) {
if (kbDownloadEventListeners == null) {
kbDownloadEventListeners = new ArrayList<OnKeyboardDownloadEventListener>();
}
if (listener != null && !kbDownloadEventListeners.contains(listener)) {
kbDownloadEventListeners.add(listener);
}
}
public static void removeKeyboardDownloadEventListener(OnKeyboardDownloadEventListener listener) {
if (kbDownloadEventListeners != null) {
kbDownloadEventListeners.remove(listener);
}
}
public static int getKeyboardHeight(Context context) {
return (int) context.getResources().getDimension(R.dimen.keyboard_height);
}
public static void setDebugMode(boolean value) {
debugMode = value;
}
public static boolean isDebugMode() {
return debugMode;
}
public static void setShouldAllowSetKeyboard(boolean value) {
shouldAllowSetKeyboard = value;
if (shouldAllowSetKeyboard == false) {
setKeyboard(KMDefault_KeyboardID, KMDefault_LanguageID, KMDefault_KeyboardName, KMDefault_LanguageName, KMDefault_KeyboardFont, null);
}
}
public static boolean shouldAllowSetKeyboard() {
return shouldAllowSetKeyboard;
}
public static void showKeyboardPicker(Context context, KeyboardType kbType) {
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
Intent i = new Intent(context, KeyboardPickerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
context.startActivity(i);
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
Intent i = new Intent(context, KeyboardPickerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public static void setKeyboardPickerFont(Typeface typeface) {
KeyboardPickerActivity.listFont = typeface;
}
public static void showLanguageList(Context context) {
KeyboardPickerActivity.showLanguageList(context);
}
public static boolean updateText(KeyboardType kbType, String text) {
boolean result = false;
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
if (InAppKeyboard != null && InAppKeyboardLoaded && !InAppKeyboardShouldIgnoreTextChange) {
String kmText = "";
if (text != null) {
kmText = text.toString().replace("\\", "\\u005C").replace("'", "\\u0027").replace("\n", "\\n");
}
InAppKeyboard.loadUrl(String.format("javascript:updateKMText('%s')", kmText));
result = true;
}
InAppKeyboardShouldIgnoreTextChange = false;
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
if (SystemKeyboard != null && SystemKeyboardLoaded && !SystemKeyboardShouldIgnoreTextChange) {
String kmText = "";
if (text != null) {
kmText = text.toString().replace("\\", "\\u005C").replace("'", "\\u0027").replace("\n", "\\n");
}
SystemKeyboard.loadUrl(String.format("javascript:updateKMText('%s')", kmText));
result = true;
}
SystemKeyboardShouldIgnoreTextChange = false;
}
return result;
}
public static boolean updateSelectionRange(KeyboardType kbType, int selStart, int selEnd) {
boolean result = false;
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
if (InAppKeyboard != null && InAppKeyboardLoaded && !InAppKeyboardShouldIgnoreSelectionChange) {
InAppKeyboard.loadUrl(String.format("javascript:updateKMSelectionRange(%d,%d)", selStart, selEnd));
result = true;
}
InAppKeyboardShouldIgnoreSelectionChange = false;
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
if (SystemKeyboard != null && SystemKeyboardLoaded && !SystemKeyboardShouldIgnoreSelectionChange) {
InputConnection ic = (IMService != null ? IMService.getCurrentInputConnection() : null);
if (ic != null) {
ExtractedText icText = ic.getExtractedText(new ExtractedTextRequest(), 0);
if (icText != null) {
updateText(kbType, icText.text.toString());
}
}
SystemKeyboard.loadUrl(String.format("javascript:updateKMSelectionRange(%d,%d)", selStart, selEnd));
result = true;
}
SystemKeyboardShouldIgnoreSelectionChange = false;
}
return result;
}
public static void resetContext(KeyboardType kbType) {
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
if (InAppKeyboard != null && InAppKeyboardLoaded) {
InAppKeyboard.loadUrl("javascript:resetContext()");
}
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
if (SystemKeyboard != null && SystemKeyboardLoaded) {
SystemKeyboard.loadUrl("javascript:resetContext()");
}
}
}
public static int getCurrentKeyboardIndex(Context context) {
return KeyboardPickerActivity.getCurrentKeyboardIndex(context);
}
public static HashMap<String, String> getCurrentKeyboardInfo(Context context) {
return KeyboardPickerActivity.getCurrentKeyboardInfo(context);
}
public static int getKeyboardIndex(Context context, String keyboardID, String languageID) {
int index = -1;
if (keyboardID != null & languageID != null) {
String kbKey = String.format("%s_%s", languageID, keyboardID);
index = KeyboardPickerActivity.getKeyboardIndex(context, kbKey);
}
return index;
}
public static HashMap<String, String> getKeyboardInfo(Context context, int index) {
return KeyboardPickerActivity.getKeyboardInfo(context, index);
}
public static boolean keyboardExists(Context context, String keyboardID, String languageID) {
boolean result = false;
if (keyboardID != null & languageID != null) {
String kbKey = String.format("%s_%s", languageID, keyboardID);
result = KeyboardPickerActivity.containsKeyboard(context, kbKey);
}
return result;
}
public static boolean isHelpBubbleEnabled() {
boolean retVal = true;
if (InAppKeyboard != null) {
retVal = InAppKeyboard.isHelpBubbleEnabled;
} else if (SystemKeyboard != null) {
retVal = SystemKeyboard.isHelpBubbleEnabled;
}
return retVal;
}
public static void setHelpBubbleEnabled(boolean newValue) {
if (InAppKeyboard != null) {
InAppKeyboard.isHelpBubbleEnabled = newValue;
}
if (SystemKeyboard != null) {
SystemKeyboard.isHelpBubbleEnabled = newValue;
}
}
public static boolean canAddNewKeyboard() {
return KeyboardPickerActivity.canAddNewKeyboard;
}
public static void setCanAddNewKeyboard(boolean newValue) {
KeyboardPickerActivity.canAddNewKeyboard = newValue;
}
public static boolean canRemoveKeyboard() {
return KeyboardPickerActivity.canRemoveKeyboard;
}
public static void setCanRemoveKeyboard(boolean newValue) {
KeyboardPickerActivity.canRemoveKeyboard = newValue;
}
public static boolean shouldCheckKeyboardUpdates() {
return KeyboardPickerActivity.shouldCheckKeyboardUpdates;
}
public static void setShouldCheckKeyboardUpdates(boolean newValue) {
KeyboardPickerActivity.shouldCheckKeyboardUpdates = newValue;
}
public static GlobeKeyAction getGlobeKeyAction(KeyboardType kbType) {
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
return inappKbGlobeKeyAction;
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
return sysKbGlobeKeyAction;
} else {
return GlobeKeyAction.GLOBE_KEY_ACTION_DO_NOTHING;
}
}
public static void setGlobeKeyAction(KeyboardType kbType, GlobeKeyAction action) {
if (kbType == KeyboardType.KEYBOARD_TYPE_INAPP) {
inappKbGlobeKeyAction = action;
} else if (kbType == KeyboardType.KEYBOARD_TYPE_SYSTEM) {
sysKbGlobeKeyAction = action;
}
}
protected static final class KMInAppKeyboardWebViewClient extends WebViewClient {
public static Context context;
KMInAppKeyboardWebViewClient(Context context) {
KMInAppKeyboardWebViewClient.context = context;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.endsWith(KMFilename_KeyboardHtml)) {
InAppKeyboardLoaded = false;
}
}
@Override
public void onPageFinished(WebView view, String url) {
if (url.endsWith(KMFilename_KeyboardHtml)) {
InAppKeyboardLoaded = true;
if (isDebugMode()) {
Log.d("KMManager", "In-App Keyboard loaded.");
}
if (!InAppKeyboard.keyboardSet) {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
int index = prefs.getInt(KMManager.KMKey_UserKeyboardIndex, 0);
if (index < 0) {
index = 0;
}
HashMap<String, String> keyboardInfo = KMManager.getKeyboardInfo(context, index);
if (keyboardInfo != null) {
String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID);
String langId = keyboardInfo.get(KMManager.KMKey_LanguageID);
String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName);
String langName = keyboardInfo.get(KMManager.KMKey_LanguageName);
String kFont = keyboardInfo.get(KMManager.KMKey_Font);
String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont);
InAppKeyboard.setKeyboard(kbId, langId, kbName, langName, kFont, kOskFont);
} else {
InAppKeyboard.setKeyboard(KMDefault_KeyboardID, KMDefault_LanguageID, KMDefault_KeyboardName, KMDefault_LanguageName, KMDefault_KeyboardFont, null);
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
if (prefs.getBoolean(KMManager.KMKey_ShouldShowHelpBubble, true)) {
InAppKeyboard.loadUrl("javascript:showHelpBubble()");
}
}
}, 2000);
KeyboardEventHandler.notifyListeners(KMTextView.kbEventListeners, KeyboardType.KEYBOARD_TYPE_INAPP, EventType.KEYBOARD_LOADED, null);
}
shouldOverrideUrlLoading(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("hideKeyboard") >= 0) {
if (KMTextView.activeView != null && KMTextView.activeView.getClass() == KMTextView.class) {
InAppKeyboard.dismissHelpBubble();
KMTextView textView = (KMTextView) KMTextView.activeView;
textView.dismissKeyboard();
}
} else if (url.indexOf("globeKeyAction") >= 0) {
InAppKeyboard.dismissHelpBubble();
if (!InAppKeyboard.isHelpBubbleEnabled) {
return false;
}
SharedPreferences prefs = appContext.getSharedPreferences(appContext.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(KMManager.KMKey_ShouldShowHelpBubble, false);
editor.commit();
if (KMManager.shouldAllowSetKeyboard()) {
if (InAppKeyboard.keyboardPickerEnabled) {
if (inappKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU) {
showKeyboardPicker(context, KeyboardType.KEYBOARD_TYPE_INAPP);
} else if (inappKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD) {
switchToNextKeyboard(context);
}
} else {
switchToNextKeyboard(context);
}
}
} else if (url.indexOf("showHelpBubble") >= 0) {
int start = url.indexOf("keyPos=") + 7;
String value = url.substring(start);
if (!value.isEmpty()) {
String[] globeKeyPos = value.split("\\,");
float fx = Float.valueOf(globeKeyPos[0]);
float fy = Float.valueOf(globeKeyPos[1]);
if (InAppKeyboard.getVisibility() == View.VISIBLE)
InAppKeyboard.showHelpBubble(context, fx, fy);
}
} else if (url.indexOf("showKeyPreview") >= 0) {
String deviceType = context.getResources().getString(R.string.device_type);
if (deviceType.equals("AndroidTablet")) {
return false;
}
if (InAppKeyboard.subKeysWindow != null) {
return false;
}
int start = url.indexOf("x=") + 2;
int end = url.indexOf("+y=");
float x = Float.valueOf(url.substring(start, end));
start = url.indexOf("y=") + 2;
end = url.indexOf("+w=");
float y = Float.valueOf(url.substring(start, end));
start = url.indexOf("w=") + 2;
end = url.indexOf("+h=");
float w = Float.valueOf(url.substring(start, end));
start = url.indexOf("h=") + 2;
end = url.indexOf("+t=");
float h = Float.valueOf(url.substring(start, end));
start = url.indexOf("t=") + 2;
String t = url.substring(start);
String text = "";
String[] values = t.split("\\,");
int length = values.length;
for (int i = 0; i < length; i++) {
if (values[i].startsWith("0x")) {
int c = Integer.parseInt(values[i].substring(2), 16);
text += String.valueOf((char) c);
}
}
float left = x - w / 2.0f;
float right = left + w;
float top = y - 1;
float bottom = top + h;
RectF keyFrame = new RectF(left, top, right, bottom);
InAppKeyboard.showKeyPreview(context, (int) x, (int) y, keyFrame, text);
} else if (url.indexOf("dismissKeyPreview") >= 0) {
InAppKeyboard.dismissKeyPreview(100);
} else if (url.indexOf("showMore") >= 0) {
if (InAppKeyboard.subKeysWindow != null && InAppKeyboard.subKeysWindow.isShowing()) {
return false;
}
int start = url.indexOf("keyPos=") + 7;
int end = url.indexOf("+keys=");
InAppKeyboard.subKeysWindowPos = url.substring(start, end).split("\\,");
start = end + 6;
end = url.indexOf("+font=");
if (end < 0) {
end = url.length();
InAppKeyboard.specialOskFont = "";
} else {
InAppKeyboard.specialOskFont = "keymanweb-osk.ttf";
}
String keys = url.substring(start, end);
String[] keyList = keys.split("\\;");
int klCount = keyList.length;
InAppKeyboard.subKeysList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < klCount; i++) {
String[] values = keyList[i].split("\\:");
String keyId = "";
String keyText = "";
if (values.length == 2) {
keyId = values[0];
keyText = values[1];
} else if (values.length == 1) {
keyId = values[0];
keyText = values[0];
int index = keyText.indexOf("-");
if (index >= 0) {
keyText = keyText.substring(index + 1);
}
}
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("keyId", keyId);
hashMap.put("keyText", keyText);
InAppKeyboard.subKeysList.add(hashMap);
}
}
return false;
}
}
protected static final class KMSystemKeyboardWebViewClient extends WebViewClient {
public static Context context;
KMSystemKeyboardWebViewClient(Context context) {
KMSystemKeyboardWebViewClient.context = context;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.endsWith(KMFilename_KeyboardHtml)) {
SystemKeyboardLoaded = false;
}
}
@Override
public void onPageFinished(WebView view, String url) {
if (url.endsWith(KMFilename_KeyboardHtml)) {
SystemKeyboardLoaded = true;
if (isDebugMode()) {
Log.d("KMManager", "System Keyboard loaded.");
}
if (!SystemKeyboard.keyboardSet) {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
int index = prefs.getInt(KMManager.KMKey_UserKeyboardIndex, 0);
if (index < 0) {
index = 0;
}
HashMap<String, String> keyboardInfo = KMManager.getKeyboardInfo(context, index);
if (keyboardInfo != null) {
String kbId = keyboardInfo.get(KMManager.KMKey_KeyboardID);
String langId = keyboardInfo.get(KMManager.KMKey_LanguageID);
String kbName = keyboardInfo.get(KMManager.KMKey_KeyboardName);
String langName = keyboardInfo.get(KMManager.KMKey_LanguageName);
String kFont = keyboardInfo.get(KMManager.KMKey_Font);
String kOskFont = keyboardInfo.get(KMManager.KMKey_OskFont);
SystemKeyboard.setKeyboard(kbId, langId, kbName, langName, kFont, kOskFont);
} else {
SystemKeyboard.setKeyboard(KMDefault_KeyboardID, KMDefault_LanguageID, KMDefault_KeyboardName, KMDefault_LanguageName, KMDefault_KeyboardFont, null);
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
if (prefs.getBoolean(KMManager.KMKey_ShouldShowHelpBubble, true)) {
SystemKeyboard.loadUrl("javascript:showHelpBubble()");
}
}
}, 2000);
KeyboardEventHandler.notifyListeners(KMTextView.kbEventListeners, KeyboardType.KEYBOARD_TYPE_SYSTEM, EventType.KEYBOARD_LOADED, null);
}
shouldOverrideUrlLoading(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("hideKeyboard") >= 0) {
SystemKeyboard.dismissHelpBubble();
IMService.requestHideSelf(0);
} else if (url.indexOf("globeKeyAction") >= 0) {
SystemKeyboard.dismissHelpBubble();
if (!SystemKeyboard.isHelpBubbleEnabled) {
return false;
}
SharedPreferences prefs = appContext.getSharedPreferences(appContext.getString(R.string.kma_prefs_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(KMManager.KMKey_ShouldShowHelpBubble, false);
editor.commit();
if (KMManager.shouldAllowSetKeyboard()) {
if (SystemKeyboard.keyboardPickerEnabled) {
if (sysKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SHOW_MENU) {
showKeyboardPicker(context, KeyboardType.KEYBOARD_TYPE_SYSTEM);
} else if (sysKbGlobeKeyAction == GlobeKeyAction.GLOBE_KEY_ACTION_SWITCH_TO_NEXT_KEYBOARD) {
switchToNextKeyboard(context);
}
} else {
switchToNextKeyboard(context);
}
}
} else if (url.indexOf("showHelpBubble") >= 0) {
int start = url.indexOf("keyPos=") + 7;
String value = url.substring(start);
if (!value.isEmpty()) {
String[] globeKeyPos = value.split("\\,");
float fx = Float.valueOf(globeKeyPos[0]);
float fy = Float.valueOf(globeKeyPos[1]);
SystemKeyboard.showHelpBubble(context, fx, fy);
}
} else if (url.indexOf("showKeyPreview") >= 0) {
String deviceType = context.getResources().getString(R.string.device_type);
if (deviceType.equals("AndroidTablet")) {
return false;
}
if (SystemKeyboard.subKeysWindow != null) {
return false;
}
int start = url.indexOf("x=") + 2;
int end = url.indexOf("+y=");
float x = Float.valueOf(url.substring(start, end));
start = url.indexOf("y=") + 2;
end = url.indexOf("+w=");
float y = Float.valueOf(url.substring(start, end));
start = url.indexOf("w=") + 2;
end = url.indexOf("+h=");
float w = Float.valueOf(url.substring(start, end));
start = url.indexOf("h=") + 2;
end = url.indexOf("+t=");
float h = Float.valueOf(url.substring(start, end));
start = url.indexOf("t=") + 2;
String t = url.substring(start);
String text = "";
String[] values = t.split("\\,");
int length = values.length;
for (int i = 0; i < length; i++) {
if (values[i].startsWith("0x")) {
int c = Integer.parseInt(values[i].substring(2), 16);
text += String.valueOf((char) c);
}
}
float left = x - w / 2.0f;
float right = left + w;
float top = y - 1;
float bottom = top + h;
RectF keyFrame = new RectF(left, top, right, bottom);
SystemKeyboard.showKeyPreview(context, (int) x, (int) y, keyFrame, text);
} else if (url.indexOf("dismissKeyPreview") >= 0) {
SystemKeyboard.dismissKeyPreview(100);
} else if (url.indexOf("showMore") >= 0) {
if (SystemKeyboard.subKeysWindow != null && SystemKeyboard.subKeysWindow.isShowing()) {
return false;
}
int start = url.indexOf("keyPos=") + 7;
int end = url.indexOf("+keys=");
SystemKeyboard.subKeysWindowPos = url.substring(start, end).split("\\,");
start = end + 6;
end = url.indexOf("+font=");
if (end < 0) {
end = url.length();
SystemKeyboard.specialOskFont = "";
} else {
SystemKeyboard.specialOskFont = "keymanweb-osk.ttf";
}
String keys = url.substring(start, end);
String[] keyList = keys.split("\\;");
int klCount = keyList.length;
SystemKeyboard.subKeysList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < klCount; i++) {
String[] values = keyList[i].split("\\:");
String keyId = "";
String keyText = "";
if (values.length == 2) {
keyId = values[0];
keyText = values[1];
} else if (values.length == 1) {
keyId = values[0];
keyText = values[0];
int index = keyText.indexOf("-");
if (index >= 0)
keyText = keyText.substring(index + 1);
}
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("keyId", keyId);
hashMap.put("keyText", keyText);
SystemKeyboard.subKeysList.add(hashMap);
}
}
return false;
}
}
private static final class KMInAppKeyboardJSHandler {
private Context context;
KMInAppKeyboardJSHandler(Context context) {
this.context = context;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public String getDeviceType() {
return context.getResources().getString(R.string.device_type);
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public int getKeyboardHeight() {
int kbHeight = context.getResources().getDimensionPixelSize(R.dimen.keyboard_height);
kbHeight -= kbHeight % 20;
return kbHeight;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public int getKeyboardWidth() {
DisplayMetrics dms = context.getResources().getDisplayMetrics();
int kbWidth = (int) (dms.widthPixels / dms.density);
return kbWidth;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void insertText(final int dn, final String s) {
Handler mainLoop = new Handler(Looper.getMainLooper());
mainLoop.post(new Runnable() {
public void run() {
if (InAppKeyboard.subKeysWindow != null || KMTextView.activeView == null || KMTextView.activeView.getClass() != KMTextView.class) {
if (KMTextView.activeView == null)
Log.w("IAK: JS Handler", "insertText failed: activeView is null");
return;
}
InAppKeyboard.dismissHelpBubble();
KMTextView textView = (KMTextView) KMTextView.activeView;
textView.beginBatchEdit();
int start = textView.getSelectionStart();
int end = textView.getSelectionEnd();
if (dn <= 0) {
if (start == end) {
if (!s.isEmpty() && s.charAt(0) == '\n') {
textView.keyDownUp(KeyEvent.KEYCODE_ENTER);
} else {
InAppKeyboardShouldIgnoreTextChange = true;
InAppKeyboardShouldIgnoreSelectionChange = true;
textView.getText().insert(start, s);
}
} else {
if (!s.isEmpty() && s.charAt(0) == '\n') {
InAppKeyboardShouldIgnoreTextChange = true;
InAppKeyboardShouldIgnoreSelectionChange = true;
textView.getText().replace(start, end, "");
textView.keyDownUp(KeyEvent.KEYCODE_ENTER);
} else {
if (s.isEmpty()) {
textView.getText().delete(start, end);
} else {
InAppKeyboardShouldIgnoreTextChange = true;
InAppKeyboardShouldIgnoreSelectionChange = true;
textView.getText().replace(start, end, s);
}
}
}
} else {
for (int i = 0; i < dn; i++) {
CharSequence chars = textView.getText().subSequence(0, start);
if (chars != null && chars.length() > 0) {
char c = chars.charAt(start - 1);
InAppKeyboardShouldIgnoreTextChange = true;
InAppKeyboardShouldIgnoreSelectionChange = true;
if (Character.isLowSurrogate(c)) {
textView.getText().delete(start - 2, end);
} else {
textView.getText().delete(start - 1, end);
}
start = textView.getSelectionStart();
end = textView.getSelectionEnd();
}
}
if (s.length() > 0) {
InAppKeyboardShouldIgnoreTextChange = true;
InAppKeyboardShouldIgnoreSelectionChange = true;
textView.getText().insert(start, s);
}
}
textView.endBatchEdit();
}
});
}
}
private static final class KMSystemKeyboardJSHandler {
private Context context;
KMSystemKeyboardJSHandler(Context context) {
this.context = context;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public String getDeviceType() {
return context.getResources().getString(R.string.device_type);
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public int getKeyboardHeight() {
int kbHeight = context.getResources().getDimensionPixelSize(R.dimen.keyboard_height);
kbHeight -= kbHeight % 20;
return kbHeight;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public int getKeyboardWidth() {
DisplayMetrics dms = context.getResources().getDisplayMetrics();
int kbWidth = (int) (dms.widthPixels / dms.density);
return kbWidth;
}
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void insertText(final int dn, final String s) {
Handler mainLoop = new Handler(Looper.getMainLooper());
mainLoop.post(new Runnable() {
public void run() {
if (SystemKeyboard.subKeysWindow != null) {
return;
}
InputConnection ic = IMService.getCurrentInputConnection();
if (ic == null) {
Log.w("SWK: JS Handler", "insertText failed: InputConnection is null");
return;
}
SystemKeyboard.dismissHelpBubble();
ic.beginBatchEdit();
ExtractedText icText = ic.getExtractedText(new ExtractedTextRequest(), 0);
if (icText != null) { // This can be null if the input connection becomes invalid.
int start = icText.startOffset + icText.selectionStart;
int end = icText.startOffset + icText.selectionEnd;
if (end > start) {
if (s.length() == 0) {
ic.setSelection(start, start);
ic.deleteSurroundingText(0, end - start);
ic.endBatchEdit();
return;
} else {
SystemKeyboardShouldIgnoreSelectionChange = true;
ic.setSelection(start, start);
ic.deleteSurroundingText(0, end - start);
}
}
}
if (s.length() > 0 && s.charAt(0) == '\n') {
keyDownUp(KeyEvent.KEYCODE_ENTER);
ic.endBatchEdit();
return;
}
for (int i = 0; i < dn; i++) {
CharSequence chars = ic.getTextBeforeCursor(1, 0);
if (chars != null && chars.length() > 0) {
char c = chars.charAt(0);
SystemKeyboardShouldIgnoreSelectionChange = true;
if (Character.isLowSurrogate(c)) {
ic.deleteSurroundingText(2, 0);
} else {
ic.deleteSurroundingText(1, 0);
}
}
}
if (s.length() > 0) {
SystemKeyboardShouldIgnoreSelectionChange = true;
ic.commitText(s, s.length());
}
ic.endBatchEdit();
}
});
}
private void keyDownUp(int keyEventCode) {
IMService.getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
IMService.getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));
}
}
}
|
package com.taobao.weex.dom;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.UnderlineSpan;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.common.Constants;
import com.taobao.weex.dom.flex.CSSConstants;
import com.taobao.weex.dom.flex.CSSNode;
import com.taobao.weex.dom.flex.FloatUtil;
import com.taobao.weex.dom.flex.MeasureOutput;
import com.taobao.weex.ui.component.WXText;
import com.taobao.weex.ui.component.WXTextDecoration;
import com.taobao.weex.utils.WXDomUtils;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.utils.WXResourceUtils;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static com.taobao.weex.dom.WXStyle.UNSET;
/**
* Class for calculating a given text's height and width. The calculating of width and height of
* text is done by {@link Layout}.
*/
public class WXTextDomObject extends WXDomObject {
/**
* Command object for setSpan
*/
private static class SetSpanOperation {
protected int start, end;
protected Object what;
SetSpanOperation(int start, int end, Object what) {
this.start = start;
this.end = end;
this.what = what;
}
public void execute(Spannable sb) {
sb.setSpan(what, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
/**
* Object for calculating text's width and height. This class is an anonymous class of
* implementing {@link com.taobao.weex.dom.flex.CSSNode.MeasureFunction}
*/
/** package **/ static final CSSNode.MeasureFunction TEXT_MEASURE_FUNCTION = new CSSNode.MeasureFunction() {
@Override
public void measure(CSSNode node, float width, @NonNull MeasureOutput measureOutput) {
WXTextDomObject textDomObject = (WXTextDomObject) node;
if (CSSConstants.isUndefined(width)) {
width = node.cssstyle.maxWidth;
}
if(textDomObject.getTextWidth(textDomObject.mTextPaint,width,false)>0) {
textDomObject.layout = textDomObject.createLayout(width, false, null);
textDomObject.hasBeenMeasured = true;
textDomObject.previousWidth = textDomObject.layout.getWidth();
measureOutput.height = textDomObject.layout.getHeight();
measureOutput.width = textDomObject.previousWidth;
}else{
measureOutput.height = 0;
measureOutput.width = 0;
}
}
};
private static final Canvas DUMMY_CANVAS = new Canvas();
private static final String ELLIPSIS = "\u2026";
private boolean mIsColorSet = false;
private boolean hasBeenMeasured = false;
private int mColor;
/**
* mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}.
*/
private int mFontStyle = UNSET;
/**
* mFontWeight can be {@link Typeface#NORMAL} or {@link Typeface#BOLD}.
*/
private int mFontWeight = UNSET;
private int mNumberOfLines = UNSET;
private int mFontSize = UNSET;
private int mLineHeight = UNSET;
private float previousWidth = Float.NaN;
private String mFontFamily = null;
private String mText = null;
private TextUtils.TruncateAt textOverflow;
private Layout.Alignment mAlignment;
private WXTextDecoration mTextDecoration = WXTextDecoration.NONE;
private TextPaint mTextPaint = new TextPaint();
private @Nullable Spanned spanned;
private @Nullable Layout layout;
private AtomicReference<Layout> atomicReference = new AtomicReference<>();
/**
* Create an instance of current class, and set {@link #TEXT_MEASURE_FUNCTION} as the
* measureFunction
* @see CSSNode#setMeasureFunction(MeasureFunction)
*/
public WXTextDomObject() {
super();
mTextPaint.setFlags(TextPaint.ANTI_ALIAS_FLAG);
setMeasureFunction(TEXT_MEASURE_FUNCTION);
}
public TextPaint getTextPaint() {
return mTextPaint;
}
/**
* Prepare the text {@link Spanned} for calculating text's size. This is done by setting
* various text span to the text.
* @see android.text.style.CharacterStyle
*/
@Override
public void layoutBefore() {
hasBeenMeasured = false;
updateStyleAndText();
spanned = createSpanned(mText);
super.dirty();
super.layoutBefore();
}
@Override
public void layoutAfter() {
if (hasBeenMeasured) {
if (layout != null &&
!FloatUtil.floatsEqual(WXDomUtils.getContentWidth(this), previousWidth)) {
recalculateLayout();
}
} else {
updateStyleAndText();
recalculateLayout();
}
hasBeenMeasured = false;
if (layout != null && !layout.equals(atomicReference.get()) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//TODO Warm up, a profile should be used to see the improvement.
warmUpTextLayoutCache(layout);
}
swap();
super.layoutAfter();
}
@Override
public Layout getExtra() {
return atomicReference.get();
}
@Override
public void updateAttr(Map<String, Object> attrs) {
swap();
super.updateAttr(attrs);
if (attrs.containsKey(Constants.Name.VALUE)) {
mText = WXAttr.getValue(attrs);
}
}
@Override
public void updateStyle(Map<String, Object> styles) {
swap();
super.updateStyle(styles);
updateStyleImp(styles);
}
@Override
public WXTextDomObject clone() {
WXTextDomObject dom = null;
try {
dom = new WXTextDomObject();
copyFields(dom);
dom.hasBeenMeasured = hasBeenMeasured;
dom.atomicReference = atomicReference;
} catch (Exception e) {
if (WXEnvironment.isApkDebugable()) {
WXLogUtils.e("WXTextDomObject clone error: ", e);
}
}
if (dom != null) {
dom.spanned = spanned;
}
return dom;
}
/**
* RecalculateLayout.
*/
private void recalculateLayout() {
float contentWidth = WXDomUtils.getContentWidth(this);
if (contentWidth > 0) {
spanned = createSpanned(mText);
layout = createLayout(contentWidth, true, layout);
previousWidth = layout.getWidth();
}
}
/**
* Update style and text.
*/
private void updateStyleAndText() {
updateStyleImp(getStyles());
mText = WXAttr.getValue(getAttrs());
}
/**
* Record the property according to the given style
* @param style the give style.
*/
private void updateStyleImp(Map<String, Object> style) {
if (style != null) {
if (style.containsKey(Constants.Name.LINES)) {
int lines = WXStyle.getLines(style);
if (lines > 0) {
mNumberOfLines = lines;
}
}
if (style.containsKey(Constants.Name.FONT_SIZE)) {
mFontSize = WXStyle.getFontSize(style);
}
if (style.containsKey(Constants.Name.FONT_WEIGHT)) {
mFontWeight = WXStyle.getFontWeight(style);
}
if (style.containsKey(Constants.Name.FONT_STYLE)) {
mFontStyle = WXStyle.getFontStyle(style);
}
if (style.containsKey(Constants.Name.COLOR)) {
mColor = WXResourceUtils.getColor(WXStyle.getTextColor(style));
mIsColorSet = mColor != Integer.MIN_VALUE;
}
if (style.containsKey(Constants.Name.TEXT_DECORATION)) {
mTextDecoration = WXStyle.getTextDecoration(style);
}
if (style.containsKey(Constants.Name.FONT_FAMILY)) {
mFontFamily = WXStyle.getFontFamily(style);
}
mAlignment = WXStyle.getTextAlignment(style);
textOverflow = WXStyle.getTextOverflow(style);
int lineHeight = WXStyle.getLineHeight(style);
if (lineHeight != UNSET) {
mLineHeight = lineHeight;
}
}
}
/**
* Update layout according to {@link #mText} and span
* @param width the specified width.
* @param forceWidth If true, force the text width to the specified width, otherwise, text width
* may equals to or be smaller than the specified width.
* @param previousLayout the result of previous layout, could be null.
*/
private
@NonNull
Layout createLayout(float width, boolean forceWidth, @Nullable Layout previousLayout) {
float textWidth;
textWidth = getTextWidth(mTextPaint, width, forceWidth);
Layout layout;
if (!FloatUtil.floatsEqual(previousWidth, textWidth) || previousLayout == null) {
layout = new StaticLayout(spanned, mTextPaint, (int) Math.ceil(textWidth),
Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
} else {
layout = previousLayout;
}
if (mNumberOfLines != UNSET && mNumberOfLines > 0 && mNumberOfLines < layout.getLineCount()) {
int lastLineStart, lastLineEnd;
lastLineStart = layout.getLineStart(mNumberOfLines - 1);
lastLineEnd = layout.getLineEnd(mNumberOfLines - 1);
if (lastLineStart < lastLineEnd) {
String text = mText.subSequence(0, lastLineStart).toString() +
truncate(mText.substring(lastLineStart, lastLineEnd),
mTextPaint, layout.getWidth(), textOverflow);
spanned = createSpanned(text);
return new StaticLayout(spanned, mTextPaint, (int) Math.ceil(textWidth),
Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
}
}
return layout;
}
public @NonNull String truncate(@Nullable String source, @NonNull TextPaint paint,
int desired, @Nullable TextUtils.TruncateAt truncateAt){
if(!TextUtils.isEmpty(source)){
StringBuilder builder;
Spanned spanned;
StaticLayout layout;
for(int i=source.length();i>0;i
builder=new StringBuilder(i+1);
builder.append(source, 0, i);
if(truncateAt!=null){
builder.append(ELLIPSIS);
}
spanned = createSpanned(builder.toString());
layout = new StaticLayout(spanned, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
if(layout.getLineCount()<=1){
return spanned.toString();
}
}
}
return "";
}
/**
* Get text width according to constrain of outerWidth with and forceToDesired
* @param textPaint paint used to measure text
* @param outerWidth the width that css-layout desired.
* @param forceToDesired if set true, the return value will be outerWidth, no matter what the width
* of text is.
* @return if forceToDesired is false, it will be the minimum value of the width of text and
* outerWidth in case of outerWidth is defined, in other case, it will be outer width.
*/
/** package **/ float getTextWidth(TextPaint textPaint,float outerWidth, boolean forceToDesired) {
float textWidth;
if (forceToDesired) {
textWidth = outerWidth;
} else {
float desiredWidth = Layout.getDesiredWidth(spanned, textPaint);
if (CSSConstants.isUndefined(outerWidth) || desiredWidth < outerWidth) {
textWidth = desiredWidth;
} else {
textWidth = outerWidth;
}
}
return textWidth;
}
/**
* Update {@link #spanned} according to the give charSequence and styles
* @param text the give raw text.
* @return an Spanned contains text and spans
*/
private
@NonNull
Spanned createSpanned(String text) {
if (!TextUtils.isEmpty(text)) {
SpannableString spannable = new SpannableString(text);
List<SetSpanOperation> ops = createSetSpanOperation(spannable.length());
if (mFontSize == UNSET) {
ops.add(new SetSpanOperation(0, spannable.length(),
new AbsoluteSizeSpan(WXText.sDEFAULT_SIZE)));
}
Collections.reverse(ops);
for (SetSpanOperation op : ops) {
op.execute(spannable);
}
return spannable;
}
return new SpannableString("");
}
/**
* Create a task list which contains {@link SetSpanOperation}. The task list will be executed
* in other method.
* @param end the end character of the text.
* @return a task list which contains {@link SetSpanOperation}.
*/
private List<SetSpanOperation> createSetSpanOperation(int end) {
List<SetSpanOperation> ops = new LinkedList<>();
int start = 0;
if (end >= start) {
if (mTextDecoration == WXTextDecoration.UNDERLINE) {
ops.add(new SetSpanOperation(start, end,
new UnderlineSpan()));
}
if (mTextDecoration == WXTextDecoration.LINETHROUGH) {
ops.add(new SetSpanOperation(start, end,
new StrikethroughSpan()));
}
if (mIsColorSet) {
ops.add(new SetSpanOperation(start, end,
new ForegroundColorSpan(mColor)));
}
if (mFontSize != UNSET) {
ops.add(new SetSpanOperation(start, end, new AbsoluteSizeSpan(mFontSize)));
}
if (mFontStyle != UNSET
|| mFontWeight != UNSET
|| mFontFamily != null) {
ops.add(new SetSpanOperation(start, end,
new WXCustomStyleSpan(mFontStyle, mFontWeight, mFontFamily)));
}
ops.add(new SetSpanOperation(start, end, new AlignmentSpan.Standard(mAlignment)));
if (mLineHeight != UNSET) {
ops.add(new SetSpanOperation(start, end, new WXLineHeightSpan(mLineHeight)));
}
}
return ops;
}
/**
* Move the reference of current layout to the {@link AtomicReference} for further use,
* then clear current layout.
*/
private void swap() {
if (layout != null) {
atomicReference.set(layout);
layout = null;
mTextPaint = new TextPaint(mTextPaint);
}
}
/**
* As warming up TextLayoutCache done in the DOM thread may manipulate UI operation,
there may be some exception, in which case the exception is ignored. After all,
this is just a warm up operation.
* @return false for warm up failure, otherwise returns true.
*/
private boolean warmUpTextLayoutCache(Layout layout) {
boolean result;
try {
layout.draw(DUMMY_CANVAS);
result = true;
} catch (Exception e) {
WXLogUtils.eTag(TAG, e);
result = false;
}
return result;
}
}
|
package com.mapswithme.maps.downloader;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmRecyclerFragment;
import com.mapswithme.maps.base.OnBackPressListener;
import com.mapswithme.maps.search.NativeMapSearchListener;
import com.mapswithme.maps.search.SearchEngine;
import com.mapswithme.util.UiUtils;
public class DownloaderFragment extends BaseMwmRecyclerFragment
implements OnBackPressListener
{
private DownloaderToolbarController mToolbarController;
private BottomPanel mBottomPanel;
private DownloaderAdapter mAdapter;
private long mCurrentSearch;
private boolean mSearchRunning;
private int mSubscriberSlot;
private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
if (newState == RecyclerView.SCROLL_STATE_DRAGGING)
mToolbarController.deactivate();
}
};
private final NativeMapSearchListener mSearchListener = new NativeMapSearchListener()
{
private final List<CountryItem> mResults = new ArrayList<>();
@Override
public void onMapSearchResults(Result[] results, long timestamp, boolean isLast)
{
if (!mSearchRunning || timestamp != mCurrentSearch)
return;
for (Result result : results)
{
CountryItem item = CountryItem.fill(result.countryId);
item.searchResultName = result.matchedString;
mResults.add(item);
}
if (isLast)
{
mAdapter.setSearchResultsMode(mResults, mToolbarController.getQuery());
mResults.clear();
onSearchEnd();
}
}
};
boolean shouldShowSearch()
{
return CountryItem.isRoot(getCurrentRoot());
}
void startSearch()
{
mSearchRunning = true;
mCurrentSearch = System.nanoTime();
SearchEngine.searchMaps(mToolbarController.getQuery(), mCurrentSearch);
mToolbarController.showProgress(true);
}
void clearSearchQuery()
{
mToolbarController.clear();
}
void cancelSearch()
{
if (!mAdapter.isSearchResultsMode())
return;
mAdapter.cancelSearch();
onSearchEnd();
}
private void onSearchEnd()
{
mSearchRunning = false;
mToolbarController.showProgress(false);
update();
}
void update()
{
mToolbarController.update();
mBottomPanel.update();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
mSubscriberSlot = MapManager.nativeSubscribe(new MapManager.StorageCallback()
{
@Override
public void onStatusChanged(List<MapManager.StorageCallbackData> data)
{
if (isAdded())
update();
}
@Override
public void onProgress(String countryId, long localSize, long remoteSize) {}
});
SearchEngine.INSTANCE.addMapListener(mSearchListener);
getRecyclerView().addOnScrollListener(mScrollListener);
mAdapter.refreshData();
mAdapter.attach();
mBottomPanel = new BottomPanel(this, view);
mToolbarController = new DownloaderToolbarController(view, getActivity(), this);
update();
}
@Override
public void onDestroyView()
{
super.onDestroyView();
mAdapter.detach();
mAdapter = null;
if (mSubscriberSlot != 0)
{
MapManager.nativeUnsubscribe(mSubscriberSlot);
mSubscriberSlot = 0;
}
SearchEngine.INSTANCE.removeMapListener(mSearchListener);
}
@Override
public void onDestroy()
{
super.onDestroy();
if (getRecyclerView() != null)
getRecyclerView().removeOnScrollListener(mScrollListener);
}
@Override
public boolean onBackPressed()
{
if (mToolbarController.hasQuery())
{
mToolbarController.clear();
return true;
}
return mAdapter.goUpwards();
}
@Override
protected int getLayoutRes()
{
return R.layout.fragment_downloader;
}
@Override
protected RecyclerView.Adapter createAdapter()
{
if (mAdapter == null)
mAdapter = new DownloaderAdapter(this);
return mAdapter;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mToolbarController.onActivityResult(requestCode, resultCode, data);
}
@Override
public DownloaderAdapter getAdapter()
{
return mAdapter;
}
@NonNull String getCurrentRoot()
{
return mAdapter.getCurrentRootId();
}
@Override
protected void setupPlaceholder(View placeholder)
{
if (mAdapter.isSearchResultsMode())
UiUtils.setupPlaceholder(placeholder, R.drawable.img_search_nothing_found_light,
R.string.search_not_found, R.string.search_not_found_query);
else
UiUtils.setupPlaceholder(placeholder, R.drawable.img_search_no_maps,
R.string.downloader_no_downloaded_maps_title, R.string.downloader_no_downloaded_maps_message);
}
}
|
package com.mapswithme.maps.downloader;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmRecyclerFragment;
import com.mapswithme.maps.base.OnBackPressListener;
import com.mapswithme.maps.search.NativeMapSearchListener;
import com.mapswithme.maps.search.SearchEngine;
import com.mapswithme.util.UiUtils;
public class DownloaderFragment extends BaseMwmRecyclerFragment
implements OnBackPressListener
{
private DownloaderToolbarController mToolbarController;
private BottomPanel mBottomPanel;
private DownloaderAdapter mAdapter;
private long mCurrentSearch;
private boolean mSearchRunning;
private int mSubscriberSlot;
private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
if (newState == RecyclerView.SCROLL_STATE_DRAGGING)
mToolbarController.deactivate();
}
};
private final NativeMapSearchListener mSearchListener = new NativeMapSearchListener()
{
private final Map<String, CountryItem> mResults = new LinkedHashMap<>();
@Override
public void onMapSearchResults(Result[] results, long timestamp, boolean isLast)
{
if (!mSearchRunning || timestamp != mCurrentSearch)
return;
for (Result result : results)
{
if (TextUtils.isEmpty(result.countryId) || mResults.containsKey(result.countryId))
continue;
CountryItem item = CountryItem.fill(result.countryId);
item.searchResultName = result.matchedString;
mResults.put(result.countryId, item);
}
if (isLast)
{
mAdapter.setSearchResultsMode(mResults.values(), mToolbarController.getQuery());
mResults.clear();
onSearchEnd();
}
}
};
boolean shouldShowSearch()
{
return CountryItem.isRoot(getCurrentRoot());
}
void startSearch()
{
mSearchRunning = true;
mCurrentSearch = System.nanoTime();
SearchEngine.searchMaps(mToolbarController.getQuery(), mCurrentSearch);
mToolbarController.showProgress(true);
}
void clearSearchQuery()
{
mToolbarController.clear();
}
void cancelSearch()
{
if (!mAdapter.isSearchResultsMode())
return;
mAdapter.cancelSearch();
onSearchEnd();
}
private void onSearchEnd()
{
mSearchRunning = false;
mToolbarController.showProgress(false);
update();
}
void update()
{
mToolbarController.update();
mBottomPanel.update();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
mSubscriberSlot = MapManager.nativeSubscribe(new MapManager.StorageCallback()
{
@Override
public void onStatusChanged(List<MapManager.StorageCallbackData> data)
{
if (isAdded())
update();
}
@Override
public void onProgress(String countryId, long localSize, long remoteSize) {}
});
SearchEngine.INSTANCE.addMapListener(mSearchListener);
getRecyclerView().addOnScrollListener(mScrollListener);
mAdapter.refreshData();
mAdapter.attach();
mBottomPanel = new BottomPanel(this, view);
mToolbarController = new DownloaderToolbarController(view, getActivity(), this);
update();
}
@Override
public void onDestroyView()
{
super.onDestroyView();
mAdapter.detach();
mAdapter = null;
if (mSubscriberSlot != 0)
{
MapManager.nativeUnsubscribe(mSubscriberSlot);
mSubscriberSlot = 0;
}
SearchEngine.INSTANCE.removeMapListener(mSearchListener);
}
@Override
public void onDestroy()
{
super.onDestroy();
if (getRecyclerView() != null)
getRecyclerView().removeOnScrollListener(mScrollListener);
}
@Override
public boolean onBackPressed()
{
if (mToolbarController.hasQuery())
{
mToolbarController.clear();
return true;
}
return mAdapter.goUpwards();
}
@Override
protected int getLayoutRes()
{
return R.layout.fragment_downloader;
}
@Override
protected RecyclerView.Adapter createAdapter()
{
if (mAdapter == null)
mAdapter = new DownloaderAdapter(this);
return mAdapter;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mToolbarController.onActivityResult(requestCode, resultCode, data);
}
@Override
public DownloaderAdapter getAdapter()
{
return mAdapter;
}
@NonNull String getCurrentRoot()
{
return mAdapter.getCurrentRootId();
}
@Override
protected void setupPlaceholder(View placeholder)
{
if (mAdapter.isSearchResultsMode())
UiUtils.setupPlaceholder(placeholder, R.drawable.img_search_nothing_found_light,
R.string.search_not_found, R.string.search_not_found_query);
else
UiUtils.setupPlaceholder(placeholder, R.drawable.img_search_no_maps,
R.string.downloader_no_downloaded_maps_title, R.string.downloader_no_downloaded_maps_message);
}
}
|
package me.fraserxu.rncouchbaselite;
import android.net.Uri;
import android.os.AsyncTask;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Manager;
import com.couchbase.lite.View;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.javascript.JavaScriptReplicationFilterCompiler;
import com.couchbase.lite.javascript.JavaScriptViewCompiler;
import com.couchbase.lite.listener.Credentials;
import com.couchbase.lite.listener.LiteListener;
import com.couchbase.lite.replicator.Replication;
import com.couchbase.lite.util.Log;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static me.fraserxu.rncouchbaselite.ReactNativeJson.convertJsonToMap;
public class ReactCBLite extends ReactContextBaseJavaModule {
static {
setLogLevel(Log.WARN);
}
public static final String REACT_CLASS = "ReactCBLite";
private static final String TAG = "ReactCBLite";
private static final int SUGGESTED_PORT = 5984;
private ReactApplicationContext context;
private Manager manager;
private Credentials allowedCredentials;
private LiteListener listener;
public ReactCBLite(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext;
}
@Override
public String getName() {
return REACT_CLASS;
}
@ReactMethod
public void init(Callback callback) {
Credentials allowedCredentials = new Credentials();
this.initWithCredentials(allowedCredentials, callback);
}
@ReactMethod
public static void logLevel(String name) {
switch (name) {
case "VERBOSE": {
setLogLevel(Log.VERBOSE);
break;
}
case "DEBUG": {
setLogLevel(Log.DEBUG);
break;
}
case "INFO": {
setLogLevel(Log.INFO);
break;
}
case "WARN": {
setLogLevel(Log.WARN);
break;
}
case "ERROR": {
setLogLevel(Log.ERROR);
break;
}
case "ASSERT":
setLogLevel(Log.ASSERT);
}
}
@ReactMethod
public void initWithAuth(String username, String password, Callback callback) {
Credentials credentials;
if (username == null && password == null) {
credentials = null;
Log.w(TAG, "No credential specified, your listener is unsecured and you are putting your data at risk");
} else if (username == null || password == null) {
callback.invoke(null, "username and password must not be null");
return;
} else {
credentials = new Credentials(username, password);
}
this.initWithCredentials(credentials, callback);
}
private void initWithCredentials(Credentials credentials, Callback callback) {
this.allowedCredentials = credentials;
try {
View.setCompiler(new JavaScriptViewCompiler());
Database.setFilterCompiler(new JavaScriptReplicationFilterCompiler());
AndroidContext context = new AndroidContext(this.context);
manager = new Manager(context, Manager.DEFAULT_OPTIONS);
this.startListener();
String url;
if (credentials != null) {
url = String.format(
"http://%s:%s@localhost:%d/",
credentials.getLogin(),
credentials.getPassword(),
listener.getListenPort()
);
} else {
url = String.format(
"http://localhost:%d/",
listener.getListenPort()
);
}
callback.invoke(url, null);
} catch (final Exception e) {
Log.e(TAG, "Couchbase init failed", e);
callback.invoke(null, e.getMessage());
}
}
private static void setLogLevel(int level) {
Log.i(TAG, "Setting log level to '" + level + "'");
Manager.enableLogging(Log.TAG, level);
Manager.enableLogging(Log.TAG_SYNC, level);
Manager.enableLogging(Log.TAG_QUERY, level);
Manager.enableLogging(Log.TAG_VIEW, level);
Manager.enableLogging(Log.TAG_CHANGE_TRACKER, level);
Manager.enableLogging(Log.TAG_BLOB_STORE, level);
Manager.enableLogging(Log.TAG_DATABASE, level);
Manager.enableLogging(Log.TAG_LISTENER, level);
Manager.enableLogging(Log.TAG_MULTI_STREAM_WRITER, level);
Manager.enableLogging(Log.TAG_REMOTE_REQUEST, level);
Manager.enableLogging(Log.TAG_ROUTER, level);
}
@ReactMethod
public void stopListener() {
Log.i(TAG, "Stopping CBL listener on port " + listener.getListenPort());
listener.stop();
}
@ReactMethod
public void startListener() {
if (listener == null) {
listener = new LiteListener(manager, SUGGESTED_PORT, allowedCredentials);
Log.i(TAG, "Starting CBL listener on port " + listener.getListenPort());
} else {
Log.i(TAG, "Restarting CBL listener on port " + listener.getListenPort());
}
listener.start();
}
@ReactMethod
public void upload(String method, String authHeader, String sourceUri, String targetUri, String contentType, Callback callback) {
if (method == null || !method.toUpperCase().equals("PUT")) {
callback.invoke("Bad parameter method: " + method);
return;
}
if (authHeader == null) {
callback.invoke("Bad parameter authHeader");
return;
}
if (sourceUri == null) {
callback.invoke("Bad parameter sourceUri");
return;
}
if (targetUri == null) {
callback.invoke("Bad parameter targetUri");
return;
}
if (contentType == null) {
callback.invoke("Bad parameter contentType");
return;
}
if (callback == null) {
Log.e(TAG, "no callback");
return;
}
SaveAttachmentTask saveAttachmentTask = new SaveAttachmentTask(method, authHeader, sourceUri, targetUri, contentType, callback);
saveAttachmentTask.execute();
}
private class SaveAttachmentTask extends AsyncTask<URL, Integer, UploadResult> {
private final String method;
private final String authHeader;
private final String sourceUri;
private final String targetUri;
private final String contentType;
private final Callback callback;
private SaveAttachmentTask(String method, String authHeader, String sourceUri, String targetUri, String contentType, Callback callback) {
this.method = method;
this.authHeader = authHeader;
this.sourceUri = sourceUri;
this.targetUri = targetUri;
this.contentType = contentType;
this.callback = callback;
}
@Override
protected UploadResult doInBackground(URL... params) {
try {
Log.i(TAG, "Uploading attachment '" + sourceUri + "' to '" + targetUri + "'");
InputStream input;
if (sourceUri.startsWith("/")) {
input = new FileInputStream(new File(sourceUri));
} else if (sourceUri.startsWith("content:
input = ReactCBLite.this.context.getContentResolver().openInputStream(Uri.parse(sourceUri));
} else {
URLConnection urlConnection = new URL(sourceUri).openConnection();
input = urlConnection.getInputStream();
}
try {
HttpURLConnection conn = (HttpURLConnection) new URL(targetUri).openConnection();
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", authHeader);
conn.setReadTimeout(100000);
conn.setConnectTimeout(100000);
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
publishProgress(bytesRead);
}
} finally {
os.close();
}
int responseCode = conn.getResponseCode();
StringBuilder responseText = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
try {
String line;
while ((line = br.readLine()) != null) {
responseText.append(line);
}
} finally {
br.close();
}
return new UploadResult(responseCode, responseText.toString());
} finally {
input.close();
}
} catch (Exception e) {
Log.e(TAG, "Failed to save attachment", e);
return new UploadResult(-1, "Failed to save attachment " + e.getMessage());
}
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.d(TAG, "Uploaded", Arrays.toString(values));
}
@Override
protected void onPostExecute(UploadResult uploadResult) {
int responseCode = uploadResult.statusCode;
WritableMap map = Arguments.createMap();
map.putInt("statusCode", responseCode);
if (responseCode == 200 || responseCode == 202) {
try {
JSONObject jsonObject = new JSONObject(uploadResult.response);
map.putMap("resp", convertJsonToMap(jsonObject));
callback.invoke(null, map);
} catch (JSONException e) {
map.putString("error", uploadResult.response);
callback.invoke(map, null);
Log.e(TAG, "Failed to parse response from clb: " + uploadResult.response, e);
}
} else {
map.putString("error", uploadResult.response);
callback.invoke(map, null);
}
}
}
private static class UploadResult {
public final int statusCode;
public final String response;
public UploadResult(int statusCode, String response) {
this.statusCode = statusCode;
this.response = response;
}
}
}
|
package wang.relish.colorpicker.sample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import wang.relish.colorpicker.ColorPickerDialog;
/**
* @author Relish Wang
* @since 2017/7/31
*/
public class MainActivity extends AppCompatActivity {
private View mViewColor;
private int mColor = 0xFFFFFF;
private boolean mHexValueEnable = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SwitchCompat mStHexEnable = (SwitchCompat) findViewById(R.id.st_hex_enable);
mStHexEnable.setChecked(mHexValueEnable);
mStHexEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
mHexValueEnable = b;
}
});
mViewColor = findViewById(R.id.view_color);
mViewColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ColorPickerDialog.Builder(MainActivity.this, mColor)
.setHexValueEnabled(mHexValueEnable)
.setOnColorPickedListener(new ColorPickerDialog.OnColorPickedListener() {
@Override
public void onColorPicked(int color) {
mColor = color;
mViewColor.setBackgroundColor(mColor);
}
})
.build()
.show();
}
});
}
}
|
package me.lucko.luckperms.bukkit;
import me.lucko.luckperms.bukkit.inject.Injector;
import me.lucko.luckperms.bukkit.model.LPPermissible;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.utils.AbstractListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginEnableEvent;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
class BukkitListener extends AbstractListener implements Listener {
private final LPBukkitPlugin plugin;
private final Set<UUID> deniedAsyncLogin = Collections.synchronizedSet(new HashSet<>());
private final Set<UUID> deniedLogin = new HashSet<>();
BukkitListener(LPBukkitPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent e) {
if (e.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
deniedAsyncLogin.add(e.getUniqueId());
return;
}
if (!plugin.isStarted() || !plugin.getStorage().isAcceptingLogins()) {
deniedAsyncLogin.add(e.getUniqueId());
// The datastore is disabled, prevent players from joining the server
e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, Message.LOADING_ERROR.toString());
return;
}
// Process login
onAsyncLogin(e.getUniqueId(), e.getName());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerPreLoginMonitor(AsyncPlayerPreLoginEvent e) {
// If they were denied before/at LOW, then don't bother handling here.
if (deniedAsyncLogin.remove(e.getUniqueId())) {
return;
}
if (plugin.isStarted() && plugin.getStorage().isAcceptingLogins() && e.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
// Login event was cancelled by another plugin
onLeave(e.getUniqueId());
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLogin(PlayerLoginEvent e) {
if (e.getResult() != PlayerLoginEvent.Result.ALLOWED) {
deniedLogin.add(e.getPlayer().getUniqueId());
return;
}
final Player player = e.getPlayer();
final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(player.getUniqueId()));
if (user == null) {
deniedLogin.add(e.getPlayer().getUniqueId());
// User wasn't loaded for whatever reason.
e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Message.LOADING_ERROR.toString());
return;
}
try {
// Make a new permissible for the user
LPPermissible lpPermissible = new LPPermissible(player, user, plugin);
// Inject into the player
Injector.inject(player, lpPermissible);
} catch (Throwable t) {
t.printStackTrace();
}
plugin.refreshAutoOp(player);
if (player.isOp()) {
// We assume all users are not op, but those who are need extra calculation.
plugin.doAsync(() -> user.getUserData().preCalculate(plugin.getPreProcessContexts(true)));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLoginMonitor(PlayerLoginEvent e) {
if (e.getResult() != PlayerLoginEvent.Result.ALLOWED) {
// If they were denied before/at LOW, then don't bother handling here.
if (deniedLogin.remove(e.getPlayer().getUniqueId())) {
return;
}
// The player got denied on sync login.
plugin.getServer().getScheduler().runTaskLater(plugin, () -> onLeave(e.getPlayer().getUniqueId()), 20L);
} else {
plugin.refreshAutoOp(e.getPlayer());
}
}
@EventHandler(priority = EventPriority.MONITOR) // Allow other plugins to see data when this event gets called.
public void onPlayerQuit(PlayerQuitEvent e) {
final Player player = e.getPlayer();
// Remove the custom permissible
Injector.unInject(player, true, true);
// Handle auto op
if (plugin.getConfiguration().get(ConfigKeys.AUTO_OP)) {
player.setOp(false);
}
// Call internal leave handling
onLeave(player.getUniqueId());
}
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
if (plugin.getConfiguration().get(ConfigKeys.OPS_ENABLED)) {
return;
}
String s = e.getMessage()
.replace("/", "")
.replace("bukkit:", "")
.replace("spigot:", "")
.replace("minecraft:", "");
if (s.equals("op") || s.startsWith("op ") || s.equals("deop") || s.startsWith("deop ")) {
e.setCancelled(true);
e.getPlayer().sendMessage(Message.OP_DISABLED.toString());
}
}
@EventHandler
public void onPluginEnable(PluginEnableEvent e) {
if (e.getPlugin().getName().equalsIgnoreCase("Vault")) {
plugin.tryVaultHook(true);
}
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent e) {
plugin.refreshAutoOp(e.getPlayer());
}
}
|
package ru.ematveev.arraysquare;
public class ArraySquare{
public int [][] arraySquare(int [][] array){
int [][] arr2 = new int[array.length][array.length];
for (int i = 0; i < array.length;){
for (int j = 0; j < array.length; j++){
arr2[j][array.length - (i+1)] = array[i][j];
}
i++;
}
array = arr2;
arr2 = null;
return array;
}
}
|
package cane.brothers.circus.domain;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "CIRCUS_LAYOUTS")
public class CircusLayout extends BaseEntity {
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "CIRCUS_ID", unique = true, nullable = false)
private Circus circus;
/**
* Circus layout name
*/
@Column(name = "NAME", nullable = false, unique = true)
private String name;
/**
* Circus arena capacity
*/
private int capacity;
/**
* Constructor
*/
public CircusLayout() {
super();
}
public CircusLayout(Circus circus, String name, int capacity) {
super();
this.circus = circus;
this.name = name;
this.capacity = capacity;
}
public Circus getCircus() {
return circus;
}
public void setCircus(Circus circus) {
this.circus = circus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
|
package com.netflix.metacat.connector.hive.iceberg;
import org.apache.iceberg.TableMetadata;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
/**
* Proxy class to get the metadata from cache if exists.
*/
@CacheConfig(cacheNames = "metacat")
public class IcebergTableOpsProxy {
/**
* Return the table metadata from cache if exists. If not exists, make the iceberg call to refresh it.
* @param icebergTableOps iceberg table operations
* @param useCache true, if table can be retrieved from cache
* @return TableMetadata
*/
@Cacheable(key = "'iceberg.' + #icebergTableOps.currentMetadataLocation()", condition = "#useCache")
public TableMetadata getMetadata(final IcebergTableOps icebergTableOps, final boolean useCache) {
return icebergTableOps.refresh();
}
}
|
package org.terasology.codecity.world.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.terasology.codecity.world.facet.CodeCityFacet;
import org.terasology.codecity.world.map.CodeMap;
import org.terasology.codecity.world.map.CodeMapFactory;
import org.terasology.codecity.world.map.DrawableCode;
import org.terasology.codecity.world.map.MapObject;
import org.terasology.codecity.world.structure.CodeClass;
import org.terasology.codecity.world.structure.CodePackage;
import org.terasology.codecity.world.structure.scale.CodeScale;
import org.terasology.codecity.world.structure.scale.SquareRootCodeScale;
import org.terasology.math.ChunkMath;
import org.terasology.math.Rect2i;
import org.terasology.math.Region3i;
import org.terasology.math.Vector2i;
import org.terasology.world.generation.Border3D;
import org.terasology.world.generation.Facet;
import org.terasology.world.generation.FacetProvider;
import org.terasology.world.generation.GeneratingRegion;
import org.terasology.world.generation.Produces;
import org.terasology.world.generation.Requires;
import org.terasology.world.generation.Updates;
import org.terasology.world.generation.facets.SurfaceHeightFacet;
import com.sun.jna.platform.unix.X11.Drawable;
/**
* Creates a new surface for buildings using an squared scale and a CodeMap.
* This surface is created just above the ground.
* @author alstrat
*
*/
@Produces(CodeCityFacet.class)
@Requires(@Facet(SurfaceHeightFacet.class))
public class CodeCityBuildingProvider implements FacetProvider {
private CodeMap codeMap;
private final CodeScale scale = new SquareRootCodeScale();
private final CodeMapFactory factory = new CodeMapFactory(scale);
public CodeCityBuildingProvider() {
CodePackage facet = new CodePackage();
CodePackage generator = new CodePackage();
CodePackage map = new CodePackage();
CodePackage structure = new CodePackage();
CodePackage scale = new CodePackage();
CodePackage terasology = new CodePackage();
CodeClass fac = new CodeClass(1, 18);
facet.addCodeContent(fac);
CodeClass bProv = new CodeClass(3, 122);
CodeClass bRast = new CodeClass(1, 54);
CodeClass gProv = new CodeClass(0, 37);
CodeClass gRast = new CodeClass(1, 34);
CodeClass wGen = new CodeClass(0, 24);
generator.addCodeContent(bProv);
generator.addCodeContent(bRast);
generator.addCodeContent(gProv);
generator.addCodeContent(gRast);
generator.addCodeContent(wGen);
terasology.addCodeContent(generator);
CodeClass cMap = new CodeClass(0, 83);
CodeClass cMapF = new CodeClass(1,101);
CodeClass cMapH = new CodeClass(3,147);
CodeClass cMapN = new CodeClass(0,57);
CodeClass cMapC = new CodeClass(0,36);
CodeClass cMapCC = new CodeClass(1,34);
CodeClass cMapCP = new CodeClass(1,43);
CodeClass cMapO = new CodeClass(4,67);
map.addCodeContent(cMap);
map.addCodeContent(cMapF);
map.addCodeContent(cMapH);
map.addCodeContent(cMapN);
map.addCodeContent(cMapC);
map.addCodeContent(cMapCC);
map.addCodeContent(cMapCP);
map.addCodeContent(cMapO);
terasology.addCodeContent(map);
CodeClass cClas = new CodeClass(2, 45);
CodeClass cPac = new CodeClass(1,34);
CodeClass cRep = new CodeClass(0,17);
structure.addCodeContent(cClas);
structure.addCodeContent(cPac);
structure.addCodeContent(cRep);
terasology.addCodeContent(structure);
CodeClass cSca = new CodeClass(0,28);
CodeClass cLin = new CodeClass(0,16);
CodeClass cSqu = new CodeClass(0,21);
scale.addCodeContent(cSca);
scale.addCodeContent(cLin);
scale.addCodeContent(cSqu);
structure.addCodeContent(scale);
List<DrawableCode> code = new ArrayList<DrawableCode>();
code.add(terasology.getDrawableCode());
codeMap = factory.generateMap(code);
}
@Override
public void setSeed(long seed) {
}
@Override
public void process(GeneratingRegion region) {
Border3D border = region.getBorderForFacet(CodeCityFacet.class);
int base = (int) region.getRegionFacet(SurfaceHeightFacet.class).get(0, 0);
CodeCityFacet facet = new CodeCityFacet(region.getRegion(), border, base);
Rect2i processRegion = facet.getWorldRegion();
processMap(facet, processRegion, codeMap, Vector2i.zero(), base);
// give our newly created and populated facet to the region
region.setRegionFacet(CodeCityFacet.class, facet);
}
/**
* Update the height of the indicated position given a CodeMap.
* @param facet Surface where the height should be updated.
* @param region Region where the facet must be updated
* @param map Map with the height information.
* @param offset Offset of the current coordinates
* @param level Current height
*/
private void processMap(CodeCityFacet facet, Rect2i region, CodeMap map, Vector2i offset, int level) {
for (MapObject obj : map.getMapObjects()) {
int x = obj.getPositionX() + offset.getX();
int y = obj.getPositionZ() + offset.getY();
int z = obj.getHeight(scale, factory) + level;
if (region.contains(x, y) && facet.getWorld(x, y) < z)
facet.setWorld(x, y, z);
if (obj.isOrigin())
processMap(facet, region, obj.getObject().getSubmap(scale, factory), new Vector2i(x+1, y+1), z);
}
}
}
|
package it.unibz.krdb.obda.reformulation.tests;
import it.unibz.krdb.obda.io.DataManager;
import it.unibz.krdb.obda.io.QueryStorageManager;
import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.OBDAModel;
import it.unibz.krdb.obda.model.OBDAResultSet;
import it.unibz.krdb.obda.model.OBDAStatement;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants;
import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWL;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLFactory;
import it.unibz.krdb.obda.querymanager.QueryController;
import it.unibz.krdb.obda.querymanager.QueryControllerGroup;
import it.unibz.krdb.obda.querymanager.QueryControllerQuery;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.SimpleConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* As the H2 in-memory StockExchange test but uses an Postgres database.
* Moreover, it requires the data to be already loaded in the database.
*
* The test requires a postgres database, the JDBC access properties and an
* account that is able to create and drop tables on the database.
*
* @author mariano
*
*/
public class StockExchangeTestPostgres extends TestCase {
// TODO We need to extend this test to import the contents of the mappings
// into OWL and repeat everything taking form OWL
private OBDADataFactory fac;
private Connection conn;
Logger log = LoggerFactory.getLogger(this.getClass());
private OBDAModel obdaModel;
private OWLOntology ontology;
List<TestQuery> testQueries = new LinkedList<TestQuery>();
private String driver;
private String url;
private String username;
private String password;
final String owlfile = "src/test/resources/test/stockexchange-unittest.owl";
final String obdafile = "src/test/resources/test/stockexchange-postgres-unittest.obda";
public class TestQuery {
public String id = "";
public String query = "";
public int distinctTuples = -1;
}
public class Result {
public String id = "";
public String query = "";
public int distinctTuples = -1;
public long timeelapsed = -1;
}
@Override
public void setUp() throws Exception {
/*
* Initializing and H2 database with the stock exchange data
*/
driver = "org.postgresql.Driver";
url = "jdbc:postgresql://obdalin.inf.unibz.it/quest-junit-db";
username = "obda";
password = "obda09";
log.debug("Driver: {}", driver);
log.debug("Url: {}", url);
log.debug("Username: {}", username);
log.debug("Password: {}", password);
fac = OBDADataFactoryImpl.getInstance();
conn = DriverManager.getConnection(url, username, password);
Statement st = conn.createStatement();
FileReader reader = new FileReader("src/test/resources/test/stockexchange-create-postgres.sql");
BufferedReader in = new BufferedReader(reader);
StringBuilder bf = new StringBuilder();
String line = in.readLine();
while (line != null) {
bf.append(line);
line = in.readLine();
}
st.executeUpdate(bf.toString());
conn.commit();
// Loading the OWL file
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
ontology = manager.loadOntologyFromOntologyDocument((new File(owlfile)));
// Loading the OBDA data
obdaModel = fac.getOBDAModel();
DataManager ioManager = new DataManager(obdaModel);
ioManager.loadOBDADataFromURI(new File(obdafile).toURI(), ontology.getOntologyID().getOntologyIRI().toURI(),
obdaModel.getPrefixManager());
}
@Override
public void tearDown() throws Exception {
try {
dropTables();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
conn.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
}
private void prepareTestQueries(int[] answer) {
/*
* Loading the queries (we have 61 queries)
*/
QueryController qcontroller = new QueryController();
QueryStorageManager qman = new QueryStorageManager(qcontroller);
qman.loadQueries(new File(obdafile).toURI());
int counter = 0;
for (QueryControllerGroup group : qcontroller.getGroups()) {
for (QueryControllerQuery query : group.getQueries()) {
TestQuery tq = new TestQuery();
tq.id = query.getID();
tq.query = query.getQuery();
tq.distinctTuples = answer[counter];
testQueries.add(tq);
counter += 1;
}
}
}
private void dropTables() throws SQLException, IOException {
Statement st = conn.createStatement();
FileReader reader = new FileReader("src/test/resources/test/stockexchange-drop-postgres.sql");
BufferedReader in = new BufferedReader(reader);
StringBuilder bf = new StringBuilder();
String line = in.readLine();
while (line != null) {
bf.append(line);
line = in.readLine();
}
st.executeUpdate(bf.toString());
st.close();
conn.commit();
}
private void runTests(QuestPreferences p) throws Exception {
// Creating a new instance of the reasoner
QuestOWLFactory factory = new QuestOWLFactory();
factory.setOBDAController(obdaModel);
factory.setPreferenceHolder(p);
QuestOWL reasoner = (QuestOWL) factory.createReasoner(ontology, new SimpleConfiguration());
reasoner.loadOBDAModel(obdaModel);
// Now we are ready for querying
OBDAStatement st = reasoner.getStatement();
List<Result> summaries = new LinkedList<StockExchangeTestPostgres.Result>();
int qc = 0;
for (TestQuery tq : testQueries) {
log.debug("Executing query: {}", qc);
log.debug("Query: {}", tq.query);
qc += 1;
int count = 0;
long start = System.currentTimeMillis();
long end = 0;
try {
OBDAResultSet rs = st.execute(tq.query);
end = System.currentTimeMillis();
while (rs.nextRow()) {
count += 1;
}
} catch (Exception e) {
end = System.currentTimeMillis();
count = -1;
}
Result summary = new Result();
summary.id = tq.id;
summary.query = tq.query;
summary.timeelapsed = end - start;
summary.distinctTuples = count;
summaries.add(summary);
}
/* Closing resources */
st.close();
reasoner.dispose();
boolean fail = false;
/* Comparing and printing results */
int totaltime = 0;
for (int i = 0; i < testQueries.size(); i++) {
TestQuery tq = testQueries.get(i);
Result summary = summaries.get(i);
totaltime += summary.timeelapsed;
fail = fail | tq.distinctTuples != summary.distinctTuples;
String out = "Query: %3d Tup. Ex.: %6d Tup. ret.: %6d Time elapsed: %6.3f s ";
log.debug(String.format(out, i, tq.distinctTuples, summary.distinctTuples, (double) summary.timeelapsed / (double) 1000)
+ " " + (tq.distinctTuples == summary.distinctTuples ? " " : "ERROR"));
}
log.debug("==========================");
log.debug(String.format("Total time elapsed: %6.3f s", (double) totaltime / (double) 1000));
assertFalse(fail);
}
public void testSiEqSig() throws Exception {
/* These are the distinct tuples that we know each query returns */
final int[] tuples = {
7, 1, 4, 1, // Simple queries group
1, 2, 2, 1, 4, 3, 3, // CQs group
2, -1, 2, // String
2, 2, 2, -1, 2, 2, 0, 0, 0, // Integer
2, 2, 2, 2, 2, 2, 0, 0, 0, // Decimal
2, 2, 2, 2, 2, 2, 0, 0, 0, // Double
1, 1, 0, -1, -1, -1, -1, -1, 0, // Date time
5, 5, 5, 5, 5, 5, -1, 5, 5, -1, -1, 5 // Boolean
};
prepareTestQueries(tuples);
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC);
runTests(p);
}
public void disabledtestSiEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC);
runTests(p);
}
public void disabledtestSiNoEqSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC);
runTests(p);
}
public void disabledtestSiNoEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC);
runTests(p);
}
/*
* Direct
*/
public void disabletestDiEqSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.DIRECT);
runTests(p);
}
public void disabledtestDiEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.DIRECT);
runTests(p);
}
/***
* This is a very slow test, disable it if you are doing rutine checks.
*
* @throws Exception
*/
public void disabledtestDiNoEqSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.DIRECT);
runTests(p);
}
/***
* This is a very slow test, disable it if you are doing rutine checks.
*
* @throws Exception
*/
public void disabledtestDiNoEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.CLASSIC);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_MAPPINGS, "true");
p.setCurrentValueOf(QuestPreferences.OBTAIN_FROM_ONTOLOGY, "false");
p.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.DIRECT);
runTests(p);
}
public void testViEqSig() throws Exception {
/* These are the distinct tuples that we know each query returns
*
* Note:
* - Pgsql can handle query: [...] WHERE number="+3"
* - Pgsql can handle query: [...] WHERE date="2008-04-02T00:00:00Z"
* - Pgsql can't handle query: [...] WHERE shareType=1 (the DBMS stores boolean as 't' or 'f')
* */
final int[] tuples = {
7, 1, 4, 1, // Simple queries group
1, 2, 2, 1, 4, 3, 3, // CQs group
2, -1, 2, // String
2, 2, 2, 2, 2, 2, 0, 0, 0, // Integer
2, 2, 2, 2, 2, 2, 0, 0, 0, // Decimal
2, 2, 2, 2, 2, 2, 0, 0, 0, // Double
1, 1, 1, -1, -1, -1, -1, -1, 1, // Date time
5, 5, 5, 5, 5, 5, -1, -1, 5, -1, -1, 5 // Boolean
};
prepareTestQueries(tuples);
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
runTests(p);
}
public void disabledtestViEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "true");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
runTests(p);
}
/***
* This is a very slow test, disable it if you are doing rutine checks.
*
* @throws Exception
*/
public void disabledtestViNoEqSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "true");
runTests(p);
}
/***
* This is a very slow test, disable it if you are doing rutine checks.
*
* @throws Exception
*/
public void disabledtestViNoEqNoSig() throws Exception {
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL);
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_EQUIVALENCES, "false");
p.setCurrentValueOf(QuestPreferences.OPTIMIZE_TBOX_SIGMA, "false");
runTests(p);
}
}
|
package org.gbif.occurrence.ws.client.mock;
import org.gbif.api.model.common.paging.Pageable;
import org.gbif.api.model.common.paging.PagingResponse;
import org.gbif.api.model.occurrence.Download;
import org.gbif.api.model.registry.DatasetOccurrenceDownloadUsage;
import org.gbif.api.service.registry.OccurrenceDownloadService;
import org.gbif.api.vocabulary.Country;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
public class OccurrenceDownloadMockServices implements OccurrenceDownloadService {
@Override
public void create(@NotNull Download download) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public Download get(@NotNull String s) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public PagingResponse<Download> list(
@Nullable Pageable pageable, @Nullable Set<Download.Status> status
) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public PagingResponse<Download> listByUser(
@NotNull String s, @Nullable Pageable pageable, @Nullable Set<Download.Status> status
) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public void update(@NotNull Download download) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public PagingResponse<DatasetOccurrenceDownloadUsage> listDatasetUsages(
@NotNull String s, @Nullable Pageable pageable
) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public Map<Integer, Map<Integer, Long>> getMonthlyStats(
@Nullable Date date, @Nullable Date date1, @Nullable Country country, @Nullable Country country1, @Nullable UUID uuid
) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public Map<Integer, Map<Integer, Long>> getDownloadedRecordsStats(
@Nullable Date date, @Nullable Date date1, @Nullable Country country, @Nullable Country country1, @Nullable UUID uuid
) {
// TODO: Write implementation
throw new UnsupportedOperationException("Not implemented yet");
}
}
|
package pl.openrest.filters.repository;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.support.CrudMethodMetadata;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.QueryDslJpaRepository;
import org.springframework.data.jpa.repository.support.Querydsl;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import pl.openrest.filters.query.PredicateContext;
import pl.openrest.filters.query.registry.JoinInformation;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.AbstractJPAQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.Predicate;
import com.mysema.query.types.path.CollectionPath;
import com.mysema.query.types.path.PathBuilder;
import com.mysema.query.types.path.PathBuilderFactory;
public class PredicateContextQueryDslRepositoryImpl<T, ID extends Serializable> extends QueryDslJpaRepository<T, ID> implements
PredicateContextQueryDslRepository<T> {
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
private final EntityPath<T> path;
private final PathBuilder<T> builder;
private final Querydsl querydsl;
// private final EntityManager em;
private final PathBuilderFactory pathBuilderFactory = new PathBuilderFactory();
public PredicateContextQueryDslRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
}
public PredicateContextQueryDslRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager,
EntityPathResolver resolver) {
super(entityInformation, entityManager, resolver);
this.path = resolver.createPath(entityInformation.getJavaType());
this.builder = new PathBuilder<T>(path.getType(), path.getMetadata());
this.querydsl = new Querydsl(entityManager, builder);
}
@Override
protected JPQLQuery createQuery(Predicate... predicate) {
return super.createQuery(predicate);
}
@Override
public T findOne(PredicateContext predicateContext) {
return createQuery(predicateContext).uniqueResult(path);
}
@Override
public Iterable<T> findAll(PredicateContext predicateContext) {
return createQuery(predicateContext).list(path);
}
@Override
public Iterable<T> findAll(PredicateContext predicateContext, Sort sort) {
JPQLQuery query = createQuery(predicateContext);
query = querydsl.applySorting(sort, query);
return query.list(path);
}
@Override
public Page<T> findAll(PredicateContext predicateContext, Pageable pageable) {
JPQLQuery countQuery = createQuery(predicateContext);
JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicateContext));
Long total = countQuery.count();
List<T> content = total > pageable.getOffset() ? query.list(path) : Collections.<T> emptyList();
return new PageImpl<T>(content, pageable, total);
}
@Override
public long count(PredicateContext predicateContext) {
return createQuery(predicateContext).count();
}
protected AbstractJPAQuery<JPAQuery> addJoins(AbstractJPAQuery<JPAQuery> query, PredicateContext context) {
for (JoinInformation join : context.getJoins()) {
if (join.isCollection())
query = query.leftJoin((CollectionPath) join.getPath(), pathBuilderFactory.create(join.getType()));
else
query = query.leftJoin((EntityPath) join.getPath());
if (join.isFetch())
query = query.fetch();
}
return query;
}
protected JPQLQuery createQuery(PredicateContext context) {
AbstractJPAQuery<JPAQuery> query = querydsl.createQuery(path);
query = addJoins(query, context);
query.where(context.getPredicate());
CrudMethodMetadata metadata = getRepositoryMethodMetadata();
if (metadata == null) {
return query;
}
LockModeType type = metadata.getLockModeType();
query = type == null ? query : query.setLockMode(type);
for (Entry<String, Object> hint : getQueryHints().entrySet()) {
query.setHint(hint.getKey(), hint.getValue());
}
return query;
}
}
|
package org.eclipse.emf.emfstore.client.model.controller;
import java.util.Date;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.emfstore.client.common.UnknownEMFStoreWorkloadCommand;
import org.eclipse.emf.emfstore.client.model.Configuration;
import org.eclipse.emf.emfstore.client.model.Usersession;
import org.eclipse.emf.emfstore.client.model.WorkspaceManager;
import org.eclipse.emf.emfstore.client.model.connectionmanager.ServerCall;
import org.eclipse.emf.emfstore.client.model.impl.ProjectSpaceBase;
import org.eclipse.emf.emfstore.client.model.observers.LoginObserver;
import org.eclipse.emf.emfstore.client.model.observers.ShareObserver;
import org.eclipse.emf.emfstore.server.exceptions.EmfStoreException;
import org.eclipse.emf.emfstore.server.model.ProjectInfo;
import org.eclipse.emf.emfstore.server.model.versioning.LogMessage;
import org.eclipse.emf.emfstore.server.model.versioning.VersioningFactory;
/**
* Shares a project.
*
* @author ovonwesen
* @author emueller
*/
public class ShareController extends ServerCall<Void> {
/**
* Constructor.
*
* @param projectSpace
* the project space to be shared
* @param session
* the session to use during share
* @param monitor
* a progress monitor that is used to indicate the progress of the share
*/
public ShareController(ProjectSpaceBase projectSpace, Usersession session, IProgressMonitor monitor) {
super(projectSpace);
// if session is null, session will be injected by sessionmanager
setUsersession(session);
setProgressMonitor(monitor);
}
@Override
protected Void run() throws EmfStoreException {
doRun();
return null;
}
@SuppressWarnings("unchecked")
private void doRun() throws EmfStoreException {
getProgressMonitor().beginTask("Sharing Project", 100);
getProgressMonitor().worked(1);
getProgressMonitor().subTask("Preparing project for sharing");
final LogMessage logMessage = VersioningFactory.eINSTANCE.createLogMessage();
logMessage.setAuthor(getUsersession().getUsername());
logMessage.setClientDate(new Date());
logMessage.setMessage("Initial commit");
ProjectInfo createdProject = null;
getProjectSpace().stopChangeRecording();
Configuration.setAutoSave(false);
getProgressMonitor().worked(10);
if (getProgressMonitor().isCanceled()) {
Configuration.setAutoSave(true);
getProjectSpace().save();
getProjectSpace().startChangeRecording();
getProgressMonitor().done();
}
getProgressMonitor().subTask("Sharing project with server");
createdProject = new UnknownEMFStoreWorkloadCommand<ProjectInfo>(getProgressMonitor()) {
@Override
public ProjectInfo run(IProgressMonitor monitor) throws EmfStoreException {
return WorkspaceManager
.getInstance()
.getConnectionManager()
.createProject(
getUsersession().getSessionId(),
getProjectSpace().getProjectName() == null ? "Project@" + new Date() : getProjectSpace()
.getProjectName(),
getProjectSpace().getProjectDescription() == null ? "" : getProjectSpace()
.getProjectDescription(), logMessage, getProjectSpace().getProject());
}
}.execute();
getProgressMonitor().worked(30);
getProgressMonitor().subTask("Finalizing share");
// set attributes after server call
getProgressMonitor().subTask("Setting attributes");
this.setUsersession(getUsersession());
WorkspaceManager.getObserverBus().register(getProjectSpace(), LoginObserver.class);
Configuration.setAutoSave(true);
getProjectSpace().save();
getProjectSpace().startChangeRecording();
getProjectSpace().setBaseVersion(createdProject.getVersion());
getProjectSpace().setLastUpdated(new Date());
getProjectSpace().setProjectId(createdProject.getProjectId());
getProjectSpace().setUsersession(getUsersession());
getProjectSpace().saveProjectSpaceOnly();
// TODO ASYNC implement File Upload with observer
// If any files have already been added, upload them.
getProgressMonitor().worked(20);
getProgressMonitor().subTask("Uploading files");
getProjectSpace().getFileTransferManager().uploadQueuedFiles(getProgressMonitor());
getProgressMonitor().worked(20);
getProgressMonitor().subTask("Finalizing share.");
getProjectSpace().getOperations().clear();
getProjectSpace().updateDirtyState();
getProgressMonitor().done();
WorkspaceManager.getObserverBus().notify(ShareObserver.class).shareDone(getProjectSpace());
}
}
|
package org.eclipse.mylyn.internal.team.ui.actions;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylyn.internal.tasks.core.RepositoryTaskHandleUtil;
import org.eclipse.mylyn.internal.tasks.ui.ITasksUiConstants;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.actions.OpenRepositoryTask;
import org.eclipse.mylyn.internal.team.ui.FocusedTeamUiPlugin;
import org.eclipse.mylyn.internal.team.ui.LinkedTaskInfo;
import org.eclipse.mylyn.internal.team.ui.templates.CommitTemplateManager;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.ILinkedTaskInfo;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.TaskRepositoryManager;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.ObjectPluginAction;
/**
* Action used to open linked task
*
* @author Mik Kersten
* @author Eugene Kuleshov
*/
public class OpenCorrespondingTaskAction extends Action implements IViewActionDelegate {
private static final String LABEL = "Open Corresponding Task";
private static final String PREFIX_HTTP = "http:
private static final String PREFIX_HTTPS = "https:
private ISelection selection;
public OpenCorrespondingTaskAction() {
setText(LABEL);
setToolTipText(LABEL);
setImageDescriptor(TasksUiImages.TASK_REPOSITORY);
}
public void init(IViewPart view) {
// ignore
}
@Override
public void run() {
if (selection instanceof StructuredSelection) {
run((StructuredSelection) selection);
}
}
public void run(IAction action) {
if (action instanceof ObjectPluginAction) {
ObjectPluginAction objectAction = (ObjectPluginAction) action;
if (objectAction.getSelection() instanceof StructuredSelection) {
StructuredSelection selection = (StructuredSelection) objectAction.getSelection();
run(selection);
}
}
}
private void run(StructuredSelection selection) {
final Object element = selection.getFirstElement();
Job job = new OpenCorrespondingTaskJob("Opening Corresponding Task", element);
job.schedule();
}
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
/**
* Reconcile <code>ILinkedTaskInfo</code> data.
*
* This is used in order to keep LinkedTaskInfo lightweight with minimal dependencies.
*/
private static ILinkedTaskInfo reconcile(ILinkedTaskInfo info) {
AbstractTask task = info.getTask();
if (task != null) {
return info;
}
String repositoryUrl = info.getRepositoryUrl();
String taskId = info.getTaskId();
String taskFullUrl = info.getTaskUrl();
String comment = info.getComment();
TaskRepositoryManager repositoryManager = TasksUiPlugin.getRepositoryManager();
TaskRepository repository = null;
if (repositoryUrl != null) {
repository = repositoryManager.getRepository(repositoryUrl);
}
if (taskFullUrl == null && comment != null) {
taskFullUrl = getUrlFromComment(comment);
}
AbstractRepositoryConnector connector = null;
if (taskFullUrl != null) {
connector = repositoryManager.getConnectorForRepositoryTaskUrl(taskFullUrl);
}
if (connector == null && repository != null) {
connector = repositoryManager.getRepositoryConnector(repository.getConnectorKind());
}
if (repositoryUrl == null && connector != null) {
repositoryUrl = connector.getRepositoryUrlFromTaskUrl(taskFullUrl);
if (repository == null) {
repository = repositoryManager.getRepository(repositoryUrl);
}
}
if (taskId == null && connector != null) {
taskId = connector.getTaskIdFromTaskUrl(taskFullUrl);
}
if (taskId == null && comment != null) {
Collection<AbstractRepositoryConnector> connectors = connector != null ? Collections.singletonList(connector)
: TasksUiPlugin.getRepositoryManager().getRepositoryConnectors();
REPOSITORIES: for (AbstractRepositoryConnector c : connectors) {
Collection<TaskRepository> repositories = repository != null ? Collections.singletonList(repository)
: TasksUiPlugin.getRepositoryManager().getRepositories(c.getConnectorKind());
for (TaskRepository r : repositories) {
String[] ids = c.getTaskIdsFromComment(r, comment);
if (ids != null && ids.length > 0) {
taskId = ids[0];
connector = c;
repository = r;
repositoryUrl = r.getUrl();
break REPOSITORIES;
}
}
}
}
if (taskId == null && comment != null) {
CommitTemplateManager commitTemplateManager = FocusedTeamUiPlugin.getDefault().getCommitTemplateManager();
taskId = commitTemplateManager.getTaskIdFromCommentOrLabel(comment);
if (taskId == null) {
taskId = getTaskIdFromLegacy07Label(comment);
}
}
if (taskFullUrl == null && repositoryUrl != null && taskId != null && connector != null) {
taskFullUrl = connector.getTaskUrl(repositoryUrl, taskId);
}
if (task == null) {
if (taskId != null && repositoryUrl != null) {
// XXX fix this hack (jira ids don't work here)
if (!taskId.contains(RepositoryTaskHandleUtil.HANDLE_DELIM)) {
// String handle = AbstractTask.getHandle(repositoryUrl, taskId);
task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repositoryUrl, taskId);
}
}
if (task == null && taskFullUrl != null) {
// search by fullUrl
for (AbstractTask currTask : TasksUiPlugin.getTaskListManager().getTaskList().getAllTasks()) {
if (currTask != null) {
String currUrl = currTask.getUrl();
if (taskFullUrl.equals(currUrl)) {
return new LinkedTaskInfo(currTask, null);
}
}
}
}
}
if (task != null) {
return new LinkedTaskInfo(task, null);
}
return new LinkedTaskInfo(repositoryUrl, taskId, taskFullUrl, comment);
}
public static String getUrlFromComment(String comment) {
int httpIndex = comment.indexOf(PREFIX_HTTP);
int httpsIndex = comment.indexOf(PREFIX_HTTPS);
int idStart = -1;
if (httpIndex != -1) {
idStart = httpIndex;
} else if (httpsIndex != -1) {
idStart = httpsIndex;
}
if (idStart != -1) {
int idEnd = comment.indexOf(' ', idStart);
if (idEnd == -1) {
return comment.substring(idStart);
} else if (idEnd != -1 && idStart < idEnd) {
return comment.substring(idStart, idEnd);
}
}
return null;
}
public static String getTaskIdFromLegacy07Label(String comment) {
String PREFIX_DELIM = ":";
String PREFIX_START_1 = "Progress on:";
String PREFIX_START_2 = "Completed:";
String usedPrefix = PREFIX_START_1;
int firstDelimIndex = comment.indexOf(PREFIX_START_1);
if (firstDelimIndex == -1) {
firstDelimIndex = comment.indexOf(PREFIX_START_2);
usedPrefix = PREFIX_START_2;
}
if (firstDelimIndex != -1) {
int idStart = firstDelimIndex + usedPrefix.length();
int idEnd = comment.indexOf(PREFIX_DELIM, firstDelimIndex + usedPrefix.length());// comment.indexOf(PREFIX_DELIM);
if (idEnd != -1 && idStart < idEnd) {
String id = comment.substring(idStart, idEnd);
if (id != null) {
return id.trim();
}
} else {
return comment.substring(0, firstDelimIndex);
}
}
return null;
}
private static final class OpenCorrespondingTaskJob extends Job {
private final Object element;
private OpenCorrespondingTaskJob(String name, Object element) {
super(name);
this.element = element;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
ILinkedTaskInfo info = null;
if (element instanceof ILinkedTaskInfo) {
info = (ILinkedTaskInfo) element;
} else if (element instanceof IAdaptable) {
info = (ILinkedTaskInfo) ((IAdaptable) element).getAdapter(ILinkedTaskInfo.class);
}
if (info == null) {
info = (ILinkedTaskInfo) Platform.getAdapterManager().getAdapter(element, ILinkedTaskInfo.class);
}
if (info != null) {
info = reconcile(info);
final AbstractTask task = info.getTask();
if (task != null) {
TasksUiUtil.refreshAndOpenTaskListElement(task);
return Status.OK_STATUS;
}
if (info.getRepositoryUrl() != null && info.getTaskId() != null) {
TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(
info.getRepositoryUrl());
String taskId = info.getTaskId();
if (repository != null && taskId != null) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(repository.getConnectorKind());
if (connectorUi != null) {
connectorUi.openRepositoryTask(repository.getUrl(), taskId);
return Status.OK_STATUS;
}
}
}
final String taskFullUrl = info.getTaskUrl();
if (taskFullUrl != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
TasksUiUtil.openUrl(taskFullUrl, false);
}
});
return Status.OK_STATUS;
}
}
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
boolean openDialog = MessageDialog.openQuestion(window.getShell(), ITasksUiConstants.TITLE_DIALOG,
"Unable to match task. Open Repository Task dialog?");
if (openDialog) {
new OpenRepositoryTask().run(null);
}
}
});
return Status.OK_STATUS;
}
}
}
|
package org.tigris.subversion.subclipse.ui.comments;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.DeviceResourceException;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.text.DefaultTextHover;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.MarginPainter;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.reconciler.DirtyRegion;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.reconciler.MonoReconciler;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.AnnotationPainter;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.internal.ui.SWTUtils;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector;
import org.eclipse.ui.texteditor.spelling.SpellingContext;
import org.eclipse.ui.texteditor.spelling.SpellingProblem;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.util.Util;
import org.tigris.subversion.subclipse.ui.ISVNUIConstants;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.subclipse.ui.SVNUIPlugin;
import org.tigris.subversion.subclipse.ui.dialogs.DialogArea;
import org.tigris.subversion.subclipse.ui.settings.CommentProperties;
/**
* This area provides the widgets for providing the SVN commit comment
*/
public class CommitCommentArea extends DialogArea {
private boolean showLabel = true;;
public static final String SPELLING_ERROR = "spelling.error"; //$NON-NLS-1$
private class TextBox implements ModifyListener, TraverseListener, FocusListener, Observer {
private final StyledText fTextField; // updated only by modify events
private final String fMessage;
private String fText;
private LocalResourceManager fResources;
public TextBox(Composite composite, String message, String initialText) {
fMessage= message;
fText= initialText;
// Create a resource manager for the composite so it gets automatically disposed
fResources= new LocalResourceManager(JFaceResources.getResources(), composite);
AnnotationModel annotationModel = new AnnotationModel();
IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess();
AnnotationRulerColumn annotationRuler = new AnnotationRulerColumn(annotationModel, 16, annotationAccess);
CompositeRuler compositeRuler = new CompositeRuler();
compositeRuler.setModel(annotationModel);
compositeRuler.addDecorator(0, annotationRuler);
Composite cc = new Composite(composite, SWT.BORDER);
cc.setLayout(new FillLayout());
cc.setLayoutData(new GridData(GridData.FILL_BOTH));
SourceViewer sourceViewer = new SourceViewer(cc, compositeRuler, null, true,
SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
if (modifyListener != null) {
sourceViewer.getTextWidget().addModifyListener(modifyListener);
}
// TODO should be done in the source viewer configuration
Font commentFont = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry().get(ISVNUIConstants.SVN_COMMENT_FONT);
if (commentFont != null) sourceViewer.getTextWidget().setFont(commentFont);
int widthMarker = 0;
if (commentProperties != null) widthMarker = commentProperties.getLogWidthMarker();
if (widthMarker > 0) {
MarginPainter marginPainter = new MarginPainter(sourceViewer);
marginPainter.setMarginRulerColumn(widthMarker);
marginPainter.setMarginRulerColor(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY));
sourceViewer.addPainter(marginPainter);
}
sourceViewer.showAnnotations(false);
sourceViewer.showAnnotationsOverview(false);
if (isSpellingAnnotationEnabled()) {
// to paint the annotations
AnnotationPainter ap = new AnnotationPainter(sourceViewer, annotationAccess);
ap.addAnnotationType(SPELLING_ERROR);
ap.setAnnotationTypeColor(SPELLING_ERROR, getSpellingErrorColor(composite));
// this will draw the squiggles under the text
sourceViewer.addPainter(ap);
}
Document document = new Document(initialText);
// NOTE: Configuration must be applied before the document is set in order for
// Hyperlink coloring to work. (Presenter needs document object up front)
sourceViewer.configure(new SourceViewerConfig(annotationModel, document));
sourceViewer.setDocument(document, annotationModel);
fTextField = sourceViewer.getTextWidget();
fTextField.addTraverseListener(this);
fTextField.addModifyListener(this);
fTextField.addFocusListener(this);
fTextField.setWordWrap(mustWrapWord());
}
private boolean mustWrapWord() {
if (commentProperties != null && commentProperties.getLogWidthMarker() > 0) {
return false;
}
return true;
}
private boolean isSpellingAnnotationEnabled() {
// Need to determine how to ask the proper question to the AnnotationPreferences
return true;
}
private Color getSpellingErrorColor(Composite composite) {
AnnotationPreference pref = EditorsUI
.getAnnotationPreferenceLookup().getAnnotationPreference(
"org.eclipse.ui.workbench.texteditor.spelling"); // $NON-NLS-1$
String preferenceKey = pref.getColorPreferenceKey();
try {
return fResources.createColor(PreferenceConverter.getColor(EditorsUI.getPreferenceStore(), preferenceKey));
} catch (DeviceResourceException e) {
SVNUIPlugin.log(IStatus.ERROR, Policy.bind("internal"), e); //$NON-NLS-1$
return JFaceColors.getErrorText(composite.getDisplay());
}
}
public void modifyText(ModifyEvent e) {
final String old = fText;
fText = fTextField.getText();
firePropertyChangeChange(COMMENT_MODIFIED, old, fText);
}
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN && (e.stateMask & SWT.SHIFT) != 0) {
e.doit = false;
return;
}
if (e.detail == SWT.TRAVERSE_RETURN && (e.stateMask & SWT.CTRL) != 0) {
e.doit = false;
firePropertyChangeChange(OK_REQUESTED, null, null);
}
}
public void focusGained(FocusEvent e) {
if (fText.length() > 0)
return;
fTextField.removeModifyListener(this);
try {
fTextField.setText(fText);
} finally {
fTextField.addModifyListener(this);
}
}
public void focusLost(FocusEvent e) {
if (fText.length() > 0)
return;
fTextField.removeModifyListener(this);
try {
fTextField.setText(fMessage);
fTextField.selectAll();
} finally {
fTextField.addModifyListener(this);
}
}
public void setEnabled(boolean enabled) {
fTextField.setEnabled(enabled);
}
public void update(Observable o, Object arg) {
if (arg instanceof String) {
setText((String)arg); // triggers a modify event
if (modifyListener != null) modifyListener.modifyText(null);
}
}
public String getText() {
return fText;
}
public int getCommentLength() {
if (fTextField == null) return 0;
if (fTextField.getText().equals(Policy.bind("CommitCommentArea_0"))) return 0; //$NON-NLS-1$
return fTextField.getText().trim().length();
}
private void setText(String text) {
if (text.length() == 0) {
fTextField.setText(fMessage);
fTextField.selectAll();
} else
fTextField.setText(text);
}
public void setFocus() {
fTextField.setFocus();
}
}
public class SourceViewerConfig extends SourceViewerConfiguration {
private CommentSpellingReconcileStrategy strategy;
public SourceViewerConfig(AnnotationModel annotationModel,
Document document) {
strategy = new CommentSpellingReconcileStrategy(annotationModel);
strategy.setDocument(document);
}
public IReconciler getReconciler(ISourceViewer sourceViewer) {
MonoReconciler reconciler = new MonoReconciler(strategy, false);
reconciler.setIsIncrementalReconciler(false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(200);
return reconciler;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return new DefaultTextHover(sourceViewer);
}
}
public class CommentSpellingReconcileStrategy implements IReconcilingStrategy {
/** The document to operate on. */
private IDocument fDocument;
private SpellingContext fSpellingContext;
private IAnnotationModel fAnnotationModel;
public CommentSpellingReconcileStrategy(AnnotationModel annotationModel) {
this.fAnnotationModel = annotationModel;
fSpellingContext = new SpellingContext();
fSpellingContext.setContentType(Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT));
}
public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
reconcile(subRegion);
}
public void reconcile(IRegion region) {
SpellingProblemCollector collector = new SpellingProblemCollector(fAnnotationModel);
EditorsUI.getSpellingService().check(fDocument, fSpellingContext, collector, null);
}
public void setDocument(IDocument document) {
fDocument = document;
}
/**
* Spelling problem collector that forwards {@link SpellingProblem}s as
* {@link IProblem}s to the {@link org.eclipse.jdt.core.IProblemRequestor}.
*/
private class SpellingProblemCollector implements ISpellingProblemCollector {
/** Annotation model */
private IAnnotationModel fAnnotationModel;
/** Annotations to add <ErrorAnnotation, Position> */
private Map fAddAnnotations;
/**
* Initializes this collector with the given annotation model.
*
* @param annotationModel
* the annotation model
*/
public SpellingProblemCollector(IAnnotationModel annotationModel) {
fAnnotationModel = annotationModel;
}
/*
* @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept(org.eclipse.ui.texteditor.spelling.SpellingProblem)
*/
public void accept(SpellingProblem problem) {
fAddAnnotations.put(new Annotation(SPELLING_ERROR, false, problem.getMessage()),
new Position(problem.getOffset(), problem.getLength()));
}
/*
* @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#beginCollecting()
*/
public void beginCollecting() {
fAddAnnotations = new HashMap();
}
/*
* @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#endCollecting()
*/
public void endCollecting() {
List removeAnnotations = new ArrayList();
for(Iterator iter = fAnnotationModel.getAnnotationIterator(); iter.hasNext();) {
Annotation annotation = (Annotation) iter.next();
if(SPELLING_ERROR.equals(annotation.getType()))
removeAnnotations.add(annotation);
}
for(Iterator iter = removeAnnotations.iterator(); iter.hasNext();)
fAnnotationModel.removeAnnotation((Annotation) iter.next());
for(Iterator iter = fAddAnnotations.keySet().iterator(); iter.hasNext();) {
Annotation annotation = (Annotation) iter.next();
fAnnotationModel.addAnnotation(annotation, (Position) fAddAnnotations.get(annotation));
}
fAddAnnotations = null;
}
}
}
private static class ComboBox extends Observable implements SelectionListener, FocusListener {
private final String fMessage;
private final String [] fComments;
private String[] fCommentTemplates;
private final Combo fCombo;
public ComboBox(Composite composite, String message, String [] options,
String[] commentTemplates) {
fMessage= message;
fComments= options;
fCommentTemplates = commentTemplates;
fCombo = new Combo(composite, SWT.READ_ONLY);
fCombo.setLayoutData(SWTUtils.createHFillGridData());
fCombo.setVisibleItemCount(20);
// populate the previous comment list
populateList();
// We don't want to have an initial selection
fCombo.addFocusListener(this);
fCombo.addSelectionListener(this);
}
private void populateList() {
fCombo.removeAll();
fCombo.add(fMessage);
for (int i = 0; i < fCommentTemplates.length; i++) {
fCombo.add(Policy.bind("CommitCommentArea_6") + ": " + //$NON-NLS-1$
Util.flattenText(fCommentTemplates[i]));
}
for (int i = 0; i < fComments.length; i++) {
fCombo.add(Util.flattenText(fComments[i]));
}
fCombo.setText(fMessage);
}
public void widgetSelected(SelectionEvent e) {
int index = fCombo.getSelectionIndex();
if (index > 0) {
index
setChanged();
// map from combo box index to array index
String message;
if (index < fCommentTemplates.length) {
message = fCommentTemplates[index];
} else {
message = fComments[index - fCommentTemplates.length];
}
notifyObservers(message);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
public void focusGained(FocusEvent e) {
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent e) {
fCombo.removeSelectionListener(this);
try {
fCombo.setText(fMessage);
} finally {
fCombo.addSelectionListener(this);
}
}
public void setEnabled(boolean enabled) {
fCombo.setEnabled(enabled);
}
void setCommentTemplates(String[] templates) {
fCommentTemplates = templates;
populateList();
}
}
private static final String EMPTY_MESSAGE= Policy.bind("CommitCommentArea_0");
private static final String COMBO_MESSAGE= Policy.bind("CommitCommentArea_1");
public static final String OK_REQUESTED = "OkRequested";//$NON-NLS-1$
public static final String COMMENT_MODIFIED = "CommentModified";//$NON-NLS-1$
private TextBox fTextBox;
private ComboBox fComboBox;
private String fProposedComment;
private Composite fComposite;
private String enterCommentMessage;
private CommentProperties commentProperties;
private ModifyListener modifyListener;
/**
* Constructor for CommitCommentArea.
* @param parentDialog
* @param settings
*/
public CommitCommentArea(Dialog parentDialog, IDialogSettings settings) {
super(parentDialog, settings);
}
public CommitCommentArea(Dialog parentDialog, IDialogSettings settings, CommentProperties commentProperties) {
this(parentDialog, settings);
this.commentProperties = commentProperties;
}
/**
* Constructor for CommitCommentArea.
* @param parentDialog
* @param settings
* @param enterCommentMessage
*/
public CommitCommentArea(Dialog parentDialog, IDialogSettings settings, String enterCommentMessage) {
this(parentDialog, settings);
this.enterCommentMessage = enterCommentMessage;
}
public CommitCommentArea(Dialog parentDialog, IDialogSettings settings, String enterCommentMessage, CommentProperties commentProperties) {
this(parentDialog, settings, enterCommentMessage);
this.commentProperties = commentProperties;
}
public Control createArea(Composite parent) {
fComposite = createGrabbingComposite(parent, 1);
initializeDialogUnits(fComposite);
if (showLabel) {
Label label = new Label(fComposite, SWT.NULL);
label.setLayoutData(new GridData());
if (enterCommentMessage == null) label.setText(Policy.bind("ReleaseCommentDialog.enterComment")); //$NON-NLS-1$
else label.setText(enterCommentMessage);
}
fTextBox= new TextBox(fComposite, EMPTY_MESSAGE, getInitialComment());
final String [] comments = SVNUIPlugin.getPlugin().getRepositoryManager().getCommentsManager().getPreviousComments();
final String[] commentTemplates = SVNUIPlugin.getPlugin().getRepositoryManager().getCommentsManager().getCommentTemplates();
fComboBox= new ComboBox(fComposite, COMBO_MESSAGE, comments, commentTemplates);
Link templatesPrefsLink = new Link(fComposite, 0);
templatesPrefsLink.setText("<a href=\"configureTemplates\">Configure Comment Templates...</a>"); //$NON-NLS-1$
templatesPrefsLink.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
openCommentTemplatesPreferencePage();
}
public void widgetSelected(SelectionEvent e) {
openCommentTemplatesPreferencePage();
}
});
fComboBox.addObserver(fTextBox);
return fComposite;
}
void openCommentTemplatesPreferencePage() {
PreferencesUtil.createPreferenceDialogOn(
null,
"org.tigris.subversion.subclipse.ui.CommentTemplatesPreferences", //$NON-NLS-1$
new String[] { "org.tigris.subversion.subclipse.ui.CommentTemplatesPreferences" }, //$NON-NLS-1$
null).open();
fComboBox.setCommentTemplates(
SVNUIPlugin.getPlugin().getRepositoryManager().getCommentsManager().getCommentTemplates());
}
public String getComment() {
return getComment(false);
}
public String getComment(boolean save) {
final String comment= fTextBox.getText();
if (comment == null)
return ""; //$NON-NLS-1$
if (save) addComment(comment);
return comment;
}
public void addComment(String comment) {
if (comment != null && comment.trim().length() > 0) SVNUIPlugin.getPlugin().getRepositoryManager().getCommentsManager().addComment(comment);
}
public String getCommentWithPrompt(Shell shell) {
final String comment= getComment(false);
if (comment.length() == 0) {
final IPreferenceStore store= SVNUIPlugin.getPlugin().getPreferenceStore();
final String value= store.getString(ISVNUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (MessageDialogWithToggle.NEVER.equals(value))
return null;
if (MessageDialogWithToggle.PROMPT.equals(value)) {
final String title= Policy.bind("CommitCommentArea_2");
final String message= Policy.bind("CommitCommentArea_3");
final String toggleMessage= Policy.bind("CommitCommentArea_4");
final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ISVNUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (dialog.getReturnCode() != IDialogConstants.YES_ID) {
fTextBox.setFocus();
return null;
}
}
}
return getComment(true);
}
public void setFocus() {
if (fTextBox != null) {
fTextBox.setFocus();
}
}
public void setProposedComment(String proposedComment) {
if (proposedComment == null || proposedComment.length() == 0) {
this.fProposedComment = null;
} else {
this.fProposedComment = proposedComment;
}
}
public boolean hasCommitTemplate() {
try {
String commitTemplate = getCommitTemplate();
return commitTemplate != null && commitTemplate.length() > 0;
} catch (SVNException e) {
SVNUIPlugin.log(e);
return false;
}
}
public void setEnabled(boolean enabled) {
fTextBox.setEnabled(enabled);
fComboBox.setEnabled(enabled);
}
public Composite getComposite() {
return fComposite;
}
public int getCommentLength() {
if (fTextBox == null) return 0;
return fTextBox.getCommentLength();
}
protected void firePropertyChangeChange(String property, Object oldValue, Object newValue) {
super.firePropertyChangeChange(property, oldValue, newValue);
}
private String getInitialComment() {
if (fProposedComment != null)
return fProposedComment;
try {
return getCommitTemplate();
} catch (SVNException e) {
SVNUIPlugin.log(e);
return ""; //$NON-NLS-1$
}
}
private String getCommitTemplate() throws SVNException {
if ((commentProperties != null) && (commentProperties.getLogTemplate() != null)) {
return commentProperties.getLogTemplate();
}
return ""; //$NON-NLS-1$
}
public void setModifyListener(ModifyListener modifyListener) {
this.modifyListener = modifyListener;
}
public void setShowLabel(boolean showLabel) {
this.showLabel = showLabel;
}
}
|
package com.redhat.ceylon.eclipse.core.builder;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.PROBLEM_MARKER_ID;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;
import static org.eclipse.core.resources.IResource.DEPTH_ZERO;
import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;
import static org.eclipse.jdt.core.IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import com.redhat.ceylon.compiler.java.launcher.Main;
import com.redhat.ceylon.compiler.java.launcher.Main.ExitState;
final class CompileErrorReporter implements
DiagnosticListener<JavaFileObject> {
private IProject project;
private boolean errorReported;
private List<IFolder> sourceDirectories;
public CompileErrorReporter(IProject project) {
this.project = project;
sourceDirectories = CeylonBuilder.getSourceFolders(project);
}
public void failed() {
if (!errorReported) {
setupMarker(project, null);
}
}
public void failed(final ExitState exitState) {
Diagnostic<? extends JavaFileObject> diagnostic = null;
if (exitState.javacExitCode == Main.EXIT_ABNORMAL) {
diagnostic = new Diagnostic<JavaFileObject>() {
@Override
public javax.tools.Diagnostic.Kind getKind() {
return javax.tools.Diagnostic.Kind.ERROR;
}
@Override
public JavaFileObject getSource() {
return null;
}
@Override
public long getPosition() {
return 0;
}
@Override
public long getStartPosition() {
return 0;
}
@Override
public long getEndPosition() {
return 0;
}
@Override
public long getLineNumber() {
return 0;
}
@Override
public long getColumnNumber() {
return 0;
}
@Override
public String getCode() {
return null;
}
@Override
public String getMessage(Locale locale) {
return "The Ceylon Java backend compiler failed abnormally" +
(exitState.ceylonCodegenExceptionCount > 0 ? "\n with " + exitState.ceylonCodegenExceptionCount + " code generation exceptions" : "") +
(exitState.ceylonCodegenErroneousCount > 0 ? "\n with " + exitState.ceylonCodegenErroneousCount + " erroneous code generations" : "") +
(exitState.ceylonCodegenGarbageCount > 0 ? "\n with " + exitState.ceylonCodegenGarbageCount + " malformed Javac tree cases" : "") +
(exitState.abortingException != null ? "\n with a throwable : " + exitState.abortingException.toString() : "") +
"";
}
};
}
if (!errorReported || diagnostic != null) {
setupMarker(project, diagnostic);
}
}
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errorReported = true;
JavaFileObject source = diagnostic.getSource();
if (source == null) {
// no source file
if (!diagnostic.toString().startsWith("Note: Created module")) {
setupMarker(project, diagnostic);
}
}
else {
IPath absolutePath = new Path(source.getName());
IFile file = null;
for (IFolder sourceDirectory : sourceDirectories) {
IPath sourceDirPath = sourceDirectory.getLocation();
if (sourceDirPath.isPrefixOf(absolutePath)) {
IResource r = sourceDirectory.findMember(absolutePath.makeRelativeTo(sourceDirPath));
if (r instanceof IFile) {
file = (IFile) r;
}
}
}
if (file == null) {
file = getWorkspace().getRoot()
.getFileForLocation(new Path(source.getName()));
}
if(file != null) {
if (CeylonBuilder.isCeylon(file)){
try {
for (IMarker m: file.findMarkers(PROBLEM_MARKER_ID, true, DEPTH_ZERO)) {
int sev = ((Integer) m.getAttribute(IMarker.SEVERITY)).intValue();
if (sev==IMarker.SEVERITY_ERROR) {
return;
}
}
}
catch (CoreException e) {
e.printStackTrace();
}
setupMarker(file, diagnostic);
}
if (CeylonBuilder.isJava(file)){
try {
for (IMarker m: file.findMarkers(JAVA_MODEL_PROBLEM_MARKER, false, DEPTH_ZERO)) {
int sev = ((Integer) m.getAttribute(IMarker.SEVERITY)).intValue();
if (sev==IMarker.SEVERITY_ERROR) {
return;
}
}
}
catch (CoreException e) {
e.printStackTrace();
}
setupMarker(file, diagnostic);
}
}else{
setupMarker(project, diagnostic);
}
}
}
private void setupMarker(IResource resource, Diagnostic<? extends JavaFileObject> diagnostic) {
try {
long line = diagnostic==null ? -1 : diagnostic.getLineNumber();
String markerId = PROBLEM_MARKER_ID + ".backend";
if (resource instanceof IFile) {
if (CeylonBuilder.isJava((IFile)resource)) {
markerId = JAVA_MODEL_PROBLEM_MARKER;
}
// if (line<0) {
//TODO: use the Symbol to get a location for the javac error
// String name = ((Symbol)((JCDiagnostic) diagnostic).getArgs()[0]).name.toString();
// Declaration member = CeylonBuilder.getPackage((IFile)resource).getDirectMember(name, null, false);
}
IMarker marker = resource.createMarker(markerId);
if (line>=0) {
//Javac doesn't have line number info for certain errors
marker.setAttribute(IMarker.LINE_NUMBER, (int) line);
marker.setAttribute(IMarker.CHAR_START,
(int) diagnostic.getStartPosition());
marker.setAttribute(IMarker.CHAR_END,
(int) diagnostic.getEndPosition());
}
if (markerId.equals(JAVA_MODEL_PROBLEM_MARKER)) {
marker.setAttribute(IMarker.SOURCE_ID, PLUGIN_ID);
}
String message = diagnostic==null ?
"unexplained compilation problem" :
diagnostic.getMessage(Locale.getDefault());
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
switch (diagnostic==null ? Diagnostic.Kind.ERROR : diagnostic.getKind()) {
case ERROR:
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
break;
case WARNING:
case MANDATORY_WARNING:
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
break;
default:
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
}
}
catch (CoreException ce) {
ce.printStackTrace();
}
}
}
|
package com.redhat.ceylon.eclipse.imp.editor;
import static java.lang.Character.isWhitespace;
import static org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
import static org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS;
import org.eclipse.core.runtime.Platform;
import org.eclipse.imp.services.IAutoEditStrategy;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.TextUtilities;
public class CeylonAutoEditStrategy implements IAutoEditStrategy {
public void customizeDocumentCommand(IDocument doc, DocumentCommand cmd) {
if (cmd.doit == false) {
return;
}
else if (cmd.length==0 && cmd.text!=null &&
isLineEnding(doc, cmd.text)) {
smartIndentAfterNewline(doc, cmd);
}
else if (cmd.text.length()==1 ||
getIndentWithSpaces() && isIndent(cmd.text)) {
smartIndentOnKeypress(doc, cmd);
}
}
public boolean isIndent(String text) {
if (text.length()==getIndentSpaces()) {
for (char c: text.toCharArray()) {
if (c!=' ') return false;
}
return true;
}
else {
return false;
}
}
private void smartIndentAfterNewline(IDocument d, DocumentCommand c) {
if (c.offset==-1 || d.getLength()==0) {
return;
}
try {
//if (end > start) {
indentNewLine(d, c);
}
catch (BadLocationException bleid ) {
bleid.printStackTrace();
}
}
private void smartIndentOnKeypress(IDocument d, DocumentCommand c) {
if (c.offset==-1 || d.getLength()==0) {
return;
}
try {
adjustIndentOfCurrentLine(d, c);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
private void adjustIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
switch (c.text.charAt(0)) {
case '}':
reduceIndentOfCurrentLine(d, c);
break;
case '{':
case '\t':
fixIndentOfCurrentLine(d, c);
break;
default:
if (isIndent(c.text)) {
fixIndentOfCurrentLine(d, c);
}
}
}
protected void fixIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int start = getStartOfCurrentLine(d, c);
int endOfWs = findEndOfWhiteSpace(d, c);
if (c.offset<=endOfWs) {
if (start==0) {
c.text="";
}
else {
c.offset = getEndOfPreviousLine(d, c);
indentNewLine(d, c);
if (d.getChar(endOfWs)=='}') {
reduceIndent(c);
}
}
c.offset=start;
c.length=endOfWs-start;
}
}
protected void reduceIndent(DocumentCommand c) {
int spaces = getIndentSpaces();
if (endsWithSpaces(c.text, spaces)) {
c.text = c.text.substring(0, c.text.length()-spaces);
}
else if (c.text.endsWith("\t")) {
c.text = c.text.substring(0, c.text.length()-1);
}
}
private void reduceIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int spaces = getIndentSpaces();
if (endsWithSpaces(d.get(c.offset-spaces, spaces),spaces)) {
c.offset = c.offset-spaces;
c.length = spaces;
}
else if (d.get(c.offset-1,1).equals("\t")) {
c.offset = c.offset-1;
c.length = 1;
}
}
private void decrementIndent(StringBuilder buf, String indent)
throws BadLocationException {
int spaces = getIndentSpaces();
if (endsWithSpaces(indent,spaces)) {
buf.setLength(buf.length()-spaces);
}
else if (indent.endsWith("\t")) {
buf.setLength(buf.length()-1);
}
}
/*private int getStartOfPreviousLine(IDocument d, DocumentCommand c)
throws BadLocationException {
return getStartOfPreviousLine(d, c.offset);
}*/
private int getStartOfPreviousLine(IDocument d, int offset)
throws BadLocationException {
return d.getLineOffset(d.getLineOfOffset(offset)-1);
}
/*private int getStartOfNextLine(IDocument d, int offset)
throws BadLocationException {
return d.getLineOffset(d.getLineOfOffset(offset)+1);
}*/
private void indentNewLine(IDocument d, DocumentCommand c)
throws BadLocationException {
boolean isCorrection = c.text.equals("{")
|| c.text.equals("\t")
|| getIndentWithSpaces() && isIndent(c.text);
char terminator1 = getPreviousNonWhitespaceCharacterInLine(d, c.offset-1);
char terminator2 = getPreviousNonWhitespaceCharacter(d, c.offset-1);
//char terminator2 = getNextNonWhitespaceCharacterInLine(d, getStartOfPreviousLine(d, c.offset));
//char terminator2 = getLastNonWhitespaceCharacterInLine(d, getStartOfPreviousLine(d, c.offset), getEndOfPreviousLine(d, c.offset));
char initiator1 = getNextNonWhitespaceCharacterInLine(d, c.offset);
char initiator2 = isCorrection ?
getNextNonWhitespaceCharacter(d, c.offset) : initiator1;
boolean isContinuation = terminator1!=';' && terminator1!='}' && terminator1!='{' &&
terminator1!='\n' && //ahem, ugly "null"
initiator2!='{' &&
!c.text.equals("{");
boolean isBeginning = terminator1=='{' && initiator1!='}';
boolean isEnding = initiator1=='}' && terminator2!='{';
StringBuilder buf = new StringBuilder(isCorrection?"":c.text);
String indent = getIndent(d, c);
if (!indent.isEmpty()) {
buf.append(indent);
if (isBeginning) {
//increment the indent level
incrementIndent(buf, indent);
}
else if (isContinuation) {
incrementIndent(buf, indent);
incrementIndent(buf, indent);
}
}
else {
if (isBeginning) {
initialIndent(buf);
}
else if (isContinuation) {
initialIndent(buf);
initialIndent(buf);
}
}
if (isEnding) {
decrementIndent(buf, indent);
if (isContinuation) decrementIndent(buf, indent);
}
if (c.text.equals("{")) buf.append("{");
c.text = buf.toString();
}
private String getIndent(IDocument d, DocumentCommand c)
throws BadLocationException {
int start = getStartOfCurrentLine(d, c);
int end = getEndOfCurrentLine(d, c);
while (true) {
//System.out.println(d.get(start, end-start));
if (start==0) {
return "";
}
else {
char ch1 = getNextNonWhitespaceCharacterInLine(d, start);
if (ch1=='}') break;
int startOfPrev = getStartOfPreviousLine(d, start);
int endOfPrev = getEndOfPreviousLine(d, start);
char ch = getLastNonWhitespaceCharacterInLine(d, startOfPrev, endOfPrev);
if (ch==';' || ch=='{' || ch=='}') break;
start = startOfPrev;
end = endOfPrev;
}
}
int endOfWs = firstEndOfWhitespace(d, start, end);
return d.get(start, endOfWs-start);
}
private char getLastNonWhitespaceCharacterInLine(IDocument d, int offset, int end)
throws BadLocationException {
char result = '\n'; //ahem, ugly null!
for (;offset<end; offset++) {
char ch = d.getChar(offset);
if (!isWhitespace(ch)) result=ch;
}
return result;
}
private void incrementIndent(StringBuilder buf, String indent) {
int spaces = getIndentSpaces();
if (indent.length()>=spaces &&
endsWithSpaces(indent,spaces)) {
for (int i=1; i<=spaces; i++) {
buf.append(' ');
}
}
else if (indent.length()>=0 &&
indent.charAt(indent.length()-1)=='\t') {
buf.append('\t');
}
}
private char getPreviousNonWhitespaceCharacter(IDocument d, int offset)
throws BadLocationException {
for (;offset>=0; offset
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0))) {
return ch.charAt(0);
}
}
return '\n';
}
private char getPreviousNonWhitespaceCharacterInLine(IDocument d, int offset)
throws BadLocationException {
for (;offset>=0; offset
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0)) ||
isLineEnding(d, ch)) {
return ch.charAt(0);
}
}
return '\n';
}
private char getNextNonWhitespaceCharacterInLine(IDocument d, int offset)
throws BadLocationException {
for (;offset<d.getLength(); offset++) {
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0)) ||
isLineEnding(d, ch)) {
return ch.charAt(0);
}
}
return '\n';
}
private char getNextNonWhitespaceCharacter(IDocument d, int offset)
throws BadLocationException {
for (;offset<d.getLength(); offset++) {
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0))) {
return ch.charAt(0);
}
}
return '\n';
}
private static void initialIndent(StringBuilder buf) {
//guess an initial indent level
if (getIndentWithSpaces()) {
int spaces = getIndentSpaces();
for (int i=1; i<=spaces; i++) {
buf.append(' ');
}
}
else {
buf.append('\t');
}
}
private int getStartOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int p = c.offset == d.getLength() ? c.offset-1 : c.offset;
return d.getLineInformationOfOffset(p).getOffset();
}
private int getEndOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int p = c.offset == d.getLength() ? c.offset-1 : c.offset;
IRegion lineInfo = d.getLineInformationOfOffset(p);
return lineInfo.getOffset() + lineInfo.getLength();
}
private int getEndOfPreviousLine(IDocument d, DocumentCommand c)
throws BadLocationException {
return getEndOfPreviousLine(d, c.offset);
}
private int getEndOfPreviousLine(IDocument d, int offset)
throws BadLocationException {
int p = offset == d.getLength() ? offset-1 : offset;
IRegion lineInfo = d.getLineInformation(d.getLineOfOffset(p)-1);
return lineInfo.getOffset() + lineInfo.getLength();
}
private boolean endsWithSpaces(String string, int spaces) {
if (string.length()<spaces) return false;
for (int i=1; i<=spaces; i++) {
if (string.charAt(string.length()-i)!=' ') {
return false;
}
}
return true;
}
private static int getIndentSpaces() {
return Platform.getPreferencesService()
.getInt("org.eclipse.ui.editors", EDITOR_TAB_WIDTH, 4, null);
}
private static boolean getIndentWithSpaces() {
return Platform.getPreferencesService()
.getBoolean("org.eclipse.ui.editors", EDITOR_SPACES_FOR_TABS, false, null);
}
public static String getDefaultIndent() {
StringBuilder result = new StringBuilder();
initialIndent(result);
return result.toString();
}
private int findEndOfWhiteSpace(IDocument d, DocumentCommand c)
throws BadLocationException {
int offset = getStartOfCurrentLine(d, c);
int end = getEndOfCurrentLine(d, c);
return firstEndOfWhitespace(d, offset, end);
}
/**
* Returns the first offset greater than <code>offset</code> and smaller than
* <code>end</code> whose character is not a space or tab character. If no such
* offset is found, <code>end</code> is returned.
*
* @param d the document to search in
* @param offset the offset at which searching start
* @param end the offset at which searching stops
* @return the offset in the specified range whose character is not a space or tab
* @exception BadLocationException if position is an invalid range in the given document
*/
private int firstEndOfWhitespace(IDocument d, int offset, int end)
throws BadLocationException {
while (offset < end) {
char ch= d.getChar(offset);
if (ch!=' ' && ch!='\t') {
return offset;
}
offset++;
}
return end;
}
private boolean isLineEnding(IDocument doc, String text) {
String[] delimiters = doc.getLegalLineDelimiters();
if (delimiters != null) {
return TextUtilities.endsWith(delimiters, text)!=-1;
}
return false;
}
}
|
package com.redhat.ceylon.eclipse.imp.editor;
import static com.redhat.ceylon.eclipse.imp.parser.CeylonSourcePositionLocator.getTokenIndexAtCharacter;
import static java.lang.Character.isWhitespace;
import static org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS;
import static org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
import org.antlr.runtime.CommonToken;
import org.eclipse.core.runtime.Platform;
import org.eclipse.imp.services.IAutoEditStrategy;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.eclipse.imp.parser.CeylonParseController;
public class CeylonAutoEditStrategy implements IAutoEditStrategy {
public void customizeDocumentCommand(IDocument doc, DocumentCommand cmd) {
//Note that IMP's Correct Indentation sends us a tab
//character at the start of each line of selected
//text. This is amazingly sucky because it's very
//difficult to distingush Correct Indentation from
//an actual typed tab.
//Note also that typed tabs are replaced with spaces
//before this method is called if the spacesfortabs
//setting is enabled.
if (cmd.doit == false) {
return;
}
//cmd.length>0 means we are replacing or deleting text
else if (cmd.text!=null && cmd.length==0) {
if (cmd.text.isEmpty()) {
//workaround for a really annoying bug where we
//get sent "" instead of "\t" or " " by IMP
//reconstruct what we would have been sent
//without the bug
if (getIndentWithSpaces()) {
int overhang = getPrefix(doc, cmd).length() % getIndentSpaces();
cmd.text = getDefaultIndent().substring(overhang);
}
else {
cmd.text = "\t";
}
smartIndentOnKeypress(doc, cmd);
}
else if (cmd.text.length()==1 && isLineEnding(doc, cmd.text)) {
//a typed newline
smartIndentAfterNewline(doc, cmd);
}
else if (cmd.text.length()==1 ||
//when spacesfortabs is enabled, we get
//sent spaces instead of a tab
getIndentWithSpaces() && isIndent(getPrefix(doc, cmd))) {
//anything that might represent a single
//keypress or a Correct Indentation
smartIndentOnKeypress(doc, cmd);
}
}
}
private String getPrefix(IDocument doc, DocumentCommand cmd) {
try {
int lineOffset = doc.getLineInformationOfOffset(cmd.offset).getOffset();
return doc.get(lineOffset, cmd.offset-lineOffset) + cmd.text;
}
catch (BadLocationException e) {
return cmd.text;
}
}
public boolean isIndent(String text) {
if (!text.isEmpty() &&
text.length() % getIndentSpaces()==0) {
for (char c: text.toCharArray()) {
if (c!=' ') return false;
}
return true;
}
else {
return false;
}
}
private void smartIndentAfterNewline(IDocument d, DocumentCommand c) {
if (c.offset==-1 || d.getLength()==0) {
return;
}
try {
//if (end > start) {
indentNewLine(d, c);
}
catch (BadLocationException bleid ) {
bleid.printStackTrace();
}
}
private void smartIndentOnKeypress(IDocument d, DocumentCommand c) {
if (c.offset==-1 || d.getLength()==0) {
return;
}
try {
adjustIndentOfCurrentLine(d, c);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
private boolean isStringOrCommentContinuation(int offset) {
IEditorPart editor = Util.getCurrentEditor();
if (editor instanceof CeylonEditor) {
CeylonParseController pc = ((CeylonEditor) editor).getParseController();
if (pc.getTokens()==null) return false;
int tokenIndex = getTokenIndexAtCharacter(pc.getTokens(), offset);
if (tokenIndex>=0) {
CommonToken token = pc.getTokens().get(tokenIndex);
return token!=null && (token.getType()==CeylonLexer.STRING_LITERAL ||
token.getType()==CeylonLexer.MULTI_COMMENT) &&
token.getStartIndex()<offset;
}
}
return false;
}
private int getStringIndent(int offset) {
IEditorPart editor = Util.getCurrentEditor();
if (editor instanceof CeylonEditor) {
CeylonParseController pc = ((CeylonEditor) editor).getParseController();
if (pc.getTokens()==null) return -1;
int tokenIndex = getTokenIndexAtCharacter(pc.getTokens(), offset);
if (tokenIndex>=0) {
CommonToken token = pc.getTokens().get(tokenIndex);
if (token!=null && token.getType()==CeylonLexer.STRING_LITERAL &&
token.getStartIndex()<offset) {
return token.getCharPositionInLine()+1;
}
}
}
return -1;
}
private void adjustIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
switch (c.text.charAt(0)) {
case '}':
reduceIndentOfCurrentLine(d, c);
break;
case '{':
case '\t':
if (isStringOrCommentContinuation(c.offset)) {
shiftToBeginningOfStringOrCommentContinuation(d, c);
}
else {
fixIndentOfCurrentLine(d, c);
}
break;
default:
//when spacesfortabs is enabled, we get sent spaces instead of a tab
if (getIndentWithSpaces() && isIndent(getPrefix(d, c))) {
if (isStringOrCommentContinuation(c.offset)) {
shiftToBeginningOfStringOrCommentContinuation(d, c);
}
else {
fixIndentOfCurrentLine(d, c);
}
}
}
}
private void shiftToBeginningOfStringOrCommentContinuation(IDocument d, DocumentCommand c)
throws BadLocationException {
//int start = getStartOfCurrentLine(d, c);
int end = getEndOfCurrentLine(d, c);
int loc = firstEndOfWhitespace(d, c.offset/*start*/, end);
if (loc>c.offset) {
c.length = 0;
c.text = "";
c.caretOffset = loc;
}
}
private void indentNewLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int stringIndent = getStringIndent(c.offset);
if (stringIndent>=0 && getIndentWithSpaces()) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<stringIndent; i++) {
sb.append(' ');
}
c.text = c.text + sb.toString();
}
else {
char lastNonWhitespaceChar = getPreviousNonWhitespaceCharacter(d, c.offset-1);
char endOfLastLineChar = getPreviousNonWhitespaceCharacterInLine(d, c.offset-1);
char startOfNewLineChar = getNextNonWhitespaceCharacterInLine(d, c.offset);
StringBuilder buf = new StringBuilder(c.text);
appendIndent(d, getStartOfCurrentLine(d, c), getEndOfCurrentLine(d, c),
startOfNewLineChar, endOfLastLineChar, lastNonWhitespaceChar,
false, buf);
c.text = buf.toString();
}
}
private void fixIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int start = getStartOfCurrentLine(d, c);
int end = getEndOfCurrentLine(d, c);
int endOfWs = firstEndOfWhitespace(d, start, end);
if (c.offset<endOfWs ||
c.offset==start && c.shiftsCaret==false) { //Test for IMP's "Correct Indent"
if (start==0) { //Start of file
c.text="";
c.offset=start;
c.length=0;
}
else {
int endOfPrev = getEndOfPreviousLine(d, c);
int startOfPrev = getStartOfPreviousLine(d, c);
char endOfLastLineChar = getLastNonWhitespaceCharacterInLine(d, startOfPrev, endOfPrev);
char lastNonWhitespaceChar = endOfLastLineChar=='\n' ?
getPreviousNonWhitespaceCharacter(d, startOfPrev) : endOfLastLineChar;
char startOfCurrentLineChar = c.text.equals("{") ? '{' : getNextNonWhitespaceCharacter(d, start);
boolean correctContinuation = endOfWs-start!=firstEndOfWhitespace(d, startOfPrev, endOfPrev)-startOfPrev; //TODO: improve this 'cos should check tabs vs spaces
StringBuilder buf = new StringBuilder();
appendIndent(d, startOfPrev, endOfPrev, startOfCurrentLineChar, endOfLastLineChar,
lastNonWhitespaceChar, correctContinuation, buf);
if (c.text.equals("{")) {
buf.append("{");
}
c.text = buf.toString();
c.offset=start;
c.length=endOfWs-start;
}
}
}
private void appendIndent(IDocument d, int startOfPrev, int endOfPrev,
char startOfCurrentLineChar, char endOfLastLineChar, char lastNonWhitespaceChar,
boolean correctContinuation, StringBuilder buf) throws BadLocationException {
boolean isContinuation = startOfCurrentLineChar!='{' && startOfCurrentLineChar!='}' &&
lastNonWhitespaceChar!=';' && lastNonWhitespaceChar!='}' && lastNonWhitespaceChar!='{';
boolean isOpening = endOfLastLineChar=='{' && startOfCurrentLineChar!='}';
boolean isClosing = startOfCurrentLineChar=='}' && lastNonWhitespaceChar!='{';
appendIndent(d, isContinuation, isOpening, isClosing, correctContinuation,
startOfPrev, endOfPrev, buf);
}
protected void reduceIndent(DocumentCommand c) {
int spaces = getIndentSpaces();
if (endsWithSpaces(c.text, spaces)) {
c.text = c.text.substring(0, c.text.length()-spaces);
}
else if (c.text.endsWith("\t")) {
c.text = c.text.substring(0, c.text.length()-1);
}
}
private void reduceIndentOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int spaces = getIndentSpaces();
if (endsWithSpaces(d.get(c.offset-spaces, spaces),spaces)) {
c.offset = c.offset-spaces;
c.length = spaces;
}
else if (d.get(c.offset-1,1).equals("\t")) {
c.offset = c.offset-1;
c.length = 1;
}
}
private void decrementIndent(StringBuilder buf, String indent)
throws BadLocationException {
int spaces = getIndentSpaces();
if (endsWithSpaces(indent,spaces)) {
buf.setLength(buf.length()-spaces);
}
else if (indent.endsWith("\t")) {
buf.setLength(buf.length()-1);
}
}
private int getStartOfPreviousLine(IDocument d, DocumentCommand c)
throws BadLocationException {
return getStartOfPreviousLine(d, c.offset);
}
private int getStartOfPreviousLine(IDocument d, int offset)
throws BadLocationException {
int os;
int line = d.getLineOfOffset(offset);
do {
os = d.getLineOffset(--line);
}
while (isStringOrCommentContinuation(os));
return os;
}
/*private int getStartOfNextLine(IDocument d, int offset)
throws BadLocationException {
return d.getLineOffset(d.getLineOfOffset(offset)+1);
}*/
private void appendIndent(IDocument d, boolean isContinuation, boolean isBeginning,
boolean isEnding, boolean correctContinuation, int start, int end,
StringBuilder buf) throws BadLocationException {
String indent = getIndent(d, start, end, isContinuation&&!correctContinuation);
if (!indent.isEmpty()) {
buf.append(indent);
if (isBeginning) {
//increment the indent level
incrementIndent(buf, indent);
}
else if (isContinuation&&correctContinuation) {
incrementIndent(buf, indent);
incrementIndent(buf, indent);
}
}
else {
if (isBeginning) {
initialIndent(buf);
}
else if (isContinuation&&correctContinuation) {
initialIndent(buf);
initialIndent(buf);
}
}
if (isEnding) {
decrementIndent(buf, indent);
if (isContinuation) decrementIndent(buf, indent);
}
}
private String getIndent(IDocument d, int start, int end, boolean isUncorrectedContinuation)
throws BadLocationException {
if (!isUncorrectedContinuation) while (true) {
//System.out.println(d.get(start, end-start));
if (start==0) {
return "";
}
else {
char ch1 = getNextNonWhitespaceCharacterInLine(d, start);
if (ch1=='}') break;
int startOfPrev = getStartOfPreviousLine(d, start);
int endOfPrev = getEndOfPreviousLine(d, start);
char ch = getLastNonWhitespaceCharacterInLine(d, startOfPrev, endOfPrev);
if (ch==';' || ch=='{' || ch=='}') break;
start = startOfPrev;
end = endOfPrev;
}
}
int endOfWs = firstEndOfWhitespace(d, start, end);
return d.get(start, endOfWs-start);
}
private char getLastNonWhitespaceCharacterInLine(IDocument d, int offset, int end)
throws BadLocationException {
char result = '\n'; //ahem, ugly null!
for (;offset<end; offset++) {
char ch = d.getChar(offset);
if (!isWhitespace(ch)) result=ch;
}
return result;
}
private void incrementIndent(StringBuilder buf, String indent) {
int spaces = getIndentSpaces();
if (indent.length()>=spaces &&
endsWithSpaces(indent,spaces)) {
for (int i=1; i<=spaces; i++) {
buf.append(' ');
}
}
else if (indent.length()>=0 &&
indent.charAt(indent.length()-1)=='\t') {
buf.append('\t');
}
}
private char getPreviousNonWhitespaceCharacter(IDocument d, int offset)
throws BadLocationException {
for (;offset>=0; offset
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0))) {
return ch.charAt(0);
}
}
return '\n';
}
private char getPreviousNonWhitespaceCharacterInLine(IDocument d, int offset)
throws BadLocationException {
for (;offset>=0; offset
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0)) ||
isLineEnding(d, ch)) {
return ch.charAt(0);
}
}
return '\n';
}
private char getNextNonWhitespaceCharacterInLine(IDocument d, int offset)
throws BadLocationException {
for (;offset<d.getLength(); offset++) {
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0)) ||
isLineEnding(d, ch)) {
return ch.charAt(0);
}
}
return '\n';
}
private char getNextNonWhitespaceCharacter(IDocument d, int offset)
throws BadLocationException {
for (;offset<d.getLength(); offset++) {
String ch = d.get(offset,1);
if (!isWhitespace(ch.charAt(0))) {
return ch.charAt(0);
}
}
return '\n';
}
private static void initialIndent(StringBuilder buf) {
//guess an initial indent level
if (getIndentWithSpaces()) {
int spaces = getIndentSpaces();
for (int i=1; i<=spaces; i++) {
buf.append(' ');
}
}
else {
buf.append('\t');
}
}
private int getStartOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int p = c.offset == d.getLength() ? c.offset-1 : c.offset;
return d.getLineInformationOfOffset(p).getOffset();
}
private int getEndOfCurrentLine(IDocument d, DocumentCommand c)
throws BadLocationException {
int p = c.offset == d.getLength() ? c.offset-1 : c.offset;
IRegion lineInfo = d.getLineInformationOfOffset(p);
return lineInfo.getOffset() + lineInfo.getLength();
}
private int getEndOfPreviousLine(IDocument d, DocumentCommand c)
throws BadLocationException {
return getEndOfPreviousLine(d, c.offset);
}
private int getEndOfPreviousLine(IDocument d, int offset)
throws BadLocationException {
int p = offset == d.getLength() ? offset-1 : offset;
IRegion lineInfo = d.getLineInformation(d.getLineOfOffset(p)-1);
return lineInfo.getOffset() + lineInfo.getLength();
}
private boolean endsWithSpaces(String string, int spaces) {
if (string.length()<spaces) return false;
for (int i=1; i<=spaces; i++) {
if (string.charAt(string.length()-i)!=' ') {
return false;
}
}
return true;
}
private static int getIndentSpaces() {
return Platform.getPreferencesService()
.getInt("org.eclipse.ui.editors", EDITOR_TAB_WIDTH, 4, null);
}
private static boolean getIndentWithSpaces() {
return Platform.getPreferencesService()
.getBoolean("org.eclipse.ui.editors", EDITOR_SPACES_FOR_TABS, false, null);
}
public static String getDefaultIndent() {
StringBuilder result = new StringBuilder();
initialIndent(result);
return result.toString();
}
/**
* Returns the first offset greater than <code>offset</code> and smaller than
* <code>end</code> whose character is not a space or tab character. If no such
* offset is found, <code>end</code> is returned.
*
* @param d the document to search in
* @param offset the offset at which searching start
* @param end the offset at which searching stops
* @return the offset in the specified range whose character is not a space or tab
* @exception BadLocationException if position is an invalid range in the given document
*/
private int firstEndOfWhitespace(IDocument d, int offset, int end)
throws BadLocationException {
while (offset < end) {
char ch= d.getChar(offset);
if (ch!=' ' && ch!='\t') {
return offset;
}
offset++;
}
return end;
}
private boolean isLineEnding(IDocument doc, String text) {
String[] delimiters = doc.getLegalLineDelimiters();
if (delimiters != null) {
return TextUtilities.endsWith(delimiters, text)!=-1;
}
return false;
}
}
|
package org.jkiss.dbeaver.model.impl.data.formatters;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.data.DBDDataFormatter;
import org.jkiss.utils.CommonUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.Map;
public class NumberDataFormatter implements DBDDataFormatter {
private DecimalFormat numberFormat;
private StringBuffer buffer;
private FieldPosition position;
@Override
public void init(Locale locale, Map<Object, Object> properties)
{
numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
Object useGrouping = properties.get(NumberFormatSample.PROP_USE_GROUPING);
if (useGrouping != null) {
numberFormat.setGroupingUsed(CommonUtils.toBoolean(useGrouping));
}
Object maxIntDigits = properties.get(NumberFormatSample.PROP_MAX_INT_DIGITS);
if (maxIntDigits != null) {
numberFormat.setMaximumIntegerDigits(CommonUtils.toInt(maxIntDigits));
}
Object minIntDigits = properties.get(NumberFormatSample.PROP_MIN_INT_DIGITS);
if (minIntDigits != null) {
numberFormat.setMinimumIntegerDigits(CommonUtils.toInt(minIntDigits));
}
Object maxFractDigits = properties.get(NumberFormatSample.PROP_MAX_FRACT_DIGITS);
if (maxFractDigits != null) {
numberFormat.setMaximumFractionDigits(CommonUtils.toInt(maxFractDigits));
}
Object minFractDigits = properties.get(NumberFormatSample.PROP_MIN_FRACT_DIGITS);
if (minFractDigits != null) {
numberFormat.setMinimumFractionDigits(CommonUtils.toInt(minFractDigits));
}
String roundingMode = CommonUtils.toString(properties.get(NumberFormatSample.PROP_ROUNDING_MODE));
if (!CommonUtils.isEmpty(roundingMode)) {
try {
numberFormat.setRoundingMode(RoundingMode.valueOf(roundingMode));
} catch (Exception e) {
// just skip it
}
}
buffer = new StringBuffer();
position = new FieldPosition(0);
}
@Nullable
@Override
public String getPattern()
{
return null;
}
@Nullable
@Override
public String formatValue(Object value)
{
if (value == null) {
return null;
}
try {
synchronized (this) {
buffer.setLength(0);
return numberFormat.format(value, buffer, position).toString();
}
} catch (Exception e) {
return value.toString();
}
}
@Override
public Object parseValue(String value, @Nullable Class<?> typeHint) throws ParseException
{
synchronized (this) {
numberFormat.setParseBigDecimal(typeHint == BigDecimal.class || typeHint == BigInteger.class);
Number number = numberFormat.parse(value);
if (number != null && typeHint != null) {
if (typeHint == Byte.class) {
return number.byteValue();
} else if (typeHint == Short.class) {
return number.shortValue();
} else if (typeHint == Integer.class) {
return number.intValue();
} else if (typeHint == Long.class) {
return number.longValue();
} else if (typeHint == Float.class) {
return number.floatValue();
} else if (typeHint == Double.class) {
return number.doubleValue();
}
}
return number;
}
}
}
|
package de.factoryfx.factory.datastorage.postgres;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import javax.sql.DataSource;
import de.factoryfx.factory.datastorage.*;
import de.factoryfx.factory.testfactories.ExampleFactoryA;
import de.factoryfx.factory.testfactories.ExampleLiveObjectA;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.postgresql.jdbc.AutoSave;
import org.postgresql.jdbc3.Jdbc3SimpleDataSource;
import ru.yandex.qatools.embed.postgresql.PostgresExecutable;
import ru.yandex.qatools.embed.postgresql.PostgresProcess;
import ru.yandex.qatools.embed.postgresql.PostgresStarter;
import ru.yandex.qatools.embed.postgresql.config.PostgresConfig;
public class PostgresFactoryStorageTest {
static PostgresProcess postgresProcess;
static DataSource postgresDatasource;
@BeforeClass
public static void setupPostgres() {
try {
PostgresStarter<PostgresExecutable, PostgresProcess> runtime = PostgresStarter.getDefaultInstance();
final PostgresConfig config = PostgresConfig.defaultWithDbName("test","testuser","testpw");
PostgresExecutable exec = runtime.prepare(config);
postgresProcess = exec.start();
Jdbc3SimpleDataSource _postgresDatasource = new Jdbc3SimpleDataSource();
_postgresDatasource.setServerName(config.net().host());
_postgresDatasource.setPortNumber(config.net().port());
_postgresDatasource.setDatabaseName(config.storage().dbName());
_postgresDatasource.setUser(config.credentials().username());
_postgresDatasource.setPassword(config.credentials().password());
_postgresDatasource.setAutosave(AutoSave.NEVER);
postgresDatasource = Mockito.spy(_postgresDatasource);
Mockito.when(postgresDatasource.getConnection()).thenAnswer(new Answer<Connection>() {
@Override
public Connection answer(InvocationOnMock invocation) throws Throwable {
Connection connection = _postgresDatasource.getConnection();
connection.setAutoCommit(false);
return connection;
}
});
} catch (IOException | SQLException e) {
throw new RuntimeException(e);
}
}
@AfterClass
public static void stopPostgres() {
postgresProcess.stop();
}
private FactorySerialisationManager<ExampleFactoryA> createSerialisation(){
int dataModelVersion = 1;
return new FactorySerialisationManager<>(new JacksonSerialisation<>(dataModelVersion),new JacksonDeSerialisation<>(ExampleFactoryA.class, dataModelVersion), Collections.emptyList(),1);
}
@Test
public void test_init_no_existing_factory() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource, new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
try (Connection con = postgresDatasource.getConnection()) {
for (String sql : Arrays.asList("select * from currentconfiguration"
,"select * from configurationmetadata"
,"select * from configuration")) {
PreparedStatement pstmt = con.prepareStatement(sql);
try (ResultSet rs = pstmt.executeQuery()) {
Assert.assertTrue(rs.next());
}
}
}
}
@Test
public void test_init_no_existing_factory_but_schema() throws SQLException, IOException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource, new ExampleFactoryA(),createSerialisation());
try (Connection con = postgresDatasource.getConnection()) {
postgresFactoryStorage.createTables(con);
con.commit();
}
postgresFactoryStorage.loadInitialFactory();
try (Connection con = postgresDatasource.getConnection()) {
for (String sql : Arrays.asList("select * from currentconfiguration"
,"select * from configurationmetadata"
,"select * from configuration")) {
PreparedStatement pstmt = con.prepareStatement(sql);
try (ResultSet rs = pstmt.executeQuery()) {
Assert.assertTrue(rs.next());
}
}
}
}
@Test
public void test_init_existing_factory() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource, new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
String id=postgresFactoryStorage.getCurrentFactory().metadata.id;
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> restored = new PostgresFactoryStorage<>(postgresDatasource, null,createSerialisation());
restored.loadInitialFactory();
Assert.assertEquals(id,restored.getCurrentFactory().metadata.id);
}
@Test
public void test_update() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource, new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
String id=postgresFactoryStorage.getCurrentFactory().metadata.id;
FactoryAndNewMetadata<ExampleFactoryA> update = new FactoryAndNewMetadata<>(new ExampleFactoryA(),new NewFactoryMetadata());
postgresFactoryStorage.updateCurrentFactory(update,"","");
Assert.assertNotEquals(id,postgresFactoryStorage.getCurrentFactory().metadata.id);
Assert.assertEquals(2,postgresFactoryStorage.getHistoryFactoryList().size());
Assert.assertEquals(id,new ArrayList<>(postgresFactoryStorage.getHistoryFactoryList()).get(0).id);
}
@Before
public void truncate() throws SQLException {
try (Connection con = postgresDatasource.getConnection()) {
for (String sql : Arrays.asList("drop table currentconfiguration"
,"drop table configurationmetadata"
,"drop table futureconfigurationmetadata"
,"drop table futureconfiguration"
,"drop table configuration")) {
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.execute();
}
con.commit();
} catch (SQLException ignored) {//non-existent upon first call
}
}
@Test
public void test_initial_history() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource,new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
Assert.assertEquals(1,postgresFactoryStorage.getHistoryFactoryList().size());
}
@Test
public void test_multi_add() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource,new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
{
NewFactoryMetadata metadata = new NewFactoryMetadata();
postgresFactoryStorage.updateCurrentFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","");
}
{
NewFactoryMetadata metadata = new NewFactoryMetadata();
postgresFactoryStorage.updateCurrentFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","");
}
{
NewFactoryMetadata metadata = new NewFactoryMetadata();
postgresFactoryStorage.updateCurrentFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","");
}
Assert.assertEquals(4,postgresFactoryStorage.getHistoryFactoryList().size());
}
@Test
public void test_restore() throws SQLException {
PostgresFactoryStorage<Void, ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource,new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
NewFactoryMetadata metadata = new NewFactoryMetadata();
postgresFactoryStorage.updateCurrentFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","");
Assert.assertEquals(2,postgresFactoryStorage.getHistoryFactoryList().size());
PostgresFactoryStorage<Void, ExampleLiveObjectA, ExampleFactoryA> restored = new PostgresFactoryStorage<>(postgresDatasource,new ExampleFactoryA(), createSerialisation());
restored.loadInitialFactory();
Assert.assertEquals(2,restored.getHistoryFactoryList().size());
}
@Test
public void test_future() throws SQLException {
PostgresFactoryStorage<Void,ExampleLiveObjectA, ExampleFactoryA> postgresFactoryStorage = new PostgresFactoryStorage<>(postgresDatasource,new ExampleFactoryA(),createSerialisation());
postgresFactoryStorage.loadInitialFactory();
{
NewFactoryMetadata metadata = new NewFactoryMetadata();
postgresFactoryStorage.addFutureFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","", LocalDateTime.now());
Collection<ScheduledFactoryMetadata> list = postgresFactoryStorage.getFutureFactoryList();
Assert.assertEquals(1,list.size());
String id = list.iterator().next().id;
ExampleFactoryA v = postgresFactoryStorage.getFutureFactory(id);
Assert.assertEquals(id,v.getId());
metadata = new NewFactoryMetadata();
postgresFactoryStorage.addFutureFactory(new FactoryAndNewMetadata<>(new ExampleFactoryA(),metadata),"","", LocalDateTime.now());
list = postgresFactoryStorage.getFutureFactoryList();
Assert.assertEquals(2,list.size());
postgresFactoryStorage.deleteFutureFactory(list.iterator().next().id);
list = postgresFactoryStorage.getFutureFactoryList();
Assert.assertEquals(1,list.size());
}
}
}
|
package org.springframework.roo.process.manager.internal;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.startlevel.StartLevel;
import org.springframework.roo.file.monitor.FileMonitorService;
import org.springframework.roo.file.monitor.MonitoringRequest;
import org.springframework.roo.file.monitor.NotifiableFileMonitorService;
import org.springframework.roo.file.undo.UndoManager;
import org.springframework.roo.process.manager.ActiveProcessManager;
import org.springframework.roo.process.manager.CommandCallback;
import org.springframework.roo.process.manager.ProcessManager;
import org.springframework.roo.process.manager.event.AbstractProcessManagerStatusPublisher;
import org.springframework.roo.process.manager.event.ProcessManagerStatus;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.ExceptionUtils;
/**
* Default implementation of {@link ProcessManager} interface.
*
* @author Ben Alex
* @since 1.0
*
*/
@Component(immediate=true)
@Service
public class DefaultProcessManager extends AbstractProcessManagerStatusPublisher implements ProcessManager {
private static final Logger logger = HandlerUtils.getLogger(DefaultProcessManager.class);
@Reference private UndoManager undoManager;
@Reference private FileMonitorService fileMonitorService;
@Reference private StartLevel startLevel;
private Timer t = new Timer(true);
private boolean developmentMode = false;
private long minimumDelayBetweenPoll = -1; // how many ms must pass at minimum between each poll (negative denotes auto-scaling; 0 = never)
private long lastPollTime = 0; // what time the last poll was completed
private long lastPollDuration = 0; // how many ms the last poll actually took
private String workingDir = null; // the working directory of the current roo project
protected void activate(ComponentContext context) {
// obtain the working directory from the framework properties
// TODO CD move constant to proper location
workingDir = context.getBundleContext().getProperty("roo.working.directory");
context.getBundleContext().addFrameworkListener(new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() == FrameworkEvent.STARTLEVEL_CHANGED) {
if (startLevel.getStartLevel() >= 99) {
if (getProcessManagerStatus().equals(ProcessManagerStatus.STARTING)) {
completeStartup();
} else {
}
}
}
}
});
// Now start a thread that will undertake a background poll every second
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (getProcessManagerStatus() == ProcessManagerStatus.AVAILABLE) {
timerBasedPoll();
}
}
}, 0, 1000);
}
protected void deactivate(ComponentContext context) {
// We have lost a required component (eg UndoManager; ROO-1037)
synchronized (processManagerStatus) {
// Do the check again, now this thread has a lock on processManagerStatus
if (getProcessManagerStatus() != ProcessManagerStatus.AVAILABLE) {
// We have the lock on processManagerStatus, yet it's not available; this would be odd
logger.warning("Unexpected status " + getProcessManagerStatus() + " without lock");
}
t.cancel();
}
}
public void completeStartup() {
// Quick sanity check that we're being called at the correct time; we don't need to get a synchronization lock if the method shouldn't even run
Assert.isTrue(getProcessManagerStatus() == ProcessManagerStatus.STARTING, "Process manager must have a status of STARTING to complete startup");
synchronized (processManagerStatus) {
try {
// Register the initial monitoring request
doTransactionally(new MonitoringRequestCommand(fileMonitorService, MonitoringRequest.getInitialMonitoringRequest(workingDir), true));
} catch (Throwable t) {
logException(t);
} finally {
setProcessManagerStatus(ProcessManagerStatus.AVAILABLE);
}
}
}
public boolean backgroundPoll() {
// Quickly determine if another thread is running; we don't need to sit around and wait (we'll get called again in a few hundred milliseconds anyway)
if (getProcessManagerStatus() != ProcessManagerStatus.AVAILABLE) {
return false;
}
synchronized (processManagerStatus) {
// Do the check again, now this thread has a lock on processManagerStatus
if (getProcessManagerStatus() != ProcessManagerStatus.AVAILABLE) {
throw new IllegalStateException("Process manager status " + getProcessManagerStatus() + " but background thread acquired synchronization lock");
}
setProcessManagerStatus(ProcessManagerStatus.BUSY_POLLING);
try {
doTransactionally(null);
} catch (Throwable t) {
// We don't want a poll failure to cause the background polling thread to die
logException(t);
} finally {
setProcessManagerStatus(ProcessManagerStatus.AVAILABLE);
}
}
return true;
}
public <T> T execute(CommandCallback<T> callback) {
Assert.notNull(callback, "Callback required");
synchronized (processManagerStatus) {
// For us to acquire this lock means no other thread has hold of process manager status
Assert.isTrue(getProcessManagerStatus() == ProcessManagerStatus.AVAILABLE || getProcessManagerStatus() == ProcessManagerStatus.BUSY_EXECUTING, "Unable to execute as another thread has set status to " + getProcessManagerStatus());
setProcessManagerStatus(ProcessManagerStatus.BUSY_EXECUTING);
try {
return doTransactionally(callback);
} catch (RuntimeException ex) {
logException(ex);
throw ex;
} finally {
setProcessManagerStatus(ProcessManagerStatus.AVAILABLE);
}
}
}
private void logException(Throwable ex) {
Throwable root = ExceptionUtils.extractRootCause(ex);
if (developmentMode) {
logger.log(Level.FINE, root.getMessage(), root);
} else {
String message = root.getMessage();
if (message == null || "".equals(message)) {
StackTraceElement[] trace = root.getStackTrace();
if (trace != null && trace.length > 0) {
message = root.getClass().getSimpleName() + " at " + trace[0].toString();
} else {
message = root.getClass().getSimpleName();
}
}
logger.log(Level.FINE, message);
}
}
private <T> T doTransactionally(CommandCallback<T> callback) {
T result = null;
try {
ActiveProcessManager.setActiveProcessManager(this);
// run the requested operation
if (callback == null) {
fileMonitorService.scanAll();
} else {
result = callback.callback();
}
// guarantee scans repeat until there are no more changes detected
while (fileMonitorService.isDirty()) {
if (fileMonitorService instanceof NotifiableFileMonitorService) {
((NotifiableFileMonitorService)fileMonitorService).scanNotified();
} else {
fileMonitorService.scanAll();
}
}
// it all seems to have worked, so clear the undo history
setProcessManagerStatus(ProcessManagerStatus.RESETTING_UNDOS);
undoManager.reset();
} catch (RuntimeException rt) {
// Something went wrong, so attempt to undo
try {
setProcessManagerStatus(ProcessManagerStatus.UNDOING);
throw rt;
} finally {
undoManager.undo();
}
} finally {
// TODO: Review in consultation with Christian as STS is clearing active process manager itself
//ActiveProcessManager.clearActiveProcessManager();
}
return result;
}
public void timerBasedPoll() {
try {
if (minimumDelayBetweenPoll == 0) {
// Manual polling only, we never allow the timer to kick of a poll
return;
}
long effectiveMinimumDelayBetweenPoll = minimumDelayBetweenPoll;
if (effectiveMinimumDelayBetweenPoll < 0) {
// A negative minimum delay between poll means auto-scaling is used
if (lastPollDuration < 500) {
// We've never done a poll, or they are very fast
effectiveMinimumDelayBetweenPoll = 0;
} else {
// Use the last duration (we might make this sliding scale in the future)
effectiveMinimumDelayBetweenPoll = lastPollDuration;
}
}
long started = System.currentTimeMillis();
if (started < lastPollTime + effectiveMinimumDelayBetweenPoll) {
// Too soon to re-poll
return;
}
backgroundPoll();
// record the completion time so we can ensure we don't re-poll too soon
lastPollTime = System.currentTimeMillis();
// compute how many milliseconds it took to run
lastPollDuration = lastPollTime - started;
if (lastPollDuration == 0) {
lastPollDuration = 1; // ensure it correctly reflects that it has ever run
}
} catch (Throwable t) {
logger.log(Level.SEVERE, t.getMessage(), t);
}
}
public boolean isDevelopmentMode() {
return developmentMode;
}
public void setDevelopmentMode(boolean developmentMode) {
this.developmentMode = developmentMode;
}
/**
* @param minimumDelayBetweenPoll how many milliseconds must pass between each poll
*/
public void setMinimumDelayBetweenPoll(long minimumDelayBetweenPoll) {
this.minimumDelayBetweenPoll = minimumDelayBetweenPoll;
}
/**
* @return how many milliseconds must pass between each poll (0 = manual only; <0 = auto-scaled; >0 = interval)
*/
public long getMinimumDelayBetweenPoll() {
return minimumDelayBetweenPoll;
}
/**
* @return how many milliseconds the last poll execution took to complete (0 = never ran; >0 = last execution time)
*/
public long getLastPollDuration() {
return lastPollDuration;
}
}
|
package com.opengamma.integration.viewer.status.impl;
import java.util.Map;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBean;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.integration.viewer.status.ViewStatusKey;
import com.opengamma.util.ArgumentChecker;
@BeanDefinition
public class ViewStatusKeyBean extends DirectBean implements ViewStatusKey {
@PropertyDefinition(validate = "notNull")
private String _securityType;
@PropertyDefinition(validate = "notNull")
private String _valueRequirementName;
@PropertyDefinition(validate = "notNull")
private String _currency;
@PropertyDefinition(validate = "notNull")
private String _targetType;
/**
* Creates an instance
*
* @param securityType the security type, not-null.
* @param valueRequirementName the value name, not-null.
* @param currency the currency, not-null.
* @param targetType the target type, not-null.
*/
public ViewStatusKeyBean(String securityType, String valueRequirementName, String currency, String targetType) {
ArgumentChecker.notNull(securityType, "securityType");
ArgumentChecker.notNull(valueRequirementName, "valueRequirementName");
ArgumentChecker.notNull(currency, "currency");
ArgumentChecker.notNull(targetType, "targetType");
setSecurityType(securityType);
setValueRequirementName(valueRequirementName);
setCurrency(currency);
setTargetType(targetType);
}
/**
* Constructor for builder
*/
ViewStatusKeyBean() {
}
///CLOVER:OFF
/**
* The meta-bean for {@code ViewStatusKeyBean}.
* @return the meta-bean, not null
*/
public static ViewStatusKeyBean.Meta meta() {
return ViewStatusKeyBean.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(ViewStatusKeyBean.Meta.INSTANCE);
}
@Override
public ViewStatusKeyBean.Meta metaBean() {
return ViewStatusKeyBean.Meta.INSTANCE;
}
@Override
protected Object propertyGet(String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 808245914: // securityType
return getSecurityType();
case 1646585789: // valueRequirementName
return getValueRequirementName();
case 575402001: // currency
return getCurrency();
case 486622315: // targetType
return getTargetType();
}
return super.propertyGet(propertyName, quiet);
}
@Override
protected void propertySet(String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case 808245914: // securityType
setSecurityType((String) newValue);
return;
case 1646585789: // valueRequirementName
setValueRequirementName((String) newValue);
return;
case 575402001: // currency
setCurrency((String) newValue);
return;
case 486622315: // targetType
setTargetType((String) newValue);
return;
}
super.propertySet(propertyName, newValue, quiet);
}
@Override
protected void validate() {
JodaBeanUtils.notNull(_securityType, "securityType");
JodaBeanUtils.notNull(_valueRequirementName, "valueRequirementName");
JodaBeanUtils.notNull(_currency, "currency");
JodaBeanUtils.notNull(_targetType, "targetType");
super.validate();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
ViewStatusKeyBean other = (ViewStatusKeyBean) obj;
return JodaBeanUtils.equal(getSecurityType(), other.getSecurityType()) &&
JodaBeanUtils.equal(getValueRequirementName(), other.getValueRequirementName()) &&
JodaBeanUtils.equal(getCurrency(), other.getCurrency()) &&
JodaBeanUtils.equal(getTargetType(), other.getTargetType());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash += hash * 31 + JodaBeanUtils.hashCode(getSecurityType());
hash += hash * 31 + JodaBeanUtils.hashCode(getValueRequirementName());
hash += hash * 31 + JodaBeanUtils.hashCode(getCurrency());
hash += hash * 31 + JodaBeanUtils.hashCode(getTargetType());
return hash;
}
/**
* Gets the securityType.
* @return the value of the property, not null
*/
public String getSecurityType() {
return _securityType;
}
/**
* Sets the securityType.
* @param securityType the new value of the property, not null
*/
public void setSecurityType(String securityType) {
JodaBeanUtils.notNull(securityType, "securityType");
this._securityType = securityType;
}
/**
* Gets the the {@code securityType} property.
* @return the property, not null
*/
public final Property<String> securityType() {
return metaBean().securityType().createProperty(this);
}
/**
* Gets the valueRequirementName.
* @return the value of the property, not null
*/
public String getValueRequirementName() {
return _valueRequirementName;
}
/**
* Sets the valueRequirementName.
* @param valueRequirementName the new value of the property, not null
*/
public void setValueRequirementName(String valueRequirementName) {
JodaBeanUtils.notNull(valueRequirementName, "valueRequirementName");
this._valueRequirementName = valueRequirementName;
}
/**
* Gets the the {@code valueRequirementName} property.
* @return the property, not null
*/
public final Property<String> valueRequirementName() {
return metaBean().valueRequirementName().createProperty(this);
}
/**
* Gets the currency.
* @return the value of the property, not null
*/
public String getCurrency() {
return _currency;
}
/**
* Sets the currency.
* @param currency the new value of the property, not null
*/
public void setCurrency(String currency) {
JodaBeanUtils.notNull(currency, "currency");
this._currency = currency;
}
/**
* Gets the the {@code currency} property.
* @return the property, not null
*/
public final Property<String> currency() {
return metaBean().currency().createProperty(this);
}
/**
* Gets the targetType.
* @return the value of the property, not null
*/
public String getTargetType() {
return _targetType;
}
/**
* Sets the targetType.
* @param targetType the new value of the property, not null
*/
public void setTargetType(String targetType) {
JodaBeanUtils.notNull(targetType, "targetType");
this._targetType = targetType;
}
/**
* Gets the the {@code targetType} property.
* @return the property, not null
*/
public final Property<String> targetType() {
return metaBean().targetType().createProperty(this);
}
/**
* The meta-bean for {@code ViewStatusKeyBean}.
*/
public static class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code securityType} property.
*/
private final MetaProperty<String> _securityType = DirectMetaProperty.ofReadWrite(
this, "securityType", ViewStatusKeyBean.class, String.class);
/**
* The meta-property for the {@code valueRequirementName} property.
*/
private final MetaProperty<String> _valueRequirementName = DirectMetaProperty.ofReadWrite(
this, "valueRequirementName", ViewStatusKeyBean.class, String.class);
/**
* The meta-property for the {@code currency} property.
*/
private final MetaProperty<String> _currency = DirectMetaProperty.ofReadWrite(
this, "currency", ViewStatusKeyBean.class, String.class);
/**
* The meta-property for the {@code targetType} property.
*/
private final MetaProperty<String> _targetType = DirectMetaProperty.ofReadWrite(
this, "targetType", ViewStatusKeyBean.class, String.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"securityType",
"valueRequirementName",
"currency",
"targetType");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 808245914: // securityType
return _securityType;
case 1646585789: // valueRequirementName
return _valueRequirementName;
case 575402001: // currency
return _currency;
case 486622315: // targetType
return _targetType;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends ViewStatusKeyBean> builder() {
return new DirectBeanBuilder<ViewStatusKeyBean>(new ViewStatusKeyBean());
}
@Override
public Class<? extends ViewStatusKeyBean> beanType() {
return ViewStatusKeyBean.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
/**
* The meta-property for the {@code securityType} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> securityType() {
return _securityType;
}
/**
* The meta-property for the {@code valueRequirementName} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> valueRequirementName() {
return _valueRequirementName;
}
/**
* The meta-property for the {@code currency} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> currency() {
return _currency;
}
/**
* The meta-property for the {@code targetType} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> targetType() {
return _targetType;
}
}
///CLOVER:ON
}
|
package com.ctrip.xpipe.redis.meta.server.keeper.manager;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import com.ctrip.xpipe.api.lifecycle.TopElement;
import com.ctrip.xpipe.redis.core.entity.ClusterMeta;
import com.ctrip.xpipe.redis.core.entity.KeeperMeta;
import com.ctrip.xpipe.redis.core.entity.KeeperTransMeta;
import com.ctrip.xpipe.redis.core.entity.Redis;
import com.ctrip.xpipe.redis.core.entity.ShardMeta;
import com.ctrip.xpipe.redis.core.meta.MetaComparator;
import com.ctrip.xpipe.redis.core.meta.MetaComparatorVisitor;
import com.ctrip.xpipe.redis.core.meta.comparator.ClusterMetaComparator;
import com.ctrip.xpipe.redis.core.meta.comparator.ShardMetaComparator;
import com.ctrip.xpipe.redis.meta.server.keeper.KeeperManager;
import com.ctrip.xpipe.redis.meta.server.keeper.KeeperStateController;
import com.ctrip.xpipe.redis.meta.server.keeper.impl.AbstractCurrentMetaObserver;
import com.ctrip.xpipe.utils.ObjectUtils;
import com.ctrip.xpipe.utils.XpipeThreadFactory;
/**
* @author wenchao.meng
*
* Sep 4, 2016
*/
@Component
public class DefaultKeeperManager extends AbstractCurrentMetaObserver implements KeeperManager, TopElement {
private int deadKeeperCheckIntervalMilli = Integer
.parseInt(System.getProperty("deadKeeperCheckIntervalMilli", "15000"));
@Autowired
private KeeperStateController keeperStateController;
private ScheduledExecutorService scheduled;
private ScheduledFuture<?> deadCheckFuture;
@Override
protected void doInitialize() throws Exception {
super.doInitialize();
scheduled = Executors.newScheduledThreadPool(2,
XpipeThreadFactory.create(String.format("KEEPER_MANAGER(%d)", currentClusterServer.getServerId())));
}
@Override
protected void doStart() throws Exception {
super.doStart();
deadCheckFuture = scheduled.scheduleWithFixedDelay(new DeadKeeperChecker(), deadKeeperCheckIntervalMilli,
deadKeeperCheckIntervalMilli, TimeUnit.MILLISECONDS);
}
@Override
protected void doStop() throws Exception {
super.doStop();
deadCheckFuture.cancel(true);
}
@Override
protected void doDispose() throws Exception {
scheduled.shutdownNow();
super.doDispose();
}
@Override
protected void handleClusterModified(ClusterMetaComparator comparator) {
String clusterId = comparator.getCurrent().getId();
comparator.accept(new ClusterComparatorVisitor(clusterId));
}
@Override
protected void handleClusterDeleted(ClusterMeta clusterMeta) {
for (ShardMeta shardMeta : clusterMeta.getShards().values()) {
for (KeeperMeta keeperMeta : shardMeta.getKeepers()) {
removeKeeper(clusterMeta.getId(), shardMeta.getId(), keeperMeta);
}
}
}
private void removeKeeper(String clusterId, String shardId, KeeperMeta keeperMeta) {
try {
keeperStateController.removeKeeper(new KeeperTransMeta(clusterId, shardId, keeperMeta));
} catch (Exception e) {
logger.error(String.format("[removeKeeper]%s:%s,%s", clusterId, shardId, keeperMeta), e);
}
}
private void addKeeper(String clusterId, String shardId, KeeperMeta keeperMeta) {
try {
keeperStateController.addKeeper(new KeeperTransMeta(clusterId, shardId, keeperMeta));
} catch (Exception e) {
logger.error(String.format("[addKeeper]%s:%s,%s", clusterId, shardId, keeperMeta), e);
}
}
@Override
protected void handleClusterAdd(ClusterMeta clusterMeta) {
for (ShardMeta shardMeta : clusterMeta.getShards().values()) {
for (KeeperMeta keeperMeta : shardMeta.getKeepers()) {
addKeeper(clusterMeta.getId(), shardMeta.getId(), keeperMeta);
}
}
}
protected List<KeeperMeta> getDeadKeepers(List<KeeperMeta> allKeepers, List<KeeperMeta> aliveKeepers) {
List<KeeperMeta> result = new LinkedList<>();
for (KeeperMeta allOne : allKeepers) {
boolean alive = false;
for (KeeperMeta aliveOne : aliveKeepers) {
if (ObjectUtils.equals(aliveOne.getIp(), allOne.getIp())
&& ObjectUtils.equals(aliveOne.getPort(), allOne.getPort())) {
alive = true;
break;
}
}
if (!alive) {
result.add(allOne);
}
}
return result;
}
public class DeadKeeperChecker implements Runnable {
@Override
public void run() {
try {
doCheck();
} catch (Throwable th) {
logger.error("[run]", th);
}
}
private void doCheck() {
for (String clusterId : currentMetaManager.allClusters()) {
ClusterMeta clusterMeta = currentMetaManager.getClusterMeta(clusterId);
for (ShardMeta shardMeta : clusterMeta.getShards().values()) {
String shardId = shardMeta.getId();
List<KeeperMeta> allKeepers = shardMeta.getKeepers();
List<KeeperMeta> aliveKeepers = currentMetaManager.getSurviveKeepers(clusterId, shardId);
List<KeeperMeta> deadKeepers = getDeadKeepers(allKeepers, aliveKeepers);
if (deadKeepers.size() > 0) {
logger.info("[doCheck][dead keepers]{}", deadKeepers);
}
for (KeeperMeta deadKeeper : deadKeepers) {
try {
keeperStateController.addKeeper(new KeeperTransMeta(clusterId, shardId, deadKeeper));
} catch (ResourceAccessException e) {
logger.error(String.format("cluster:%s,shard:%s, keeper:%s, error:%s", clusterId, shardId,
deadKeeper, e.getMessage()));
} catch (Throwable th) {
logger.error("[doCheck]", th);
}
}
}
}
}
}
protected class ClusterComparatorVisitor implements MetaComparatorVisitor<ShardMeta> {
private String clusterId;
public ClusterComparatorVisitor(String clusterId) {
this.clusterId = clusterId;
}
@Override
public void visitAdded(ShardMeta added) {
logger.info("[visitAdded][add shard]{}", added);
for (KeeperMeta keeperMeta : added.getKeepers()) {
addKeeper(clusterId, added.getId(), keeperMeta);
}
}
@Override
public void visitModified(@SuppressWarnings("rawtypes") MetaComparator comparator) {
ShardMetaComparator shardMetaComparator = (ShardMetaComparator) comparator;
shardMetaComparator.accept(new ShardComparatorVisitor(clusterId, shardMetaComparator.getCurrent().getId()));
}
@Override
public void visitRemoved(ShardMeta removed) {
logger.info("[visitRemoved][remove shard]{}", removed);
for (KeeperMeta keeperMeta : removed.getKeepers()) {
removeKeeper(clusterId, removed.getId(), keeperMeta);
}
}
}
protected class ShardComparatorVisitor implements MetaComparatorVisitor<Redis> {
private String clusterId;
private String shardId;
protected ShardComparatorVisitor(String clusterId, String shardId) {
this.clusterId = clusterId;
this.shardId = shardId;
}
@Override
public void visitAdded(Redis added) {
if (added instanceof KeeperMeta) {
addKeeper(clusterId, shardId, (KeeperMeta) added);
} else {
logger.debug("[visitAdded][do nothng]{}", added);
}
}
@SuppressWarnings("rawtypes")
@Override
public void visitModified(MetaComparator comparator) {
// nothing to do
}
@Override
public void visitRemoved(Redis removed) {
if (removed instanceof KeeperMeta) {
removeKeeper(clusterId, shardId, (KeeperMeta) removed);
} else {
logger.debug("[visitAdded][do nothng]{}", removed);
}
}
}
}
|
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.SystemClock;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperation;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.CharacteristicReadOperation;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.CharacteristicWriteOperation;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.DescriptorWriteOperation;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton
public class RileyLinkBLE {
@Inject AAPSLogger aapsLogger;
@Inject RileyLinkServiceData rileyLinkServiceData;
@Inject RileyLinkUtil rileyLinkUtil;
@Inject SP sp;
private final Context context;
private final boolean gattDebugEnabled = true;
private boolean manualDisconnect = false;
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothGattCallback bluetoothGattCallback;
private BluetoothDevice rileyLinkDevice;
private BluetoothGatt bluetoothConnectionGatt = null;
private BLECommOperation mCurrentOperation;
private final Semaphore gattOperationSema = new Semaphore(1, true);
private Runnable radioResponseCountNotified;
private boolean mIsConnected = false;
@Inject
public RileyLinkBLE(final Context context) {
this.context = context;
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onCharacteristicChanged(final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
if (gattDebugEnabled) {
aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicChanged "
+ GattAttributes.lookup(characteristic.getUuid()) + " "
+ ByteUtil.getHex(characteristic.getValue()));
if (characteristic.getUuid().equals(UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT))) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Response Count is " + ByteUtil.shortHexString(characteristic.getValue()));
}
}
if (radioResponseCountNotified != null) {
radioResponseCountNotified.run();
}
}
@Override
public void onCharacteristicRead(final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
final String statusMessage = getGattStatusMessage(status);
if (gattDebugEnabled) {
aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicRead ("
+ GattAttributes.lookup(characteristic.getUuid()) + ") " + statusMessage + ":"
+ ByteUtil.getHex(characteristic.getValue()));
}
mCurrentOperation.gattOperationCompletionCallback(characteristic.getUuid(), characteristic.getValue());
}
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
final String uuidString = GattAttributes.lookup(characteristic.getUuid());
if (gattDebugEnabled) {
aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " "
+ uuidString + " " + ByteUtil.shortHexString(characteristic.getValue()));
}
mCurrentOperation.gattOperationCompletionCallback(characteristic.getUuid(), characteristic.getValue());
}
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
super.onConnectionStateChange(gatt, status, newState);
// https://github.com/NordicSemiconductor/puck-central-android/blob/master/PuckCentral/app/src/main/java/no/nordicsemi/puckcentral/bluetooth/gatt/GattManager.java#L117
if (status == 133) {
aapsLogger.error(LTag.PUMPBTCOMM, "Got the status 133 bug, closing gatt");
disconnect();
SystemClock.sleep(500);
return;
}
if (gattDebugEnabled) {
final String stateMessage;
if (newState == BluetoothProfile.STATE_CONNECTED) {
stateMessage = "CONNECTED";
} else if (newState == BluetoothProfile.STATE_CONNECTING) {
stateMessage = "CONNECTING";
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
stateMessage = "DISCONNECTED";
} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
stateMessage = "DISCONNECTING";
} else {
stateMessage = "UNKNOWN newState (" + newState + ")";
}
aapsLogger.warn(LTag.PUMPBTCOMM, "onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage);
}
if (newState == BluetoothProfile.STATE_CONNECTED) {
if (status == BluetoothGatt.GATT_SUCCESS) {
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected, context);
} else {
aapsLogger.debug(LTag.PUMPBTCOMM, "BT State connected, GATT status {} ({})", status, getGattStatusMessage(status));
}
} else if ((newState == BluetoothProfile.STATE_CONNECTING) ||
(newState == BluetoothProfile.STATE_DISCONNECTING)) {
aapsLogger.debug(LTag.PUMPBTCOMM, "We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" :
"Disconnecting");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected, context);
if (manualDisconnect)
close();
aapsLogger.warn(LTag.PUMPBTCOMM, "RileyLink Disconnected.");
} else {
aapsLogger.warn(LTag.PUMPBTCOMM, "Some other state: (status={},newState={})", status, newState);
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " "
+ getGattStatusMessage(status) + " written: " + ByteUtil.getHex(descriptor.getValue()));
}
mCurrentOperation.gattOperationCompletionCallback(descriptor.getUuid(), descriptor.getValue());
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
mCurrentOperation.gattOperationCompletionCallback(descriptor.getUuid(), descriptor.getValue());
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onDescriptorRead " + getGattStatusMessage(status) + " status " + descriptor);
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onMtuChanged " + mtu + " status " + status);
}
}
@Override
public void onReadRemoteRssi(final BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onReadRemoteRssi " + getGattStatusMessage(status) + ": " + rssi);
}
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onReliableWriteCompleted status " + status);
}
}
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
final List<BluetoothGattService> services = gatt.getServices();
boolean rileyLinkFound = false;
for (BluetoothGattService service : services) {
final UUID uuidService = service.getUuid();
if (isAnyRileyLinkServiceFound(service)) {
rileyLinkFound = true;
}
if (gattDebugEnabled) {
debugService(service, 0);
}
}
if (gattDebugEnabled) {
aapsLogger.warn(LTag.PUMPBTCOMM, "onServicesDiscovered " + getGattStatusMessage(status));
}
aapsLogger.info(LTag.PUMPBTCOMM, "Gatt device is RileyLink device: " + rileyLinkFound);
if (rileyLinkFound) {
mIsConnected = true;
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady, context);
} else {
mIsConnected = false;
rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkError,
RileyLinkError.DeviceIsNotRileyLink);
}
} else {
aapsLogger.debug(LTag.PUMPBTCOMM, "onServicesDiscovered " + getGattStatusMessage(status));
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed, context);
}
}
};
}
@Inject
public void onInit() {
aapsLogger.debug(LTag.PUMPBTCOMM, "BT Adapter: " + this.bluetoothAdapter);
}
private boolean isAnyRileyLinkServiceFound(BluetoothGattService service) {
boolean found = GattAttributes.isRileyLink(service.getUuid());
if (found) {
return true;
} else {
List<BluetoothGattService> includedServices = service.getIncludedServices();
for (BluetoothGattService serviceI : includedServices) {
if (isAnyRileyLinkServiceFound(serviceI)) {
return true;
}
}
}
return false;
}
public BluetoothDevice getRileyLinkDevice() {
return this.rileyLinkDevice;
}
public void debugService(BluetoothGattService service, int indentCount) {
String indentString = StringUtils.repeat(' ', indentCount);
final UUID uuidService = service.getUuid();
if (gattDebugEnabled) {
final String uuidServiceString = uuidService.toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(indentString);
stringBuilder.append(GattAttributes.lookup(uuidServiceString, "Unknown service"));
stringBuilder.append(" (" + uuidServiceString + ")");
for (BluetoothGattCharacteristic character : service.getCharacteristics()) {
final String uuidCharacteristicString = character.getUuid().toString();
stringBuilder.append("\n ");
stringBuilder.append(indentString);
stringBuilder.append(" - " + GattAttributes.lookup(uuidCharacteristicString, "Unknown Characteristic"));
stringBuilder.append(" (" + uuidCharacteristicString + ")");
}
stringBuilder.append("\n\n");
aapsLogger.warn(LTag.PUMPBTCOMM, stringBuilder.toString());
List<BluetoothGattService> includedServices = service.getIncludedServices();
for (BluetoothGattService serviceI : includedServices) {
debugService(serviceI, indentCount + 4);
}
}
}
void registerRadioResponseCountNotification(Runnable notifier) {
radioResponseCountNotified = notifier;
}
public boolean isConnected() {
return mIsConnected;
}
public boolean discoverServices() {
if (bluetoothConnectionGatt == null) {
// shouldn't happen, but if it does we exit
return false;
}
if (bluetoothConnectionGatt.discoverServices()) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Starting to discover GATT Services.");
return true;
} else {
aapsLogger.error(LTag.PUMPBTCOMM, "Cannot discover GATT Services.");
return false;
}
}
public boolean enableNotifications() {
BLECommOperationResult result = setNotification_blocking(UUID.fromString(GattAttributes.SERVICE_RADIO),
UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT));
if (result.resultCode != BLECommOperationResult.RESULT_SUCCESS) {
aapsLogger.error(LTag.PUMPBTCOMM, "Error setting response count notification");
return false;
}
return true;
}
public void findRileyLink(String RileyLinkAddress) {
aapsLogger.debug(LTag.PUMPBTCOMM, "RileyLink address: " + RileyLinkAddress);
// Must verify that this is a valid MAC, or crash.
rileyLinkDevice = bluetoothAdapter.getRemoteDevice(RileyLinkAddress);
// if this succeeds, we get a connection state change callback?
if (rileyLinkDevice != null) {
connectGatt();
} else {
aapsLogger.error(LTag.PUMPBTCOMM, "RileyLink device not found with address: " + RileyLinkAddress);
}
}
// This function must be run on UI thread.
public void connectGatt() {
if (this.rileyLinkDevice == null) {
aapsLogger.error(LTag.PUMPBTCOMM, "RileyLink device is null, can't do connectGatt.");
return;
}
bluetoothConnectionGatt = rileyLinkDevice.connectGatt(context, true, bluetoothGattCallback);
// , BluetoothDevice.TRANSPORT_LE
if (bluetoothConnectionGatt == null) {
aapsLogger.error(LTag.PUMPBTCOMM, "Failed to connect to Bluetooth Low Energy device at " + bluetoothAdapter.getAddress());
} else {
if (gattDebugEnabled) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Gatt Connected.");
}
String deviceName = bluetoothConnectionGatt.getDevice().getName();
if (StringUtils.isNotEmpty(deviceName)) {
// Update stored name upon connecting (also for backwards compatibility for device where a name was not yet stored)
sp.putString(RileyLinkConst.Prefs.RileyLinkName, deviceName);
} else {
sp.remove(RileyLinkConst.Prefs.RileyLinkName);
}
rileyLinkServiceData.rileyLinkName = deviceName;
rileyLinkServiceData.rileyLinkAddress = bluetoothConnectionGatt.getDevice().getAddress();
}
}
public void disconnect() {
mIsConnected = false;
aapsLogger.warn(LTag.PUMPBTCOMM, "Closing GATT connection");
// Close old conenction
if (bluetoothConnectionGatt != null) {
// Not sure if to disconnect or to close first..
bluetoothConnectionGatt.disconnect();
manualDisconnect = true;
}
}
public void close() {
if (bluetoothConnectionGatt != null) {
bluetoothConnectionGatt.close();
bluetoothConnectionGatt = null;
}
}
private BLECommOperationResult setNotification_blocking(UUID serviceUUID, UUID charaUUID) {
BLECommOperationResult rval = new BLECommOperationResult();
if (bluetoothConnectionGatt != null) {
try {
gattOperationSema.acquire();
SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow
} catch (InterruptedException e) {
aapsLogger.error(LTag.PUMPBTCOMM, "setNotification_blocking: interrupted waiting for gattOperationSema");
return rval;
}
if (mCurrentOperation != null) {
rval.resultCode = BLECommOperationResult.RESULT_BUSY;
} else {
if (bluetoothConnectionGatt.getService(serviceUUID) == null) {
// Catch if the service is not supported by the BLE device
rval.resultCode = BLECommOperationResult.RESULT_NONE;
aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported");
// TODO: 11/07/2016 UI update for user
// xyz rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter);
} else {
BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID)
.getCharacteristic(charaUUID);
// Tell Android that we want the notifications
bluetoothConnectionGatt.setCharacteristicNotification(chara, true);
List<BluetoothGattDescriptor> list = chara.getDescriptors();
if (gattDebugEnabled) {
for (int i = 0; i < list.size(); i++) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Found descriptor: " + list.get(i).toString());
}
}
BluetoothGattDescriptor descr = list.get(0);
// Tell the remote device to send the notifications
mCurrentOperation = new DescriptorWriteOperation(aapsLogger, bluetoothConnectionGatt, descr,
BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mCurrentOperation.execute(this);
if (mCurrentOperation.timedOut) {
rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT;
} else if (mCurrentOperation.interrupted) {
rval.resultCode = BLECommOperationResult.RESULT_INTERRUPTED;
} else {
rval.resultCode = BLECommOperationResult.RESULT_SUCCESS;
}
}
mCurrentOperation = null;
gattOperationSema.release();
}
} else {
aapsLogger.error(LTag.PUMPBTCOMM, "setNotification_blocking: not configured!");
rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED;
}
return rval;
}
// call from main
BLECommOperationResult writeCharacteristic_blocking(UUID serviceUUID, UUID charaUUID, byte[] value) {
BLECommOperationResult rval = new BLECommOperationResult();
if (bluetoothConnectionGatt != null) {
rval.value = value;
try {
gattOperationSema.acquire();
SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow
} catch (InterruptedException e) {
aapsLogger.error(LTag.PUMPBTCOMM, "writeCharacteristic_blocking: interrupted waiting for gattOperationSema");
return rval;
}
if (mCurrentOperation != null) {
rval.resultCode = BLECommOperationResult.RESULT_BUSY;
} else {
if (bluetoothConnectionGatt.getService(serviceUUID) == null) {
// Catch if the service is not supported by the BLE device
// GGW: Tue Jul 12 01:14:01 UTC 2016: This can also happen if the
// app that created the bluetoothConnectionGatt has been destroyed/created,
// e.g. when the user switches from portrait to landscape.
rval.resultCode = BLECommOperationResult.RESULT_NONE;
aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported");
// TODO: 11/07/2016 UI update for user
// xyz rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter);
} else {
BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID)
.getCharacteristic(charaUUID);
mCurrentOperation = new CharacteristicWriteOperation(aapsLogger, bluetoothConnectionGatt, chara, value);
mCurrentOperation.execute(this);
if (mCurrentOperation.timedOut) {
rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT;
} else if (mCurrentOperation.interrupted) {
rval.resultCode = BLECommOperationResult.RESULT_INTERRUPTED;
} else {
rval.resultCode = BLECommOperationResult.RESULT_SUCCESS;
}
}
mCurrentOperation = null;
gattOperationSema.release();
}
} else {
aapsLogger.error(LTag.PUMPBTCOMM, "writeCharacteristic_blocking: not configured!");
rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED;
}
return rval;
}
BLECommOperationResult readCharacteristic_blocking(UUID serviceUUID, UUID charaUUID) {
BLECommOperationResult rval = new BLECommOperationResult();
if (bluetoothConnectionGatt != null) {
try {
gattOperationSema.acquire();
SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow
} catch (InterruptedException e) {
aapsLogger.error(LTag.PUMPBTCOMM, "readCharacteristic_blocking: Interrupted waiting for gattOperationSema");
return rval;
}
if (mCurrentOperation != null) {
rval.resultCode = BLECommOperationResult.RESULT_BUSY;
} else {
if (bluetoothConnectionGatt.getService(serviceUUID) == null) {
// Catch if the service is not supported by the BLE device
rval.resultCode = BLECommOperationResult.RESULT_NONE;
aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported");
// TODO: 11/07/2016 UI update for user
// xyz rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter);
} else {
BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID).getCharacteristic(
charaUUID);
mCurrentOperation = new CharacteristicReadOperation(aapsLogger, bluetoothConnectionGatt, chara);
mCurrentOperation.execute(this);
if (mCurrentOperation.timedOut) {
rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT;
} else if (mCurrentOperation.interrupted) {
rval.resultCode = BLECommOperationResult.RESULT_INTERRUPTED;
} else {
rval.resultCode = BLECommOperationResult.RESULT_SUCCESS;
rval.value = mCurrentOperation.getValue();
}
}
}
mCurrentOperation = null;
gattOperationSema.release();
} else {
aapsLogger.error(LTag.PUMPBTCOMM, "readCharacteristic_blocking: not configured!");
rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED;
}
return rval;
}
private String getGattStatusMessage(final int status) {
final String statusMessage;
if (status == BluetoothGatt.GATT_SUCCESS) {
statusMessage = "SUCCESS";
} else if (status == BluetoothGatt.GATT_FAILURE) {
statusMessage = "FAILED";
} else if (status == BluetoothGatt.GATT_WRITE_NOT_PERMITTED) {
statusMessage = "NOT PERMITTED";
} else if (status == 133) {
statusMessage = "Found the strange 133 bug";
} else {
statusMessage = "UNKNOWN (" + status + ")";
}
return statusMessage;
}
}
|
package fr.obeo.dsl.debug.ide;
import fr.obeo.dsl.debug.ide.event.IDSLDebugEvent;
import fr.obeo.dsl.debug.ide.event.IDSLDebugEventProcessor;
import fr.obeo.dsl.debug.ide.event.debugger.BreakpointReply;
import fr.obeo.dsl.debug.ide.event.debugger.DeleteVariableReply;
import fr.obeo.dsl.debug.ide.event.debugger.PopStackFrameReply;
import fr.obeo.dsl.debug.ide.event.debugger.PushStackFrameReply;
import fr.obeo.dsl.debug.ide.event.debugger.ResumingReply;
import fr.obeo.dsl.debug.ide.event.debugger.SetCurrentInstructionReply;
import fr.obeo.dsl.debug.ide.event.debugger.SpawnRunningThreadReply;
import fr.obeo.dsl.debug.ide.event.debugger.StepIntoResumingReply;
import fr.obeo.dsl.debug.ide.event.debugger.StepOverResumingReply;
import fr.obeo.dsl.debug.ide.event.debugger.StepReturnResumingReply;
import fr.obeo.dsl.debug.ide.event.debugger.SteppedReply;
import fr.obeo.dsl.debug.ide.event.debugger.SuspendedReply;
import fr.obeo.dsl.debug.ide.event.debugger.TerminatedReply;
import fr.obeo.dsl.debug.ide.event.debugger.VariableReply;
import fr.obeo.dsl.debug.ide.event.model.AbstractBreakpointRequest;
import fr.obeo.dsl.debug.ide.event.model.AbstractStepRequest;
import fr.obeo.dsl.debug.ide.event.model.AddBreakpointRequest;
import fr.obeo.dsl.debug.ide.event.model.DisconnectRequest;
import fr.obeo.dsl.debug.ide.event.model.RemoveBreakpointRequest;
import fr.obeo.dsl.debug.ide.event.model.ResumeRequest;
import fr.obeo.dsl.debug.ide.event.model.StartRequest;
import fr.obeo.dsl.debug.ide.event.model.StepIntoRequest;
import fr.obeo.dsl.debug.ide.event.model.StepOverRequest;
import fr.obeo.dsl.debug.ide.event.model.StepReturnRequest;
import fr.obeo.dsl.debug.ide.event.model.SuspendRequest;
import fr.obeo.dsl.debug.ide.event.model.TerminateRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* Base {@link IDSLDebugger debugger} implementation.
*
* @author <a href="mailto:yvan.lussaud@obeo.fr">Yvan Lussaud</a>
*/
public abstract class AbstractDSLDebugger implements IDSLDebugger {
/**
* The {@link fr.obeo.dsl.debug.ide.event.DSLDebugEventDispatcher dispatcher} for asynchronous
* communication or the {@link fr.obeo.dsl.debug.ide.DSLDebugTargetAdapter target} for synchronous
* communication.
*/
protected final IDSLDebugEventProcessor target;
/**
* Tells if the debugger is terminated.
*/
private boolean terminated;
/**
* Thread name to current instruction. For check purpose only.
*/
protected final Map<String, EObject> currentInstructions = new HashMap<String, EObject>();
/**
* Mapping form thread name to the thread controller.
*/
private final Map<String, ThreadController> controllers = new ConcurrentHashMap<String, ThreadController>();
/**
* Instructions marked as breakpoints. TODO find something more powerful (expression, EClass, etc...)
*/
private final Set<URI> breakpoints = new HashSet<URI>();
/**
* Constructor.
*
* @param target
* the {@link fr.obeo.dsl.debug.ide.event.DSLDebugEventDispatcher dispatcher} for asynchronous
* communication or the {@link fr.obeo.dsl.debug.ide.DSLDebugTargetAdapter target} for
* synchronous communication
*/
public AbstractDSLDebugger(IDSLDebugEventProcessor target) {
this.target = target;
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.event.IDSLDebugEventProcessor#handleEvent(fr.obeo.dsl.debug.ide.event.IDSLDebugEvent)
*/
public void handleEvent(IDSLDebugEvent event) {
if (event instanceof DisconnectRequest) {
disconnect();
} else if (event instanceof AbstractStepRequest) {
handleStepRequest((AbstractStepRequest)event);
} else if (event instanceof ResumeRequest) {
handleResumeRequest((ResumeRequest)event);
} else if (event instanceof SuspendRequest) {
handleSuspendRequest((SuspendRequest)event);
} else if (event instanceof TerminateRequest) {
handleTerminateRequest((TerminateRequest)event);
} else if (event instanceof AbstractBreakpointRequest) {
handleBreakpointRequest((AbstractBreakpointRequest)event);
} else if (event instanceof StartRequest) {
start();
}
}
/**
* Handles {@link AbstractBreakpointRequest}.
*
* @param breakpointRequest
* the {@link AbstractBreakpointRequest}
*/
private void handleBreakpointRequest(AbstractBreakpointRequest breakpointRequest) {
if (breakpointRequest instanceof AddBreakpointRequest) {
addBreakPoint(breakpointRequest.getURI());
} else if (breakpointRequest instanceof RemoveBreakpointRequest) {
removeBreakPoint(breakpointRequest.getURI());
}
}
/**
* Handles {@link TerminateRequest}.
*
* @param terminateRequest
* the {@link TerminateRequest}
*/
private void handleTerminateRequest(TerminateRequest terminateRequest) {
final String threadName = terminateRequest.getThreadName();
if (threadName != null) {
terminate(threadName);
// target.handleEvent(new TerminatedReply(threadName));
} else {
terminate();
target.handleEvent(new TerminatedReply());
}
}
/**
* Handles {@link SuspendRequest}.
*
* @param suspendRequest
* the {@link SuspendRequest}
*/
private void handleSuspendRequest(SuspendRequest suspendRequest) {
final String threadName = suspendRequest.getThreadName();
if (threadName != null) {
suspend(threadName);
} else {
suspend();
}
}
/**
* Handles {@link ResumeRequest}.
*
* @param resumeRequest
* the {@link ResumeRequest}
*/
private void handleResumeRequest(ResumeRequest resumeRequest) {
final String threadName = resumeRequest.getThreadName();
if (threadName != null) {
resume(threadName);
} else {
resume();
}
}
/**
* Handles {@link AbstractStepRequest}.
*
* @param stepRequest
* the {@link AbstractStepRequest}
*/
private void handleStepRequest(AbstractStepRequest stepRequest) {
final String threadName = stepRequest.getThreadName();
if (stepRequest.getInstrcution() != currentInstructions.get(threadName)) {
throw new IllegalStateException("instruction desynchronization.");
}
if (stepRequest instanceof StepIntoRequest) {
stepInto(threadName);
} else if (stepRequest instanceof StepOverRequest) {
stepOver(threadName);
} else if (stepRequest instanceof StepReturnRequest) {
stepReturn(threadName);
}
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#stepped(java.lang.String)
*/
public void stepped(final String threadName) {
target.handleEvent(new SteppedReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#suspended(java.lang.String)
*/
public void suspended(String threadName) {
target.handleEvent(new SuspendedReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#breaked(java.lang.String)
*/
public void breaked(String threadName) {
target.handleEvent(new BreakpointReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#resuming(java.lang.String)
*/
public void resuming(String threadName) {
target.handleEvent(new ResumingReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#steppingInto(java.lang.String)
*/
public void steppingInto(String threadName) {
target.handleEvent(new StepIntoResumingReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#steppingOver(java.lang.String)
*/
public void steppingOver(String threadName) {
target.handleEvent(new StepOverResumingReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#steppingReturn(java.lang.String)
*/
public void steppingReturn(String threadName) {
target.handleEvent(new StepReturnResumingReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#terminated()
*/
public void terminated() {
target.handleEvent(new TerminatedReply());
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#spawnRunningThread(java.lang.String,
* org.eclipse.emf.ecore.EObject)
*/
public void spawnRunningThread(String threadName, EObject context) {
target.handleEvent(new SpawnRunningThreadReply(threadName, context));
controllers.put(threadName, createThreadHandler(threadName));
}
/**
* Creates a {@link ThreadController} for the given thread. if the thread is a new Java {@link Thread} a
* new instance should be created, if not the {@link ThreadController} for the existing Java
* {@link Thread} should be returned.
*
* @param threadName
* the thread name
* @return if the thread is a new Java {@link Thread} a new instance should be created, if not the
* {@link ThreadController} for the existing Java {@link Thread} should be returned
*/
protected ThreadController createThreadHandler(String threadName) {
return new ThreadController(this, threadName);
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#setTerminated(boolean)
*/
public void setTerminated(boolean terminated) {
this.terminated = terminated;
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#isTerminated()
*/
public boolean isTerminated() {
return terminated;
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#getNextInstruction(java.lang.String,
* org.eclipse.emf.ecore.EObject, fr.obeo.dsl.debug.ide.IDSLDebugger.Stepping)
*/
public EObject getNextInstruction(String threadName, EObject currentInstruction, Stepping stepping) {
return null;
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#shouldBreak(org.eclipse.emf.ecore.EObject)
*/
public boolean shouldBreak(EObject instruction) {
return breakpoints.contains(EcoreUtil.getURI(instruction));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#addBreakPoint(org.eclipse.emf.common.util.URI)
*/
public void addBreakPoint(URI instruction) {
breakpoints.add(instruction);
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#removeBreakPoint(org.eclipse.emf.common.util.URI)
*/
public void removeBreakPoint(URI instruction) {
breakpoints.remove(instruction);
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#control(java.lang.String, org.eclipse.emf.ecore.EObject)
*/
public boolean control(String threadName, EObject instruction) {
final boolean res;
if (!isTerminated()) {
res = controllers.get(threadName).control(instruction);
} else {
res = false;
}
return res;
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#resume(java.lang.String)
*/
public void resume(String threadName) {
controllers.get(threadName).resume();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#stepInto(java.lang.String)
*/
public void stepInto(String threadName) {
controllers.get(threadName).stepInto();
};
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#stepOver(java.lang.String)
*/
public void stepOver(String threadName) {
controllers.get(threadName).stepOver();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#stepReturn(java.lang.String)
*/
public void stepReturn(String threadName) {
controllers.get(threadName).stepReturn();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#suspend(java.lang.String)
*/
public void suspend(String threadName) {
controllers.get(threadName).suspend();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#terminate()
*/
public void terminate() {
setTerminated(true);
for (ThreadController controler : controllers.values()) {
synchronized(controler) {
controler.wakeUp();
}
}
controllers.clear();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#terminate(java.lang.String)
*/
public void terminate(String threadName) {
controllers.get(threadName).terminate();
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#suspend()
*/
public void suspend() {
for (ThreadController controler : controllers.values()) {
controler.suspend();
}
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#resume()
*/
public void resume() {
for (ThreadController controler : controllers.values()) {
controler.resume();
}
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#variable(java.lang.String, java.lang.String, java.lang.String,
* java.lang.Object)
*/
public void variable(String threadName, String declarationTypeName, String name, Object value) {
target.handleEvent(new VariableReply(threadName, declarationTypeName, name, value));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#deleteVariable(java.lang.String, java.lang.String)
*/
public void deleteVariable(String threadName, String name) {
target.handleEvent(new DeleteVariableReply(threadName, name));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#pushStackFrame(java.lang.String, java.lang.String,
* org.eclipse.emf.ecore.EObject, org.eclipse.emf.ecore.EObject)
*/
public void pushStackFrame(String threadName, String frameName, EObject context, EObject instruction) {
currentInstructions.put(threadName, instruction);
target.handleEvent(new PushStackFrameReply(threadName, frameName, context, instruction, canStepInto(
threadName, instruction)));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#popStackFrame(java.lang.String)
*/
public void popStackFrame(String threadName) {
target.handleEvent(new PopStackFrameReply(threadName));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#setCurrentInstruction(java.lang.String,
* org.eclipse.emf.ecore.EObject)
*/
public void setCurrentInstruction(String threadName, EObject instruction) {
currentInstructions.put(threadName, instruction);
target.handleEvent(new SetCurrentInstructionReply(threadName, instruction, canStepInto(threadName,
instruction)));
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#terminated(java.lang.String)
*/
public void terminated(String threadName) {
target.handleEvent(new TerminatedReply(threadName));
controllers.remove(threadName);
if (controllers.size() == 0) {
setTerminated(true);
terminated();
}
}
/**
* {@inheritDoc}
*
* @see fr.obeo.dsl.debug.ide.IDSLDebugger#isTerminated(java.lang.String)
*/
public boolean isTerminated(String threadName) {
return !controllers.containsKey(threadName);
}
}
|
package com.linkedin.thirdeye.dashboard.resources;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkedin.thirdeye.anomalydetection.alertFilterAutotune.BaseAlertFilterAutoTune;
import com.linkedin.thirdeye.detector.email.filter.BaseAlertFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.linkedin.thirdeye.anomaly.detection.DetectionJobScheduler;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.format.ISODateTimeFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkedin.thirdeye.anomaly.detection.lib.AutotuneMethodType;
import com.linkedin.thirdeye.anomaly.detection.lib.FunctionReplayRunnable;
import com.linkedin.thirdeye.anomaly.job.JobConstants.JobStatus;
import com.linkedin.thirdeye.anomaly.utils.AnomalyUtils;
import com.linkedin.thirdeye.anomalydetection.alertFilterAutotune.AlertFilterAutotuneFactory;
import com.linkedin.thirdeye.anomalydetection.performanceEvaluation.PerformanceEvaluateHelper;
import com.linkedin.thirdeye.anomalydetection.performanceEvaluation.PerformanceEvaluationMethod;
import com.linkedin.thirdeye.api.TimeGranularity;
import com.linkedin.thirdeye.datalayer.bao.AnomalyFunctionManager;
import com.linkedin.thirdeye.datalayer.bao.AutotuneConfigManager;
import com.linkedin.thirdeye.datalayer.bao.MergedAnomalyResultManager;
import com.linkedin.thirdeye.datalayer.bao.RawAnomalyResultManager;
import com.linkedin.thirdeye.datalayer.dto.AnomalyFunctionDTO;
import com.linkedin.thirdeye.datalayer.dto.AutotuneConfigDTO;
import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO;
import com.linkedin.thirdeye.datasource.DAORegistry;
import com.linkedin.thirdeye.detector.email.filter.AlertFilter;
import com.linkedin.thirdeye.detector.email.filter.AlertFilterFactory;
import com.linkedin.thirdeye.detector.email.filter.PrecisionRecallEvaluator;
import com.linkedin.thirdeye.util.SeverityComputationUtil;
@Path("/detection-job")
@Produces(MediaType.APPLICATION_JSON)
public class DetectionJobResource {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final DetectionJobScheduler detectionJobScheduler;
private final AnomalyFunctionManager anomalyFunctionDAO;
private final MergedAnomalyResultManager mergedAnomalyResultDAO;
private final RawAnomalyResultManager rawAnomalyResultDAO;
private final AutotuneConfigManager autotuneConfigDAO;
private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance();
private final AlertFilterAutotuneFactory alertFilterAutotuneFactory;
private final AlertFilterFactory alertFilterFactory;
private EmailResource emailResource;
private static final Logger LOG = LoggerFactory.getLogger(DetectionJobResource.class);
public static final String AUTOTUNE_FEATURE_KEY = "features";
public static final String AUTOTUNE_PATTERN_KEY = "pattern";
public static final String AUTOTUNE_MTTD_KEY = "mttd";
public DetectionJobResource(DetectionJobScheduler detectionJobScheduler, AlertFilterFactory alertFilterFactory, AlertFilterAutotuneFactory alertFilterAutotuneFactory, EmailResource emailResource) {
this.detectionJobScheduler = detectionJobScheduler;
this.anomalyFunctionDAO = DAO_REGISTRY.getAnomalyFunctionDAO();
this.mergedAnomalyResultDAO = DAO_REGISTRY.getMergedAnomalyResultDAO();
this.rawAnomalyResultDAO = DAO_REGISTRY.getRawAnomalyResultDAO();
this.autotuneConfigDAO = DAO_REGISTRY.getAutotuneConfigDAO();
this.alertFilterAutotuneFactory = alertFilterAutotuneFactory;
this.alertFilterFactory = alertFilterFactory;
this.emailResource = emailResource;
}
// Toggle Function Activation is redundant to endpoints defined in AnomalyResource
@Deprecated
@POST
@Path("/{id}")
public Response enable(@PathParam("id") Long id) throws Exception {
toggleActive(id, true);
return Response.ok().build();
}
@Deprecated
@DELETE
@Path("/{id}")
public Response disable(@PathParam("id") Long id) throws Exception {
toggleActive(id, false);
return Response.ok().build();
}
@Deprecated
private void toggleActive(Long id, boolean state) {
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(id);
if (anomalyFunctionSpec == null) {
throw new NullArgumentException("Function spec not found");
}
anomalyFunctionSpec.setIsActive(state);
anomalyFunctionDAO.update(anomalyFunctionSpec);
}
// endpoints to modify to aonmaly detection function
// show remove to anomalyResource
@POST
@Path("/requiresCompletenessCheck/enable/{id}")
public Response enableRequiresCompletenessCheck(@PathParam("id") Long id) throws Exception {
toggleRequiresCompletenessCheck(id, true);
return Response.ok().build();
}
@POST
@Path("/requiresCompletenessCheck/disable/{id}")
public Response disableRequiresCompletenessCheck(@PathParam("id") Long id) throws Exception {
toggleRequiresCompletenessCheck(id, false);
return Response.ok().build();
}
private void toggleRequiresCompletenessCheck(Long id, boolean state) {
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(id);
if(anomalyFunctionSpec == null) {
throw new NullArgumentException("Function spec not found");
}
anomalyFunctionSpec.setRequiresCompletenessCheck(state);
anomalyFunctionDAO.update(anomalyFunctionSpec);
}
@POST
@Path("/{id}/ad-hoc")
public Response adHoc(@PathParam("id") Long id, @QueryParam("start") String startTimeIso,
@QueryParam("end") String endTimeIso) throws Exception {
Long startTime = null;
Long endTime = null;
if (StringUtils.isBlank(startTimeIso) || StringUtils.isBlank(endTimeIso)) {
throw new IllegalStateException("startTimeIso and endTimeIso must not be null");
}
startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
detectionJobScheduler.runAdhocAnomalyFunction(id, startTime, endTime);
return Response.ok().build();
}
/**
* Returns the weight of the metric at the given window. The calculation of baseline (history) data is specified by
* seasonal period (in days) and season count. Seasonal period is the difference of duration from one window to the
* other. For instance, to use the data that is one week before current window, set seasonal period to 7. The season
* count specify how many seasons of history data to retrieve. If there are more than 1 season, then the baseline is
* the average of all seasons.
*
* Examples of the configuration of baseline:
* 1. Week-Over-Week: seasonalPeriodInDays = 7, seasonCount = 1
* 2. Week-Over-4-Weeks-Mean: seasonalPeriodInDays = 7, seasonCount = 4
* 3. Month-Over-Month: seasonalPeriodInDays = 30, seasonCount = 1
*
* @param collectionName the collection to which the metric belong
* @param metricName the metric name
* @param startTimeIso start time of current window, inclusive
* @param endTimeIso end time of current window, exclusive
* @param seasonalPeriodInDays the difference of duration between the start time of each window
* @param seasonCount the number of history windows
*
* @return the weight of the metric at the given window
* @throws Exception
*/
@POST
@Path("/anomaly-weight")
public Response computeSeverity(@NotNull @QueryParam("collection") String collectionName,
@NotNull @QueryParam("metric") String metricName,
@NotNull @QueryParam("start") String startTimeIso, @NotNull @QueryParam("end") String endTimeIso,
@QueryParam("period") String seasonalPeriodInDays, @QueryParam("seasonCount") String seasonCount)
throws Exception {
DateTime startTime = null;
DateTime endTime = null;
if (StringUtils.isNotBlank(startTimeIso)) {
startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso);
}
if (StringUtils.isNotBlank(endTimeIso)) {
endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso);
}
long currentWindowStart = startTime.getMillis();
long currentWindowEnd = endTime.getMillis();
// Default is using one week data priors current values for calculating weight
long seasonalPeriodMillis = TimeUnit.DAYS.toMillis(7);
if (StringUtils.isNotBlank(seasonalPeriodInDays)) {
seasonalPeriodMillis = TimeUnit.DAYS.toMillis(Integer.parseInt(seasonalPeriodInDays));
}
int seasonCountInt = 1;
if (StringUtils.isNotBlank(seasonCount)) {
seasonCountInt = Integer.parseInt(seasonCount);
}
SeverityComputationUtil util = new SeverityComputationUtil(collectionName, metricName);
Map<String, Object> severity =
util.computeSeverity(currentWindowStart, currentWindowEnd, seasonalPeriodMillis, seasonCountInt);
return Response.ok(severity.toString(), MediaType.TEXT_PLAIN_TYPE).build();
}
/**
* The wrapper endpoint to do first time replay, tuning and send out notification to user
* @param id anomaly function id
* @param startTimeIso start time of replay
* @param endTimeIso end time of replay
* @param isForceBackfill whether force back fill or not, default is true
* @param isRemoveAnomaliesInWindow whether need to remove exsiting anomalies within replay time window, default is false
* @param speedup whether use speedUp or not
* @param userDefinedPattern tuning parameter, user defined pattern can be "UP", "DOWN", or "UP&DOWN"
* @param sensitivity sensitivity level for initial tuning
* @param fromAddr email notification from address, if blank uses fromAddr of ThirdEyeConfiguration
* @param toAddr email notification to address
* @param teHost thirdeye host, if black uses thirdeye host configured in ThirdEyeConfiguration
* @param smtpHost smtp host if black uses smtpHost configured in ThirdEyeConfiguration
* @param smtpPort smtp port if black uses smtpPort configured in ThirdEyeConfiguration
* @param phantomJsPath phantomJSpath
* @return
*/
@POST
@Path("/{id}/notifyreplaytuning")
public Response triggerReplayTuningAndNotification(@PathParam("id") @NotNull final long id,
@QueryParam("start") @NotNull String startTimeIso, @QueryParam("end") @NotNull String endTimeIso,
@QueryParam("force") @DefaultValue("true") String isForceBackfill,
@QueryParam("removeAnomaliesInWindow") @DefaultValue("false") final Boolean isRemoveAnomaliesInWindow,
@QueryParam("speedup") @DefaultValue("false") final Boolean speedup,
@QueryParam("userDefinedPattern") @DefaultValue("UP") String userDefinedPattern,
@QueryParam("sensitivity") @DefaultValue("MEDIUM") final String sensitivity, @QueryParam("from") String fromAddr,
@QueryParam("to") String toAddr,
@QueryParam("teHost") String teHost, @QueryParam("smtpHost") String smtpHost,
@QueryParam("smtpPort") Integer smtpPort, @QueryParam("phantomJsPath") String phantomJsPath) {
// run replay, update function with jobId
long jobId;
try {
Response response =
generateAnomaliesInRange(id, startTimeIso, endTimeIso, isForceBackfill, speedup, isRemoveAnomaliesInWindow);
Map<Long, Long> entity = (Map<Long, Long>) response.getEntity();
jobId = entity.get(id);
} catch (Exception e) {
return Response.status(Status.BAD_REQUEST).entity("Failed to start replay!").build();
}
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
JobStatus jobStatus = detectionJobScheduler.waitForJobDone(jobId);
int numReplayedAnomalies = 0;
if (!jobStatus.equals(JobStatus.COMPLETED)) {
//TODO: cleanup done tasks and replay results under this failed job
// send email to internal
String replayFailureSubject =
new StringBuilder("Replay failed on metric: " + anomalyFunctionDAO.findById(id).getMetric()).toString();
String replayFailureText = new StringBuilder("Failed on Function: " + id + "with Job Id: " + jobId).toString();
emailResource.sendEmailWithText(null, null, replayFailureSubject, replayFailureText,
smtpHost, smtpPort);
return Response.status(Status.BAD_REQUEST).entity("Replay job error with job status: {}" + jobStatus).build();
} else {
numReplayedAnomalies =
mergedAnomalyResultDAO.findByStartTimeInRangeAndFunctionId(startTime, endTime, id, false).size();
LOG.info("Replay completed with {} anomalies generated.", numReplayedAnomalies);
}
// create initial tuning and apply filter
Response initialAutotuneResponse =
initiateAlertFilterAutoTune(id, startTimeIso, endTimeIso, "AUTOTUNE", userDefinedPattern, sensitivity, "", "");
if (initialAutotuneResponse.getEntity() != null) {
updateAlertFilterToFunctionSpecByAutoTuneId(Long.valueOf(initialAutotuneResponse.getEntity().toString()));
LOG.info("Initial alert filter applied");
} else {
LOG.info("AutoTune doesn't applied");
}
// send out email
String subject = new StringBuilder(
"Replay results for " + anomalyFunctionDAO.findById(id).getFunctionName() + " is ready for review!").toString();
emailResource.generateAndSendAlertForFunctions(startTime, endTime, String.valueOf(id), fromAddr, toAddr, subject,
false, true, teHost, smtpHost, smtpPort, phantomJsPath);
LOG.info("Sent out email");
return Response.ok("Replay, Tuning and Notification finished!").build();
}
/**
* Breaks down the given range into consecutive monitoring windows as per function definition
* Regenerates anomalies for each window separately
*
* As the anomaly result regeneration is a heavy job, we move the function from Dashboard to worker
* @param id an anomaly function id
* @param startTimeIso The start time of the monitoring window (in ISO Format), ex: 2016-5-23T00:00:00Z
* @param endTimeIso The start time of the monitoring window (in ISO Format)
* @param isForceBackfill false to resume backfill from the latest left off
* @param speedup
* whether this backfill should speedup with 7-day window. The assumption is that the functions are using
* WoW-based algorithm, or Seasonal Data Model.
* @return HTTP response of this request with a job execution id
* @throws Exception
*/
@POST
@Path("/{id}/replay")
public Response generateAnomaliesInRange(@PathParam("id") @NotNull final long id,
@QueryParam("start") @NotNull String startTimeIso,
@QueryParam("end") @NotNull String endTimeIso,
@QueryParam("force") @DefaultValue("false") String isForceBackfill,
@QueryParam("speedup") @DefaultValue("false") final Boolean speedup,
@QueryParam("removeAnomaliesInWindow") @DefaultValue("false") final Boolean isRemoveAnomaliesInWindow) throws Exception {
Response response = generateAnomaliesInRangeForFunctions(Long.toString(id), startTimeIso, endTimeIso,
isForceBackfill, speedup, isRemoveAnomaliesInWindow);
return response;
}
/**
* Breaks down the given range into consecutive monitoring windows as per function definition
* Regenerates anomalies for each window separately
*
* Different from the previous replay function, this replay function takes multiple function ids, and is able to send
* out alerts to user once the replay is done.
*
* Enable replay on inactive function, but still keep the original function status after replay
* If the anomaly function has historical anomalies, will only remove anomalies within the replay period, making replay capable to take historical information
*
* As the anomaly result regeneration is a heavy job, we move the function from Dashboard to worker
* @param ids a string containing multiple anomaly function ids, separated by comma (e.g. f1,f2,f3)
* @param startTimeIso The start time of the monitoring window (in ISO Format), ex: 2016-5-23T00:00:00Z
* @param endTimeIso The start time of the monitoring window (in ISO Format)
* @param isForceBackfill false to resume backfill from the latest left off
* @param speedup
* whether this backfill should speedup with 7-day window. The assumption is that the functions are using
* WoW-based algorithm, or Seasonal Data Model.
* @param isRemoveAnomaliesInWindow whether remove existing anomalies in replay window
* @return HTTP response of this request with a map from function id to its job execution id
* @throws Exception
*/
@POST
@Path("/replay")
public Response generateAnomaliesInRangeForFunctions(@QueryParam("ids") @NotNull String ids,
@QueryParam("start") @NotNull String startTimeIso,
@QueryParam("end") @NotNull String endTimeIso,
@QueryParam("force") @DefaultValue("false") String isForceBackfill,
@QueryParam("speedup") @DefaultValue("false") final Boolean speedup,
@QueryParam("removeAnomaliesInWindow") @DefaultValue("false") final Boolean isRemoveAnomaliesInWindow) throws Exception {
final boolean forceBackfill = Boolean.valueOf(isForceBackfill);
final List<Long> functionIdList = new ArrayList<>();
final Map<Long, Long> detectionJobIdMap = new HashMap<>();
for (String functionId : ids.split(",")) {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(Long.valueOf(functionId));
if (anomalyFunction != null) {
functionIdList.add(Long.valueOf(functionId));
} else {
LOG.warn("[Backfill] Unable to load function id {}", functionId);
}
}
if (functionIdList.isEmpty()) {
return Response.noContent().build();
}
// Check if the timestamps are available
DateTime startTime = null;
DateTime endTime = null;
if (startTimeIso == null || startTimeIso.isEmpty()) {
LOG.error("[Backfill] Monitoring start time is not found");
throw new IllegalArgumentException(String.format("[Backfill] Monitoring start time is not found"));
}
if (endTimeIso == null || endTimeIso.isEmpty()) {
LOG.error("[Backfill] Monitoring end time is not found");
throw new IllegalArgumentException(String.format("[Backfill] Monitoring end time is not found"));
}
startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso);
endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso);
if (startTime.isAfter(endTime)) {
LOG.error("[Backfill] Monitoring start time is after monitoring end time");
throw new IllegalArgumentException(String.format(
"[Backfill] Monitoring start time is after monitoring end time"));
}
if (endTime.isAfterNow()) {
endTime = DateTime.now();
LOG.warn("[Backfill] End time is in the future. Force to now.");
}
final Map<Long, Integer> originalWindowSize = new HashMap<>();
final Map<Long, TimeUnit> originalWindowUnit = new HashMap<>();
final Map<Long, String> originalCron = new HashMap<>();
saveFunctionWindow(functionIdList, originalWindowSize, originalWindowUnit, originalCron);
// Update speed-up window and cron
if (speedup) {
for (long functionId : functionIdList) {
anomalyFunctionSpeedup(functionId);
}
}
// Run backfill : for each function, set to be active to enable runBackfill,
// remove existing anomalies if there is any already within the replay window (to avoid duplicated anomaly results)
// set the original activation status back after backfill
for (long functionId : functionIdList) {
// Activate anomaly function if it's inactive
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId);
Boolean isActive = anomalyFunction.getIsActive();
if (!isActive) {
anomalyFunction.setActive(true);
anomalyFunctionDAO.update(anomalyFunction);
}
// if isRemoveAnomaliesInWindow is true, remove existing anomalies within same replay window
if (isRemoveAnomaliesInWindow) {
OnboardResource onboardResource = new OnboardResource();
onboardResource.deleteExistingAnomalies(functionId, startTime.getMillis(), endTime.getMillis());
}
// run backfill
long detectionJobId = detectionJobScheduler.runBackfill(functionId, startTime, endTime, forceBackfill);
// Put back activation status
anomalyFunction.setActive(isActive);
anomalyFunctionDAO.update(anomalyFunction);
detectionJobIdMap.put(functionId, detectionJobId);
}
/**
* Check the job status in thread and recover the function
*/
new Thread(new Runnable() {
@Override
public void run() {
for(long detectionJobId : detectionJobIdMap.values()) {
detectionJobScheduler.waitForJobDone(detectionJobId);
}
// Revert window setup
revertFunctionWindow(functionIdList, originalWindowSize, originalWindowUnit, originalCron);
}
}).start();
return Response.ok(detectionJobIdMap).build();
}
/**
* Under current infrastructure, we are not able to determine whether and how we accelerate the backfill.
* Currently, the requirement for speedup is to increase the window up to 1 week.
* For WoW-based models, if we enlarge the window to 7 days, it can significantly increase the backfill speed.
* Now, the hard-coded code is a contemporary solution to this problem. It can be fixed under new infra.
*
* TODO Data model provide information on how the function can speed up, and user determines if they wnat to speed up
* TODO the replay
* @param functionId
*/
private void anomalyFunctionSpeedup (long functionId) {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId);
anomalyFunction.setWindowSize(170);
anomalyFunction.setWindowUnit(TimeUnit.HOURS);
anomalyFunction.setCron("0 0 0 ? * MON *");
anomalyFunctionDAO.update(anomalyFunction);
}
private void saveFunctionWindow(List<Long> functionIdList, Map<Long, Integer> windowSize,
Map<Long, TimeUnit> windowUnit, Map<Long, String> cron) {
for (long functionId : functionIdList) {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId);
windowSize.put(functionId, anomalyFunction.getWindowSize());
windowUnit.put(functionId, anomalyFunction.getWindowUnit());
cron.put(functionId, anomalyFunction.getCron());
}
}
private void revertFunctionWindow(List<Long> functionIdList, Map<Long, Integer> windowSize,
Map<Long, TimeUnit> windowUnit, Map<Long, String> cron) {
for (long functionId : functionIdList) {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId);
if (windowSize.containsKey(functionId)) {
anomalyFunction.setWindowSize(windowSize.get(functionId));
}
if (windowUnit.containsKey(functionId)) {
anomalyFunction.setWindowUnit(windowUnit.get(functionId));
}
if (cron.containsKey(functionId)) {
anomalyFunction.setCron(cron.get(functionId));
}
anomalyFunctionDAO.update(anomalyFunction);
}
}
@POST
@Path("/{id}/offlineAnalysis")
public Response generateAnomaliesInTrainingData(@PathParam("id") @NotNull long id,
@QueryParam("time") String analysisTimeIso) throws Exception {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(id);
if (anomalyFunction == null) {
return Response.noContent().build();
}
DateTime analysisTime = DateTime.now();
if (StringUtils.isNotEmpty(analysisTimeIso)) {
analysisTime = ISODateTimeFormat.dateTimeParser().parseDateTime(analysisTimeIso);
}
Long jobId = detectionJobScheduler.runOfflineAnalysis(id, analysisTime);
List<Long> anomalyIds = new ArrayList<>();
if (jobId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Anomaly function " + Long.toString(id)
+ " is inactive. Or thread is interrupted.").build();
} else {
JobStatus jobStatus = detectionJobScheduler.waitForJobDone(jobId);
if(jobStatus.equals(JobStatus.FAILED)) {
return Response.status(Response.Status.NO_CONTENT).entity("Detection job failed").build();
} else {
List<MergedAnomalyResultDTO> mergedAnomalies = mergedAnomalyResultDAO.findByStartTimeInRangeAndFunctionId(
0, analysisTime.getMillis(), id, true);
for (MergedAnomalyResultDTO mergedAnomaly : mergedAnomalies) {
anomalyIds.add(mergedAnomaly.getId());
}
}
}
return Response.ok(anomalyIds).build();
}
/**
* Given a list of holiday starts and holiday ends, return merged anomalies with holidays removed
* @param functionId: the functionId to fetch merged anomalies with holidays removed
* @param startTime: start time in milliseconds of merged anomalies
* @param endTime: end time of in milliseconds merged anomalies
* @param holidayStarts: holidayStarts in ISO Format ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param holidayEnds: holidayEnds in in ISO Format ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @return a list of merged anomalies with holidays removed
*/
public static List<MergedAnomalyResultDTO> getMergedAnomaliesRemoveHolidays(long functionId, long startTime, long endTime, String holidayStarts, String holidayEnds) {
StringTokenizer starts = new StringTokenizer(holidayStarts, ",");
StringTokenizer ends = new StringTokenizer(holidayEnds, ",");
MergedAnomalyResultManager anomalyMergedResultDAO = DAO_REGISTRY.getMergedAnomalyResultDAO();
List<MergedAnomalyResultDTO> totalAnomalies = anomalyMergedResultDAO.findByStartTimeInRangeAndFunctionId(startTime, endTime, functionId, true);
int origSize = totalAnomalies.size();
long start;
long end;
while (starts.hasMoreElements() && ends.hasMoreElements()) {
start = ISODateTimeFormat.dateTimeParser().parseDateTime(starts.nextToken()).getMillis();
end = ISODateTimeFormat.dateTimeParser().parseDateTime(ends.nextToken()).getMillis();
List<MergedAnomalyResultDTO> holidayMergedAnomalies = anomalyMergedResultDAO.findByStartTimeInRangeAndFunctionId(start, end, functionId, true);
totalAnomalies.removeAll(holidayMergedAnomalies);
}
if(starts.hasMoreElements() || ends.hasMoreElements()) {
LOG.warn("Input holiday starts and ends length not equal!");
}
LOG.info("Removed {} merged anomalies", origSize - totalAnomalies.size());
return totalAnomalies;
}
/**
*
* @param ids a list of anomaly function ids, separate by comma, id1,id2,id3
* @param startTimeIso start time of anomalies to tune alert filter in ISO format ex: 2016-5-23T00:00:00Z
* @param endTimeIso end time of anomalies to tune alert filter in ISO format ex: 2016-5-23T00:00:00Z
* @param autoTuneType the type of auto tune to invoke (default is "AUTOTUNE")
* @param holidayStarts: holidayStarts in ISO Format, ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param holidayEnds: holidayEnds in in ISO Format, ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param features: a list of features separated by comma, ex: weight,score.
* Note that, the feature must be a existing field name in MergedAnomalyResult or a pre-set feature name
* @param pattern: users' customization on pattern. Format can be one of them: "UP", "DOWN" or "UP,DOWN"
* @param mttd: mttd string to specify severity on minimum-time-to-detection. Format example: "window_size_in_hour=2.5;weight=0.3"
* @return HTTP response of request: a list of autotune config id
*/
@POST
@Path("/autotune/filter/{functionIds}")
public Response tuneAlertFilter(@PathParam("functionIds") String ids,
@QueryParam("start") String startTimeIso,
@QueryParam("end") String endTimeIso,
@QueryParam("autoTuneType") @DefaultValue("AUTOTUNE") String autoTuneType,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds,
@QueryParam("tuningFeatures") String features,
@QueryParam("mttd") String mttd,
@QueryParam("pattern") String pattern) {
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
// get anomalies by function id, start time and end time
List<MergedAnomalyResultDTO> anomalies = new ArrayList<>();
List<Long> anomalyFunctionIds = new ArrayList<>();
for (String idString : ids.split(",")) {
long id = Long.valueOf(idString);
AnomalyFunctionDTO anomalyFunctionSpec = DAO_REGISTRY.getAnomalyFunctionDAO().findById(id);
if (anomalyFunctionSpec == null) {
LOG.warn("Anomaly detection function id {} doesn't exist", id);
continue;
}
anomalyFunctionIds.add(id);
anomalies.addAll(
getMergedAnomaliesRemoveHolidays(id, startTime, endTime, holidayStarts, holidayEnds));
}
if (anomalyFunctionIds.isEmpty()) {
return Response.status(Status.BAD_REQUEST).entity("No valid function ids").build();
}
// create alert filter auto tune
AutotuneConfigDTO autotuneConfig = new AutotuneConfigDTO();
Properties autotuneProperties = autotuneConfig.getTuningProps();
// if new feature set being specified
if (StringUtils.isNotBlank(features)) {
String previousFeatures = autotuneProperties.getProperty(AUTOTUNE_FEATURE_KEY);
LOG.info("The previous features for autotune is {}; now change to {}", previousFeatures, features);
autotuneProperties.setProperty(AUTOTUNE_FEATURE_KEY, features);
autotuneConfig.setTuningProps(autotuneProperties);
}
// if new pattern being specified
if (StringUtils.isNotBlank(pattern)) {
String previousPattern = autotuneProperties.getProperty(AUTOTUNE_PATTERN_KEY);
LOG.info("The previous pattern for autotune is {}; now changed to {}", previousPattern, pattern);
autotuneProperties.setProperty(AUTOTUNE_PATTERN_KEY, pattern);
autotuneConfig.setTuningProps(autotuneProperties);
}
// if new mttd requirement specified
if (StringUtils.isNotBlank(mttd)) {
String previousMttd = autotuneProperties.getProperty(AUTOTUNE_MTTD_KEY);
LOG.info("The previous mttd for autotune is {}; now changed to {}", previousMttd, mttd);
autotuneProperties.setProperty(AUTOTUNE_MTTD_KEY, mttd);
autotuneConfig.setTuningProps(autotuneProperties);
}
BaseAlertFilterAutoTune alertFilterAutotune = alertFilterAutotuneFactory.fromSpec(autoTuneType, autotuneConfig, anomalies);
LOG.info("initiated alertFilterAutoTune of Type {}", alertFilterAutotune.getClass().toString());
// tune
try {
Map<String, String> tunedAlertFilter = alertFilterAutotune.tuneAlertFilter();
LOG.info("Tuned alert filter with configurations: {}", tunedAlertFilter);
} catch (Exception e) {
LOG.warn("Exception when tuning alert filter: {}", e.getMessage());
}
// write to DB
List<Long> autotuneIds = new ArrayList<>();
for (long functionId : anomalyFunctionIds) {
autotuneConfig.setId(null);
autotuneConfig.setFunctionId(functionId);
long autotuneId = DAO_REGISTRY.getAutotuneConfigDAO().save(autotuneConfig);
autotuneIds.add(autotuneId);
}
try {
String autotuneIdsJson = OBJECT_MAPPER.writeValueAsString(autotuneIds);
return Response.ok(autotuneIdsJson).build();
} catch (JsonProcessingException e) {
LOG.error("Failed to covert autotune ID list to Json String. Property: {}.", autotuneIds.toString(), e);
return Response.serverError().build();
}
}
/**
* Endpoint to check if merged anomalies given a time period have at least one positive label
* @param id functionId to test anomalies
* @param startTimeIso start time to check anomaly history labels in ISO format ex: 2016-5-23T00:00:00Z
* @param endTimeIso end time to check anomaly history labels in ISO format ex: 2016-5-23T00:00:00Z
* @param holidayStarts optional: holidayStarts in ISO format as string, ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param holidayEnds optional:holidayEnds in ISO format as string, ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @return true if the list of merged anomalies has at least one positive label, false otherwise
*/
@POST
@Path("/initautotune/checkhaslabel/{functionId}")
public Response checkAnomaliesHasLabel(@PathParam("functionId") long id,
@QueryParam("start") String startTimeIso,
@QueryParam("end") String endTimeIso,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds) {
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
List<MergedAnomalyResultDTO> anomalyResultDTOS = getMergedAnomaliesRemoveHolidays(id, startTime, endTime, holidayStarts, holidayEnds);
return Response.ok(AnomalyUtils.checkHasLabels(anomalyResultDTOS)).build();
}
/**
* End point to trigger initiate alert filter auto tune
* @param id functionId to initiate alert filter auto tune
* @param startTimeIso: training data starts time ex: 2016-5-23T00:00:00Z
* @param endTimeIso: training data ends time ex: 2016-5-23T00:00:00Z
* @param autoTuneType: By default is "AUTOTUNE"
* @param holidayStarts optional: holidayStarts in ISO format: start1,start2,...
* @param holidayEnds optional:holidayEnds in ISO format: end1,end2,...
* @return true if alert filter has successfully being initiated, false otherwise
*/
@POST
@Path("/initautotune/filter/{functionId}")
public Response initiateAlertFilterAutoTune(@PathParam("functionId") long id,
@QueryParam("start") String startTimeIso,
@QueryParam("end") String endTimeIso,
@QueryParam("autoTuneType") @DefaultValue("AUTOTUNE") String autoTuneType,
@QueryParam("userDefinedPattern") @DefaultValue("UP,DOWN") String userDefinedPattern,
@QueryParam("Sensitivity") @DefaultValue("MEDIUM") String sensitivity,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds) {
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
// get anomalies by function id, start time and end time
List<MergedAnomalyResultDTO> anomalies = getMergedAnomaliesRemoveHolidays(id, startTime, endTime, holidayStarts, holidayEnds);
//initiate AutoTuneConfigDTO
Properties tuningProperties = new Properties();
tuningProperties.put("pattern", userDefinedPattern);
tuningProperties.put("sensitivity", sensitivity);
AutotuneConfigDTO autotuneConfig = new AutotuneConfigDTO(tuningProperties);
// create alert filter auto tune
BaseAlertFilterAutoTune alertFilterAutotune = alertFilterAutotuneFactory.fromSpec(autoTuneType, autotuneConfig, anomalies);
LOG.info("initiated alertFilterAutoTune of Type {}", alertFilterAutotune.getClass().toString());
String autotuneId = null;
// tune
try {
Map<String, String> tunedAlertFilterConfig = alertFilterAutotune.tuneAlertFilter();
LOG.info("Get tunedAlertFilter: {}", tunedAlertFilterConfig);
} catch (Exception e) {
LOG.warn("Exception when tune alert filter, {}", e.getMessage());
}
// write to DB
autotuneConfig.setFunctionId(id);
autotuneConfig.setAutotuneMethod(AutotuneMethodType.INITIATE_ALERT_FILTER_LOGISTIC_AUTO_TUNE);
autotuneId = DAO_REGISTRY.getAutotuneConfigDAO().save(autotuneConfig).toString();
return Response.ok(autotuneId).build();
}
/**
* The endpoint to evaluate system performance. The evaluation will be based on sent and non sent anomalies
* @param id: function ID
* @param startTimeIso: startTime of merged anomaly ex: 2016-5-23T00:00:00Z
* @param endTimeIso: endTime of merged anomaly ex: 2016-5-23T00:00:00Z
* @param isProjected: Boolean to indicate is to return projected performance for current alert filter.
* If "true", return projected performance for current alert filter
* @return feedback summary, precision and recall as json object
* @throws Exception when data has no positive label or model has no positive prediction
*/
@GET
@Path("/eval/filter/{functionId}")
public Response evaluateAlertFilterByFunctionId(@PathParam("functionId") long id,
@QueryParam("start") @NotNull String startTimeIso,
@QueryParam("end") @NotNull String endTimeIso,
@QueryParam("isProjected") @DefaultValue("false") String isProjected,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds) {
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
// get anomalies by function id, start time and end time`
AnomalyFunctionDTO anomalyFunctionSpec = DAO_REGISTRY.getAnomalyFunctionDAO().findById(id);
List<MergedAnomalyResultDTO> anomalyResultDTOS =
getMergedAnomaliesRemoveHolidays(id, startTime, endTime, holidayStarts, holidayEnds);
PrecisionRecallEvaluator evaluator;
if (Boolean.valueOf(isProjected)) {
// create alert filter and evaluator
AlertFilter alertFilter = alertFilterFactory.fromSpec(anomalyFunctionSpec.getAlertFilter());
//evaluate current alert filter (calculate current precision and recall)
evaluator = new PrecisionRecallEvaluator(alertFilter, anomalyResultDTOS);
LOG.info("AlertFilter of Type {}, has been evaluated with precision: {}, recall:{}", alertFilter.getClass().toString(),
evaluator.getWeightedPrecision(), evaluator.getRecall());
} else {
evaluator = new PrecisionRecallEvaluator(anomalyResultDTOS);
}
Map<String, Number> evaluatorValues = evaluator.toNumberMap();
try {
String propertiesJson = OBJECT_MAPPER.writeValueAsString(evaluatorValues);
return Response.ok(propertiesJson).build();
} catch (JsonProcessingException e) {
LOG.error("Failed to covert evaluator values to a Json String. Property: {}.", evaluatorValues.toString(), e);
return Response.serverError().build();
}
}
/**
* To evaluate alert filte directly by autotune Id using autotune_config_index table
* This is to leverage the intermediate step before updating tuned alert filter configurations
* @param id: autotune Id
* @param startTimeIso: merged anomalies start time. ex: 2016-5-23T00:00:00Z
* @param endTimeIso: merged anomalies end time ex: 2016-5-23T00:00:00Z
* @param holidayStarts: holiday starts time to remove merged anomalies in ISO format. ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param holidayEnds: holiday ends time to remove merged anomlaies in ISO format. ex: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @return HTTP response of evaluation results
*/
@GET
@Path("/eval/autotune/{autotuneId}")
public Response evaluateAlertFilterByAutoTuneId(@PathParam("autotuneId") long id,
@QueryParam("start") @NotNull String startTimeIso, @QueryParam("end") @NotNull String endTimeIso,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds) {
long startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
long endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
AutotuneConfigDTO target = DAO_REGISTRY.getAutotuneConfigDAO().findById(id);
long functionId = target.getFunctionId();
List<MergedAnomalyResultDTO> anomalyResultDTOS =
getMergedAnomaliesRemoveHolidays(functionId, startTime, endTime, holidayStarts, holidayEnds);
Map<String, String> alertFilterParams = target.getConfiguration();
AlertFilter alertFilter = alertFilterFactory.fromSpec(alertFilterParams);
PrecisionRecallEvaluator evaluator = new PrecisionRecallEvaluator(alertFilter, anomalyResultDTOS);
Map<String, Number> evaluatorValues = evaluator.toNumberMap();
try {
String propertiesJson = OBJECT_MAPPER.writeValueAsString(evaluatorValues);
return Response.ok(propertiesJson).build();
} catch (JsonProcessingException e) {
LOG.error("Failed to covert evaluator values to a Json String. Property: {}.", evaluatorValues.toString(), e);
return Response.serverError().build();
}
}
/**
* Perform anomaly function autotune:
* - run backfill on all possible combinations of tuning parameters
* - keep all the parameter combinations which lie in the goal range
* - return list of parameter combinations along with their performance evaluation
* @param functionId
* the id of the target anomaly function
* @param replayTimeIso
* the end time of the anomaly function replay in ISO format, e.g. 2017-02-27T00:00:00.000Z
* @param replayDuration
* the duration of the replay ahead of the replayStartTimeIso
* @param durationUnit
* the time unit of the duration, DAYS, HOURS, MINUTES and so on
* @param speedup
* whether we speedup the replay process
* @param tuningJSON
* the json object includes all tuning fields and list of parameters
* ex: {"baselineLift": [0.9, 0.95, 1, 1.05, 1.1], "baselineSeasonalPeriod": [2, 3, 4]}
* @param goal
* the expected performance assigned by user
* @param includeOrigin
* to include the performance of original setup into comparison
* If we perform offline analysis before hand, we don't get the correct performance about the current configuration
* setup. Therefore, we need to exclude the performance from the comparison.
* @return
* A response containing all satisfied properties with their evaluation result
*/
@Deprecated
@POST
@Path("replay/function/{id}")
public Response anomalyFunctionReplay(@PathParam("id") @NotNull long functionId,
@QueryParam("time") String replayTimeIso, @QueryParam("duration") @DefaultValue("30") int replayDuration,
@QueryParam("durationUnit") @DefaultValue("DAYS") String durationUnit,
@QueryParam("speedup") @DefaultValue("true") boolean speedup,
@QueryParam("tune") @DefaultValue("{\"pValueThreshold\":[0.05, 0.01]}") String tuningJSON,
@QueryParam("goal") @DefaultValue("0.05") double goal,
@QueryParam("includeOriginal") @DefaultValue("true") boolean includeOrigin,
@QueryParam("evalMethod") @DefaultValue("ANOMALY_PERCENTAGE") String performanceEvaluationMethod) {
AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId);
if (anomalyFunction == null) {
LOG.warn("Unable to find anomaly function {}", functionId);
return Response.status(Response.Status.BAD_REQUEST).entity("Cannot find function").build();
}
DateTime replayStart = null;
DateTime replayEnd = null;
try {
TimeUnit timeUnit = TimeUnit.valueOf(durationUnit.toUpperCase());
TimeGranularity timeGranularity = new TimeGranularity(replayDuration, timeUnit);
replayEnd = DateTime.now();
if (StringUtils.isNotEmpty(replayTimeIso)) {
replayEnd = ISODateTimeFormat.dateTimeParser().parseDateTime(replayTimeIso);
}
replayStart = replayEnd.minus(timeGranularity.toPeriod());
} catch (Exception e) {
throw new WebApplicationException("Unable to parse strings, " + replayTimeIso
+ ", in ISO DateTime format", e);
}
// List all tuning parameter sets
List<Map<String, String>> tuningParameters = null;
try {
tuningParameters = listAllTuningParameters(new JSONObject(tuningJSON));
} catch(JSONException e) {
LOG.error("Unable to parse json string: {}", tuningJSON, e );
return Response.status(Response.Status.BAD_REQUEST).build();
}
if (tuningParameters.size() == 0) { // no tuning combinations
LOG.warn("No tuning parameter is found in json string {}", tuningJSON);
return Response.status(Response.Status.BAD_REQUEST).build();
}
AutotuneMethodType autotuneMethodType = AutotuneMethodType.EXHAUSTIVE;
PerformanceEvaluationMethod performanceEvalMethod = PerformanceEvaluationMethod.valueOf(performanceEvaluationMethod.toUpperCase());
Map<String, Double> originalPerformance = new HashMap<>();
originalPerformance.put(performanceEvalMethod.name(),
PerformanceEvaluateHelper.getPerformanceEvaluator(performanceEvalMethod, functionId, functionId,
new Interval(replayStart.getMillis(), replayEnd.getMillis()), mergedAnomalyResultDAO).evaluate());
// select the functionAutotuneConfigDTO in DB
//TODO: override existing autotune results by a method "autotuneConfigDAO.udpate()"
AutotuneConfigDTO targetDTO = null;
List<AutotuneConfigDTO> functionAutoTuneConfigDTOList =
autotuneConfigDAO.findAllByFuctionIdAndWindow(functionId,replayStart.getMillis(), replayEnd.getMillis());
for (AutotuneConfigDTO configDTO : functionAutoTuneConfigDTOList) {
if(configDTO.getAutotuneMethod().equals(autotuneMethodType) &&
configDTO.getPerformanceEvaluationMethod().equals(performanceEvalMethod) &&
configDTO.getStartTime() == replayStart.getMillis() && configDTO.getEndTime() == replayEnd.getMillis() &&
configDTO.getGoal() == goal) {
targetDTO = configDTO;
break;
}
}
if (targetDTO == null) { // Cannot find existing dto
targetDTO = new AutotuneConfigDTO();
targetDTO.setFunctionId(functionId);
targetDTO.setAutotuneMethod(autotuneMethodType);
targetDTO.setPerformanceEvaluationMethod(performanceEvalMethod);
targetDTO.setStartTime(replayStart.getMillis());
targetDTO.setEndTime(replayEnd.getMillis());
targetDTO.setGoal(goal);
autotuneConfigDAO.save(targetDTO);
}
// clear message;
targetDTO.setMessage("");
if (includeOrigin) {
targetDTO.setPerformance(originalPerformance);
} else {
targetDTO.setPerformance(Collections.EMPTY_MAP);
}
autotuneConfigDAO.update(targetDTO);
// Setup threads and start to run
for(Map<String, String> config : tuningParameters) {
LOG.info("Running backfill replay with parameter configuration: {}" + config.toString());
FunctionReplayRunnable backfillRunnable = new FunctionReplayRunnable(detectionJobScheduler, anomalyFunctionDAO,
mergedAnomalyResultDAO, rawAnomalyResultDAO, autotuneConfigDAO);
backfillRunnable.setTuningFunctionId(functionId);
backfillRunnable.setFunctionAutotuneConfigId(targetDTO.getId());
backfillRunnable.setReplayStart(replayStart);
backfillRunnable.setReplayEnd(replayEnd);
backfillRunnable.setForceBackfill(true);
backfillRunnable.setGoal(goal);
backfillRunnable.setSpeedUp(speedup);
backfillRunnable.setPerformanceEvaluationMethod(performanceEvalMethod);
backfillRunnable.setAutotuneMethodType(autotuneMethodType);
backfillRunnable.setTuningParameter(config);
new Thread(backfillRunnable).start();
}
return Response.ok(targetDTO.getId()).build();
}
/**
* Parse the jsonobject and list all the possible configuration combinations
* @param tuningJSON the input json string from user
* @return full list of all the possible configurations
* @throws JSONException
*/
private List<Map<String, String>> listAllTuningParameters(JSONObject tuningJSON) throws JSONException {
List<Map<String, String>> tuningParameters = new ArrayList<>();
Iterator<String> jsonFieldIterator = tuningJSON.keys();
Map<String, List<String>> fieldToParams = new HashMap<>();
int numPermutations = 1;
while (jsonFieldIterator.hasNext()) {
String field = jsonFieldIterator.next();
if (field != null && !field.isEmpty()) {
// JsonArray to String List
List<String> params = new ArrayList<>();
JSONArray paramArray = tuningJSON.getJSONArray(field);
if (paramArray.length() == 0) {
continue;
}
for (int i = 0; i < paramArray.length(); i++) {
params.add(paramArray.get(i).toString());
}
numPermutations *= params.size();
fieldToParams.put(field, params);
}
}
if (fieldToParams.size() == 0) { // No possible tuning parameters
return tuningParameters;
}
List<String> fieldList = new ArrayList<>(fieldToParams.keySet());
for (int i = 0; i < numPermutations; i++) {
Map<String, String> combination = new HashMap<>();
int index = i;
for (String field : fieldList) {
List<String> params = fieldToParams.get(field);
combination.put(field, params.get(index % params.size()));
index /= params.size();
}
tuningParameters.add(combination);
}
return tuningParameters;
}
/**
* Single function Reply to generate anomalies given a time range
* Given anomaly function Id, or auto tuned Id, start time, end time, it clones a function with same configurations and replays from start time to end time
* Replay function with input auto tuned configurations and save the cloned function
* @param functionId functionId to be replayed
* @param autotuneId autotuneId that has auto tuned configurations as well as original functionId. If autotuneId is provided, the replay will apply auto tuned configurations to the auto tuned function
* If both functionId and autotuneId are provided, use autotuneId as principal
* Either functionId or autotuneId should be not null to provide function information, if functionId is not aligned with autotuneId's function, use all function information from autotuneId
* @param replayStartTimeIso replay start time in ISO format, e.g. 2017-02-27T00:00:00.000Z, replay start time inclusive
* @param replayEndTimeIso replay end time, e.g. 2017-02-27T00:00:00.000Z, replay end time exclusive
* @param speedUp boolean to determine should we speed up the replay process (by maximizing detection window size)
* @return cloned function Id
*/
@Deprecated
@POST
@Path("/replay/singlefunction")
public Response replayAnomalyFunctionByFunctionId(@QueryParam("functionId") Long functionId,
@QueryParam("autotuneId") Long autotuneId,
@QueryParam("start") @NotNull String replayStartTimeIso,
@QueryParam("end") @NotNull String replayEndTimeIso,
@QueryParam("speedUp") @DefaultValue("true") boolean speedUp) {
if (functionId == null && autotuneId == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
DateTime replayStart;
DateTime replayEnd;
try {
replayStart = ISODateTimeFormat.dateTimeParser().parseDateTime(replayStartTimeIso);
replayEnd = ISODateTimeFormat.dateTimeParser().parseDateTime(replayEndTimeIso);
} catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity("Input start and end time illegal! ").build();
}
FunctionReplayRunnable functionReplayRunnable;
AutotuneConfigDTO target = null;
if (autotuneId != null) {
target = DAO_REGISTRY.getAutotuneConfigDAO().findById(autotuneId);
functionReplayRunnable = new FunctionReplayRunnable(detectionJobScheduler, anomalyFunctionDAO, mergedAnomalyResultDAO, rawAnomalyResultDAO, target.getConfiguration(), target.getFunctionId(), replayStart, replayEnd, false);
} else {
functionReplayRunnable = new FunctionReplayRunnable(detectionJobScheduler, anomalyFunctionDAO, mergedAnomalyResultDAO, rawAnomalyResultDAO, new HashMap<String, String>(), functionId, replayStart, replayEnd, false);
}
functionReplayRunnable.setSpeedUp(speedUp);
functionReplayRunnable.run();
Map<String, String> responseMessages = new HashMap<>();
responseMessages.put("cloneFunctionId", String.valueOf(functionReplayRunnable.getLastClonedFunctionId()));
if (target != null && functionId != null && functionId != target.getFunctionId()) {
responseMessages.put("Warning", "Input function Id does not consistent with autotune Id's function, use auto tune Id's information instead.");
}
return Response.ok(responseMessages).build();
}
/**
* Given alert filter autotune Id, update to function spec
* @param id alert filte autotune id
* @return function Id being updated
*/
@POST
@Path("/update/filter/{autotuneId}")
public Response updateAlertFilterToFunctionSpecByAutoTuneId(@PathParam("autotuneId") long id) {
AutotuneConfigDTO target = DAO_REGISTRY.getAutotuneConfigDAO().findById(id);
long functionId = target.getFunctionId();
AnomalyFunctionManager anomalyFunctionDAO = DAO_REGISTRY.getAnomalyFunctionDAO();
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(functionId);
anomalyFunctionSpec.setAlertFilter(target.getConfiguration());
anomalyFunctionDAO.update(anomalyFunctionSpec);
return Response.ok(functionId).build();
}
/**
* Extract alert filter boundary given auto tune Id
* @param id autotune Id
* @return alert filter boundary in json format
*/
@POST
@Path("/eval/autotuneboundary/{autotuneId}")
public Response getAlertFilterBoundaryByAutoTuneId(@PathParam("autotuneId") long id) {
AutotuneConfigDTO target = DAO_REGISTRY.getAutotuneConfigDAO().findById(id);
return Response.ok(target.getConfiguration()).build();
}
/**
* Extract alert filter training data
* @param id alert filter autotune id
* @param startTimeIso: alert filter trainig data start time in ISO format: e.g. 2017-02-27T00:00:00.000Z
* @param endTimeIso: alert filter training data end time in ISO format
* @param holidayStarts holiday starts time in ISO format to remove merged anomalies: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @param holidayEnds holiday ends time in ISO format to remove merged anomalies: 2016-5-23T00:00:00Z,2016-6-23T00:00:00Z,...
* @return training data in json format
*/
@POST
@Path("/eval/autotunemetadata/{autotuneId}")
public Response getAlertFilterMetaDataByAutoTuneId(@PathParam("autotuneId") long id,
@QueryParam("start") String startTimeIso, @QueryParam("end") String endTimeIso,
@QueryParam("holidayStarts") @DefaultValue("") String holidayStarts,
@QueryParam("holidayEnds") @DefaultValue("") String holidayEnds) {
long startTime;
long endTime;
try {
startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis();
endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis();
} catch (Exception e) {
throw new WebApplicationException("Unable to parse strings, " + startTimeIso + " and " + endTimeIso
+ ", in ISO DateTime format", e);
}
AutotuneConfigDTO target = DAO_REGISTRY.getAutotuneConfigDAO().findById(id);
long functionId = target.getFunctionId();
List<MergedAnomalyResultDTO> anomalyResultDTOS =
getMergedAnomaliesRemoveHolidays(functionId, startTime, endTime, holidayStarts, holidayEnds);
List<AnomalyUtils.MetaDataNode> metaData = new ArrayList<>();
for (MergedAnomalyResultDTO anomaly: anomalyResultDTOS) {
metaData.add(new AnomalyUtils.MetaDataNode(anomaly));
}
return Response.ok(metaData).build();
}
/**
* Get Minimum Time to Detection for Function.
* This endpoint evaluate both alert filter's MTTD and bucket size for function and returns the maximum of the two as MTTD
* @param id function Id to be evaluated
* @param severity severity value
* @return minimum time to detection in HOUR
*/
@GET
@Path("/eval/mttd/{functionId}")
public Response getAlertFilterMTTD (@PathParam("functionId") @NotNull long id,
@QueryParam("severity") @NotNull double severity) {
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(id);
BaseAlertFilter alertFilter = alertFilterFactory.fromSpec(anomalyFunctionSpec.getAlertFilter());
double alertFilterMTTDInHour = alertFilter.getAlertFilterMTTD(severity);
TimeUnit detectionUnit = anomalyFunctionSpec.getBucketUnit();
int detectionBucketSize = anomalyFunctionSpec.getBucketSize();
double functionMTTDInHour = TimeUnit.HOURS.convert(detectionBucketSize, detectionUnit);
return Response.ok(Math.max(functionMTTDInHour, alertFilterMTTDInHour)).build();
}
/**
* Get Minimum Time to Detection for Autotuned (Preview) Alert Filter.
* This endpoint evaluate both alert filter's MTTD and bucket size for function and returns the maximum of the two as MTTD
* @param id autotune Id to be evaluated
* @param severity severity value
* @return minimum time to detection in HOUR
*/
@GET
@Path("/eval/projected/mttd/{autotuneId}")
public Response getProjectedMTTD (@PathParam("autotuneId") @NotNull long id,
@QueryParam("severity") @NotNull double severity) {
//Initiate tuned alert filter
AutotuneConfigDTO target = DAO_REGISTRY.getAutotuneConfigDAO().findById(id);
Map<String, String> tunedParams = target.getConfiguration();
BaseAlertFilter alertFilter = alertFilterFactory.fromSpec(tunedParams);
// Get current function
long functionId = target.getFunctionId();
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(functionId);
double alertFilterMTTDInHour = alertFilter.getAlertFilterMTTD(severity);
TimeUnit detectionUnit = anomalyFunctionSpec.getBucketUnit();
int detectionBucketSize = anomalyFunctionSpec.getBucketSize();
double functionMTTDInHour = TimeUnit.HOURS.convert(detectionBucketSize, detectionUnit);
return Response.ok(Math.max(functionMTTDInHour, alertFilterMTTDInHour)).build();
}
}
|
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.BaseTemplateModel;
public class PropertyGroupTemplateModel extends BaseTemplateModel {
private static final Log log = LogFactory.getLog(PropertyGroupTemplateModel.class);
private final String name;
private final List<PropertyTemplateModel> properties;
PropertyGroupTemplateModel(VitroRequest vreq, PropertyGroup group,
Individual subject, boolean editing,
List<DataProperty> populatedDataPropertyList,
List<ObjectProperty> populatedObjectPropertyList) {
this.name = group.getName();
List<Property> propertyList = group.getPropertyList();
properties = new ArrayList<PropertyTemplateModel>(propertyList.size());
for (Property p : propertyList) {
if (p instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) p;
RequestedAction dop = new DisplayObjectProperty(op);
if (!PolicyHelper.isAuthorizedForActions(vreq, dop)) {
continue;
}
ObjectPropertyTemplateModel tm = ObjectPropertyTemplateModel.getObjectPropertyTemplateModel(
op, subject, vreq, editing, populatedObjectPropertyList);
if (!tm.isEmpty() || (editing && !tm.getAddUrl().isEmpty())) {
properties.add(tm);
}
} else if (p instanceof DataProperty){
DataProperty dp = (DataProperty) p;
RequestedAction dop = new DisplayDataProperty(dp);
if (!PolicyHelper.isAuthorizedForActions(vreq, dop)) {
continue;
}
properties.add(new DataPropertyTemplateModel(dp, subject, vreq, editing, populatedDataPropertyList));
} else {
log.debug(p.getURI() + " is neither an ObjectProperty nor a DataProperty; skipping display");
}
}
}
protected boolean isEmpty() {
return properties.isEmpty();
}
protected void remove(PropertyTemplateModel ptm) {
properties.remove(ptm);
}
public String toString(){
String ptmStr ="";
for( int i=0; i < properties.size() ; i ++ ){
PropertyTemplateModel ptm = properties.get(i);
String spacer = "\n ";
if( ptm != null )
ptmStr = ptmStr + spacer + ptm.toString();
}
return String.format("\nPropertyGroupTemplateModel %s[%s] ",name, ptmStr );
}
/* Accessor methods for templates */
// Add this so it's included in dumps for debugging. The templates will want to display
// name using getName(String)
public String getName() {
return name;
}
public String getName(String otherGroupName) {
if (name == null || name.isEmpty()) {
return otherGroupName;
} else {
return name;
}
}
public List<PropertyTemplateModel> getProperties() {
return properties;
}
}
|
package won.protocol.agreement;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import org.apache.thrift.Option;
import won.protocol.agreement.effect.MessageEffect;
import won.protocol.message.WonMessageDirection;
import won.protocol.message.WonMessageType;
/**
*
* @author fkleedorfer
*
*/
public class ConversationMessage implements Comparable<ConversationMessage>{
URI messageURI;
URI senderNeedURI;
Set<URI> proposes = new HashSet<>();
Set<ConversationMessage> proposesRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> proposesInverseRefs = new HashSet<ConversationMessage>();
Set<URI> rejects = new HashSet<>();
Set<ConversationMessage> rejectsRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> rejectsInverseRefs = new HashSet<ConversationMessage>();
Set<URI> previous = new HashSet<>();
Set<ConversationMessage> previousRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> previousInverseRefs = new HashSet<ConversationMessage>();
Set<URI> accepts = new HashSet<>();
Set<ConversationMessage> acceptsRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> acceptsInverseRefs = new HashSet<ConversationMessage>();
Set<URI> retracts = new HashSet<>();
Set<ConversationMessage> retractsRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> retractsInverseRefs = new HashSet<ConversationMessage>();
Set<URI> proposesToCancel = new HashSet<>();
Set<ConversationMessage> proposesToCancelRefs = new HashSet<ConversationMessage>();
Set<ConversationMessage> proposesToCancelInverseRefs = new HashSet<ConversationMessage>();
Set<URI> contentGraphs = new HashSet<>();
Option<ConversationMessage> conversationRoot = Option.none();
URI correspondingRemoteMessageURI;
ConversationMessage correspondingRemoteMessageRef;
URI isResponseTo;
Optional<ConversationMessage> isResponseToOption;
ConversationMessage isResponseToInverseRef;
URI isRemoteResponseTo;
ConversationMessage isRemoteResponseToRef;
ConversationMessage isRemoteResponseToInverseRef;
WonMessageType messageType ;
WonMessageDirection direction;
DeliveryChain deliveryChain;
private OptionalInt minDistanceToOwnRoot = OptionalInt.empty();
private OptionalInt maxDistanceToOwnRoot = OptionalInt.empty();
private OptionalInt order = OptionalInt.empty();
private Set<ConversationMessage> knownMessagesOnPathToRoot = new HashSet<ConversationMessage>();
private Set<MessageEffect> effects = Collections.EMPTY_SET;
public ConversationMessage(URI messageURI) {
this.messageURI = messageURI;
}
/**
* Removes all proposes, rejects, accepts, proposesToCancel, contentGraphs
*/
public void removeHighlevelProtocolProperties() {
removeProposes();
removeAccepts();
removeProposesToCancel();
removeRejects();
removeRetracts();
}
private void removeProposes() {
this.proposes = new HashSet<>();
this.proposesRefs.forEach(other -> other.removeProposesInverseRef(this));
this.proposesRefs = new HashSet<>();
}
private void removeProposesInverseRef(ConversationMessage other) {
this.proposesInverseRefs.remove(other);
}
private void removeProposesToCancel() {
this.proposesToCancel = new HashSet<>();
this.proposesToCancelRefs.forEach(other -> other.removeProposesToCancelInverseRef(this));
this.proposesToCancelRefs = new HashSet<>();
}
private void removeProposesToCancelInverseRef(ConversationMessage other) {
this.proposesInverseRefs.remove(other);
}
private void removeAccepts() {
this.accepts = new HashSet<>();
this.acceptsRefs.forEach(other -> other.removeAcceptsInverseRef(this));
this.acceptsRefs = new HashSet<>();
}
private void removeAcceptsInverseRef(ConversationMessage other) {
this.proposesInverseRefs.remove(other);
}
private void removeRejects() {
this.rejects = new HashSet<>();
this.rejectsRefs.forEach(other -> other.removeRejectsInverseRef(this));
this.rejectsRefs = new HashSet<>();
}
private void removeRejectsInverseRef(ConversationMessage other) {
this.proposesInverseRefs.remove(other);
}
private void removeRetracts() {
this.retracts = new HashSet<>();
this.retractsRefs.forEach(other -> other.removeRetractsInverseRef(this));
this.retractsRefs = new HashSet<>();
}
private void removeRetractsInverseRef(ConversationMessage other) {
this.proposesInverseRefs.remove(other);
}
public ConversationMessage getRootOfDeliveryChain() {
return getDeliveryChain().getHead();
}
public boolean isHeadOfDeliveryChain() {
return isFromOwner() || (isFromSystem() && !isResponse()) || (!hasCorrespondingRemoteMessage() && ! isResponse());
}
public boolean isEndOfDeliveryChain() {
return this == getDeliveryChain().getEnd();
}
public boolean isInSameDeliveryChain(ConversationMessage other) {
return this.getDeliveryChain() == other.getDeliveryChain();
}
public DeliveryChain getDeliveryChain() {
if (this.deliveryChain != null) return deliveryChain;
if (this.isHeadOfDeliveryChain()) {
this.deliveryChain = new DeliveryChain();
this.deliveryChain.addMessage(this);
return this.deliveryChain;
}
if (isResponse() && getIsResponseToOption().isPresent()) {
this.deliveryChain = getIsResponseToOption().get().getDeliveryChain();
if (this.deliveryChain != null) {
this.deliveryChain.addMessage(this);
return deliveryChain;
}
}
if (hasCorrespondingRemoteMessage()) {
this.deliveryChain = getCorrespondingRemoteMessageRef().getDeliveryChain();
if (this.deliveryChain != null) {
this.deliveryChain.addMessage(this);
return deliveryChain;
}
}
throw new IllegalStateException("did not manage to obtain the delivery chain for message " + this.getMessageURI());
}
public boolean isResponse() {
return this.messageType == WonMessageType.SUCCESS_RESPONSE || this.messageType == WonMessageType.FAILURE_RESPONSE;
}
public boolean hasResponse() {
return this.isResponseToInverseRef != null;
}
public boolean hasRemoteResponse() {
return this.isRemoteResponseToInverseRef != null;
}
public boolean hasSuccessResponse() {
return hasResponse() && this.isResponseToInverseRef.getMessageType() == WonMessageType.SUCCESS_RESPONSE;
}
public boolean hasRemoteSuccessResponse() {
return hasRemoteResponse() && this.isRemoteResponseToInverseRef.getMessageType() == WonMessageType.SUCCESS_RESPONSE;
}
public boolean isAcknowledgedRemotely() {
boolean hsr = hasSuccessResponse();
boolean hcrm = hasCorrespondingRemoteMessage();
boolean hrsr = hcrm && correspondingRemoteMessageRef.hasSuccessResponse();
boolean hrr = hrsr && correspondingRemoteMessageRef.getIsResponseToInverseRef().hasCorrespondingRemoteMessage();
return hsr && hcrm && hrsr && hrr;
}
public boolean hasPreviousMessage() {
return ! this.getPreviousRefs().isEmpty();
}
public boolean hasSubsequentMessage() {
return !this.getPreviousInverseRefs().isEmpty();
}
public boolean isCorrespondingRemoteMessageOf(ConversationMessage other) {
return getCorrespondingRemoteMessageRef() == other;
}
public boolean isResponseTo(ConversationMessage other) {
return getIsRemoteResponseToRef() == other;
}
public boolean hasResponse(ConversationMessage other) {
return other.getIsResponseToOption().orElse(null) == this;
}
public boolean isRemoteResponseTo(ConversationMessage other) {
return getIsRemoteResponseToRef() == other;
}
public boolean hasRemoteResponse(ConversationMessage other) {
return other.getIsRemoteResponseToRef() == this;
}
public boolean partOfSameExchange(ConversationMessage other) {
return this.getDeliveryChain() == other.getDeliveryChain();
}
/**
* Compares messages for sorting them temporally, using the URI as tie breaker so as to ensure a stable ordering.
* @param other
* @return
*/
public int compareTo(ConversationMessage other) {
if (this == other) return 0;
int o1dist = this.getOrder();
int o2dist = other.getOrder();
if (o1dist != o2dist) {
return o1dist - o2dist;
}
if (this.isResponseTo(other)) return 1;
if (this.isRemoteResponseTo(other)) return 1;
if (this.isFromExternal() && this.isCorrespondingRemoteMessageOf(other)) return 1;
if (this.isInSameDeliveryChain(other)) {
if (this.isHeadOfDeliveryChain() || other.isEndOfDeliveryChain()) {
return -1;
}
if (this.isEndOfDeliveryChain() || other.isHeadOfDeliveryChain()) {
return 1;
}
}
//if we get to here, we should check if one of the delivery chains is earlier
return this.getMessageURI().compareTo(other.getMessageURI());
}
public int getOrder() {
if (this.order.isPresent()) {
return this.order.getAsInt();
}
OptionalInt mindist = getPreviousRefs()
.stream()
.mapToInt(msg -> msg.getOrder() + 1).min();
if (this.hasCorrespondingRemoteMessage() && this.isFromExternal()) {
this.order = OptionalInt.of(Math.max(mindist.orElse(0), getCorrespondingRemoteMessageRef().getOrder() +1));
} else {
this.order = OptionalInt.of(mindist.orElse(0));
}
return this.order.getAsInt();
}
public Option<ConversationMessage> getOwnConversationRoot() {
if (this.conversationRoot.isDefined()) {
return this.conversationRoot;
}
for (ConversationMessage prev: this.getPreviousRefs()) {
Option<ConversationMessage> root = prev.getOwnConversationRoot();
if (root.isDefined()) {
this.conversationRoot = Option.some(root.get());
return root;
}
}
this.conversationRoot = Option.some(this);
return this.conversationRoot;
}
public Set<ConversationMessage> getReachableConversationRoots(){
Set<ConversationMessage> roots = new HashSet<>();
Option<ConversationMessage> ownRoot = getOwnConversationRoot();
if (ownRoot.isDefined()) {
roots.add(ownRoot.get());
}
if (this.hasCorrespondingRemoteMessage()) {
Option<ConversationMessage> remoteRoot = getCorrespondingRemoteMessageRef().getOwnConversationRoot();
if (remoteRoot.isDefined()) {
roots.add(remoteRoot.get());
}
}
return roots;
}
public boolean sharesReachableRootsWith(ConversationMessage other) {
Set<ConversationMessage> myRoots = getReachableConversationRoots();
return other.getReachableConversationRoots()
.stream()
.anyMatch(root -> myRoots.contains(root));
}
public boolean isMessageOnPathToRoot(ConversationMessage other) {
if (this == other) return false;
boolean foundIt = isMessageOnPathToRoot(other, new HashSet<>());
return foundIt;
}
private boolean isMessageOnPathToRoot(ConversationMessage other, Set<ConversationMessage> visited) {
if (this == other) return true;
if (this.getOrder() < other.getOrder()) {
//if this is the case, it's impossible that the other message is on the path to root
return false;
}
if (this.knownMessagesOnPathToRoot.contains(other)) {
return true;
}
visited.add(this);
if (!this.hasPreviousMessage()) {
return false;
}
Boolean foundIt = getPreviousRefs().stream()
.filter(msg -> !visited.contains(msg))
.anyMatch(msg -> msg.isMessageOnPathToRoot(other, visited));
if (foundIt) {
this.knownMessagesOnPathToRoot.add(other);
return true;
}
if (this.hasCorrespondingRemoteMessage() && !visited.contains(this.getCorrespondingRemoteMessageRef())) {
return this.getCorrespondingRemoteMessageRef().isMessageOnPathToRoot(other, visited);
}
return false;
}
public boolean isAgreementProtocolMessage() {
return this.isRetractsMessage() || this.isProposesMessage() || this.isProposesToCancelMessage() || this.isAcceptsMessage() || this.isRejectsMessage();
}
public boolean isFromOwner() {
return this.direction == WonMessageDirection.FROM_OWNER;
}
public boolean isFromExternal() {
return this.direction == WonMessageDirection.FROM_EXTERNAL;
}
public boolean isFromSystem() {
return this.direction == WonMessageDirection.FROM_SYSTEM;
}
public boolean isAcknowledgedLocally() {
return hasSuccessResponse();
}
public boolean isRetractsMessage() {
return !this.retractsRefs.isEmpty();
}
public boolean isAcceptsMessage() {
return !this.acceptsRefs.isEmpty();
}
public boolean isProposesMessage() {
return !this.proposesRefs.isEmpty();
}
public boolean isRejectsMessage() {
return !this.rejectsRefs.isEmpty();
}
public boolean isProposesToCancelMessage() {
return !this.proposesToCancelRefs.isEmpty();
}
public boolean proposes(ConversationMessage other) {
return this.proposesRefs.contains(other);
}
public boolean accepts(ConversationMessage other) {
return this.acceptsRefs.contains(other);
}
public boolean proposesToCancel(ConversationMessage other) {
return this.proposesToCancelRefs.contains(other);
}
public boolean retracts(ConversationMessage other) {
return this.retractsRefs.contains(other);
}
public boolean rejects(ConversationMessage other) {
return this.rejectsRefs.contains(other);
}
public URI getMessageURI() {
return messageURI;
}
public URI getSenderNeedURI() {
return senderNeedURI;
}
public void setSenderNeedURI(URI senderNeedURI) {
this.senderNeedURI = senderNeedURI;
}
public Set<URI> getProposes() {
return proposes;
}
public Set<URI> getRejects() {
return rejects;
}
public Set<ConversationMessage> getProposesRefs(){
return proposesRefs;
}
public void addProposes(URI proposes) {
this.proposes.add(proposes);
}
public void addProposesRef(ConversationMessage ref) {
this.proposesRefs.add(ref);
}
public Set<ConversationMessage> getRejectsRefs(){
return rejectsRefs;
}
public void addRejects(URI rejects) {
this.rejects.add(rejects);
}
public void addRejectsRef(ConversationMessage ref) {
this.rejectsRefs.add(ref);
}
public Set<URI> getPrevious() {
return previous;
}
public Set<ConversationMessage> getPreviousRefs(){
return previousRefs;
}
public void addPrevious(URI previous) {
this.previous.add(previous);
}
public void addPreviousRef(ConversationMessage ref) {
this.previousRefs.add(ref);
}
public Set<URI> getAccepts() {
return accepts;
}
public Set<ConversationMessage> getAcceptsRefs(){
return this.acceptsRefs;
}
public void addAcceptsRef(ConversationMessage ref) {
this.acceptsRefs.add(ref);
}
public void addAccepts(URI accepts) {
this.accepts.add(accepts);
}
public Set<URI> getRetracts() {
return retracts;
}
public Set<ConversationMessage> getRetractsRefs(){
return this.retractsRefs;
}
public void addRetractsRef(ConversationMessage ref) {
this.retractsRefs.add(ref);
}
public void addRetracts(URI retracts) {
this.retracts.add(retracts);
}
public Set<URI> getProposesToCancel() {
return proposesToCancel;
}
public Set<ConversationMessage> getProposesToCancelRefs(){
return this.proposesToCancelRefs;
}
public void addProposesToCancelRef(ConversationMessage ref) {
this.proposesToCancelRefs.add(ref);
}
public void addProposesToCancel(URI proposesToCancel) {
this.proposesToCancel.add(proposesToCancel);
}
public URI getCorrespondingRemoteMessageURI() {
return correspondingRemoteMessageURI;
}
public ConversationMessage getCorrespondingRemoteMessageRef() {
return this.correspondingRemoteMessageRef;
}
public boolean hasCorrespondingRemoteMessage() {
return this.correspondingRemoteMessageRef != null;
}
public void setCorrespondingRemoteMessageURI(URI correspondingRemoteMessageURI) {
this.correspondingRemoteMessageURI = correspondingRemoteMessageURI;
}
public void setCorrespondingRemoteMessageRef(ConversationMessage ref) {
this.correspondingRemoteMessageRef = ref;
}
public URI getIsResponseTo() {
return isResponseTo;
}
public void setIsResponseTo(URI isResponseTo) {
this.isResponseTo = isResponseTo;
}
/**
* Return an optional conversation message here - it's possible that we only have the response, not the
* original one.
* @return
*/
public Optional<ConversationMessage> getIsResponseToOption() {
return isResponseToOption;
}
public void setIsResponseToRef(ConversationMessage ref) {
this.isResponseToOption = Optional.of(ref);
}
public URI getIsRemoteResponseTo() {
return isRemoteResponseTo;
}
public void setIsRemoteResponseTo(URI isRemoteResponseTo) {
this.isRemoteResponseTo = isRemoteResponseTo;
}
public ConversationMessage getIsRemoteResponseToRef() {
return isRemoteResponseToRef;
}
public void setIsRemoteResponseToRef(ConversationMessage ref) {
this.isRemoteResponseToRef = ref;
}
public Set<ConversationMessage> getProposesInverseRefs() {
return proposesInverseRefs;
}
public void addProposesInverseRef(ConversationMessage ref) {
this.proposesInverseRefs.add(ref);
}
public Set<ConversationMessage> getRejectsInverseRefs() {
return rejectsInverseRefs;
}
public void addRejectsInverseRef(ConversationMessage ref) {
this.rejectsInverseRefs.add(ref);
}
public Set<ConversationMessage> getPreviousInverseRefs() {
return previousInverseRefs;
}
public void addPreviousInverseRef(ConversationMessage ref) {
this.previousInverseRefs.add(ref);
}
public Set<ConversationMessage> getAcceptsInverseRefs() {
return acceptsInverseRefs;
}
public void addAcceptsInverseRef(ConversationMessage ref) {
this.acceptsInverseRefs.add(ref);
}
public Set<ConversationMessage> getRetractsInverseRefs() {
return retractsInverseRefs;
}
public void addRetractsInverseRef(ConversationMessage ref) {
this.retractsInverseRefs.add(ref);
}
public ConversationMessage getIsResponseToInverseRef() {
return isResponseToInverseRef;
}
public void setIsResponseToInverseRef(ConversationMessage ref) {
this.isResponseToInverseRef = ref;
}
public ConversationMessage getIsRemoteResponseToInverseRef() {
return isRemoteResponseToInverseRef;
}
public void setIsRemoteResponseToInverseRef(ConversationMessage ref) {
this.isRemoteResponseToInverseRef = ref;
}
public Set<ConversationMessage> getProposesToCancelInverseRefs() {
return proposesToCancelInverseRefs;
}
public void addProposesToCancelInverseRef(ConversationMessage ref) {
this.proposesToCancelInverseRefs.add(ref);
}
public Set<URI> getContentGraphs() {
return contentGraphs;
}
public void addContentGraph(URI contentGraph) {
this.contentGraphs.add(contentGraph);
}
public WonMessageType getMessageType() {
return messageType;
}
public void setMessageType(WonMessageType messageType) {
this.messageType = messageType;
}
public WonMessageDirection getDirection() {
return direction;
}
public void setDirection(WonMessageDirection direction) {
this.direction = direction;
}
public void setEffects(Set<MessageEffect> effects) {
this.effects = effects;
}
public Set<MessageEffect> getEffects() {
return effects;
}
@Override
public String toString() {
return "ConversationMessage [messageURI=" + messageURI
+ ", order=" + getOrder()
+ ", direction=" + direction
+ ", messageType=" + messageType
+ ", deliveryChainPosition:" + (this == getDeliveryChain().getHead() ? "head" : this == getDeliveryChain().getEnd() ? "end" : "middle")
+ ", deliveryChainHead:" + getDeliveryChain().getHeadURI()
+ ", senderNeedURI=" + senderNeedURI
+ ", proposes=" + proposes + ", proposesRefs:" + proposesRefs.size()
+ ", rejects=" + rejects + ", rejectsRefs:" + rejectsRefs.size()
+ ", previous=" + previous + ", previousRefs:"
+ previousRefs.size() + ", accepts=" + accepts + ", acceptsRefs:" + acceptsRefs.size() + ", retracts=" + retracts
+ ", retractsRefs:" + retractsRefs.size() + ", proposesToCancel=" + proposesToCancel
+ ", proposesToCancelRefs:" + proposesToCancelRefs.size() + ", correspondingRemoteMessageURI="
+ correspondingRemoteMessageURI + ", correspondingRemoteMessageRef=" + messageUriOrNullString(correspondingRemoteMessageRef)
+ ", isResponseTo= " +isResponseTo + ", isRemoteResponseTo=" + isRemoteResponseTo
+ ", isResponseToRef: " + messageUriOrNullString(isResponseToOption)
+ ", isRemoteResponseToRef:" + messageUriOrNullString(isRemoteResponseToRef)
+ ", isResponseToInverse: " + messageUriOrNullString(isResponseToInverseRef)
+ ", isRemoteResponseToInverse: " + messageUriOrNullString(isRemoteResponseToInverseRef)
+ "]";
}
private Object messageUriOrNullString(ConversationMessage message) {
return message != null? message.getMessageURI():"null";
}
private Object messageUriOrNullString(Optional<ConversationMessage> messageOpt) {
return (messageOpt.isPresent()) ? messageOpt.get().getMessageURI():"null";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((messageURI == null) ? 0 : messageURI.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConversationMessage other = (ConversationMessage) obj;
if (messageURI == null) {
if (other.messageURI != null)
return false;
} else if (!messageURI.equals(other.messageURI))
return false;
return true;
}
}
|
package com.xpn.xwiki.objects.classes;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.ecs.xhtml.input;
import org.apache.velocity.VelocityContext;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.hibernate.mapping.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.model.reference.ClassPropertyReference;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.template.Template;
import org.xwiki.template.TemplateManager;
import org.xwiki.velocity.VelocityManager;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Context;
import com.xpn.xwiki.api.DeprecatedContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.merge.MergeConfiguration;
import com.xpn.xwiki.doc.merge.MergeResult;
import com.xpn.xwiki.internal.template.SUExecutor;
import com.xpn.xwiki.internal.xml.XMLAttributeValueFilter;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.meta.MetaClass;
import com.xpn.xwiki.objects.meta.PropertyMetaClass;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.web.Utils;
/**
* Represents an XClass property and contains property definitions (eg "relational storage", "display type",
* "separator", "multi select", etc). Each property definition is of type {@link BaseProperty}.
*
* @version $Id$
*/
public class PropertyClass extends BaseCollection<ClassPropertyReference>
implements PropertyClassInterface, Comparable<PropertyClass>
{
/**
* Logging helper object.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(PropertyClass.class);
/**
* Identifier used to specify that the property has a custom displayer in the XClass itself.
*/
private static final String CLASS_DISPLAYER_IDENTIFIER = "class";
/**
* Identifier prefix used to specify that the property has a custom displayer in a wiki document.
*/
private static final String DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX = "doc:";
/**
* Identifier prefix used to specify that the property has a custom displayer in a velocity template.
*/
private static final String TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX = "template:";
private BaseClass xclass;
private long id;
private PropertyMetaClass pMetaClass;
protected String cachedCustomDisplayer;
public PropertyClass()
{
}
public PropertyClass(String name, String prettyname, PropertyMetaClass xWikiClass)
{
setName(name);
setPrettyName(prettyname);
setxWikiClass(xWikiClass);
setUnmodifiable(false);
setDisabled(false);
}
@Override
protected ClassPropertyReference createReference()
{
return new ClassPropertyReference(getName(), this.xclass.getReference());
}
@Override
public BaseClass getXClass(XWikiContext context)
{
return getxWikiClass();
}
public BaseClass getxWikiClass()
{
if (this.pMetaClass == null) {
MetaClass metaClass = MetaClass.getMetaClass();
this.pMetaClass = (PropertyMetaClass) metaClass.get(getClassType());
}
return this.pMetaClass;
}
public void setxWikiClass(BaseClass xWikiClass)
{
this.pMetaClass = (PropertyMetaClass) xWikiClass;
}
@Override
public BaseCollection getObject()
{
return this.xclass;
}
@Override
public void setObject(BaseCollection object)
{
this.xclass = (BaseClass) object;
}
public String getFieldFullName()
{
if (getObject() == null) {
return getName();
}
return getObject().getName() + "_" + getName();
}
@Override
public long getId()
{
if (getObject() == null) {
return this.id;
}
return getObject().getId();
}
@Override
public void setId(long id)
{
this.id = id;
}
@Override
public String toString(BaseProperty property)
{
return property.toText();
}
@Override
public BaseProperty fromString(String value)
{
return null;
}
public BaseProperty newPropertyfromXML(Element ppcel)
{
String value = ppcel.getText();
return fromString(value);
}
@Override
public void displayHidden(StringBuffer buffer, String name, String prefix, BaseCollection object,
XWikiContext context)
{
input input = new input();
input.setAttributeFilter(new XMLAttributeValueFilter());
BaseProperty prop = (BaseProperty) object.safeget(name);
if (prop != null) {
input.setValue(prop.toText());
}
input.setType("hidden");
input.setName(prefix + name);
input.setID(prefix + name);
buffer.append(input.toString());
}
@Override
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object,
XWikiContext context)
{
BaseProperty prop = (BaseProperty) object.safeget(name);
if (prop != null) {
buffer.append(prop.toText());
}
}
@Override
public void displayEdit(StringBuffer buffer, String name, String prefix, BaseCollection object,
XWikiContext context)
{
input input = new input();
input.setAttributeFilter(new XMLAttributeValueFilter());
BaseProperty prop = (BaseProperty) object.safeget(name);
if (prop != null) {
input.setValue(prop.toText());
}
input.setType("text");
input.setName(prefix + name);
input.setID(prefix + name);
input.setDisabled(isDisabled());
buffer.append(input.toString());
}
public String displayHidden(String name, String prefix, BaseCollection object, XWikiContext context)
{
StringBuffer buffer = new StringBuffer();
displayHidden(buffer, name, prefix, object, context);
return buffer.toString();
}
public String displayHidden(String name, BaseCollection object, XWikiContext context)
{
return displayHidden(name, "", object, context);
}
public String displayView(String name, String prefix, BaseCollection object, XWikiContext context)
{
StringBuffer buffer = new StringBuffer();
displayView(buffer, name, prefix, object, context);
return buffer.toString();
}
public String displayView(String name, BaseCollection object, XWikiContext context)
{
return displayView(name, "", object, context);
}
public String displayEdit(String name, String prefix, BaseCollection object, XWikiContext context)
{
StringBuffer buffer = new StringBuffer();
displayEdit(buffer, name, prefix, object, context);
return buffer.toString();
}
public String displayEdit(String name, BaseCollection object, XWikiContext context)
{
return displayEdit(name, "", object, context);
}
public boolean isCustomDisplayed(XWikiContext context)
{
return (StringUtils.isNotEmpty(getCachedDefaultCustomDisplayer(context)));
}
public void displayCustom(StringBuffer buffer, String fieldName, String prefix, String type, BaseObject object,
final XWikiContext context) throws XWikiException
{
String content = "";
try {
VelocityContext vcontext = Utils.getComponent(VelocityManager.class).getVelocityContext();
vcontext.put("name", fieldName);
vcontext.put("prefix", prefix);
// The PropertyClass instance can be used to access meta properties in the custom displayer (e.g.
// dateFormat, multiSelect). It can be obtained from the XClass of the given object but only if the property
// has been added to the XClass. We need to have it in the Velocity context for the use case when an XClass
// property needs to be previewed before being added to the XClass.
vcontext.put("field", new com.xpn.xwiki.api.PropertyClass(this, context));
vcontext.put("object", new com.xpn.xwiki.api.Object(object, context));
vcontext.put("type", type);
vcontext.put("context", new DeprecatedContext(context));
vcontext.put("xcontext", new Context(context));
BaseProperty prop = (BaseProperty) object.safeget(fieldName);
if (prop != null) {
vcontext.put("value", prop.getValue());
} else {
// The $value property can exist in the velocity context, we overwrite it to make sure we don't get a
// wrong value in the displayer when the property does not exist yet.
vcontext.put("value", null);
}
String customDisplayer = getCachedDefaultCustomDisplayer(context);
if (StringUtils.isNotEmpty(customDisplayer)) {
if (customDisplayer.equals(CLASS_DISPLAYER_IDENTIFIER)) {
final String rawContent = getCustomDisplay();
XWikiDocument classDocument =
context.getWiki().getDocument(getObject().getDocumentReference(), context);
final String classSyntax = classDocument.getSyntax().toIdString();
// Using author reference since the document content is not relevant in this case.
DocumentReference authorReference = classDocument.getAuthorReference();
// Make sure we render the custom displayer with the rights of the user who wrote it (i.e. class
// document author).
content = renderContentInContext(rawContent, classSyntax, authorReference, context);
} else if (customDisplayer.startsWith(DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX)) {
XWikiDocument displayerDoc = context.getWiki().getDocument(
StringUtils.substringAfter(customDisplayer, DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX), context);
final String rawContent = displayerDoc.getContent();
final String displayerDocSyntax = displayerDoc.getSyntax().toIdString();
DocumentReference authorReference = displayerDoc.getContentAuthorReference();
// Make sure we render the custom displayer with the rights of the user who wrote it (i.e. displayer
// document content author).
content = renderContentInContext(rawContent, displayerDocSyntax, authorReference, context);
} else if (customDisplayer.startsWith(TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX)) {
content = context.getWiki().evaluateTemplate(
StringUtils.substringAfter(customDisplayer, TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX), context);
}
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES,
XWikiException.ERROR_XWIKI_CLASSES_CANNOT_PREPARE_CUSTOM_DISPLAY,
"Exception while preparing the custom display of " + fieldName, e, null);
}
buffer.append(content);
}
/**
* Render content in the current document's context with the rights of the given user.
*/
private String renderContentInContext(final String content, final String syntax, DocumentReference authorReference,
final XWikiContext context) throws Exception
{
return Utils.getComponent(SUExecutor.class)
.call(() -> context.getDoc().getRenderedContent(content, syntax, context), authorReference);
}
@Override
public String getClassName()
{
BaseClass bclass = getxWikiClass();
return (bclass == null) ? "" : bclass.getName();
}
// In property classes we need to store this info in the HashMap for fields
// This way it is readable by the displayEdit/displayView functions..
@Override
public String getName()
{
return getStringValue("name");
}
@Override
public void setName(String name)
{
setStringValue("name", name);
}
public String getCustomDisplay()
{
return getStringValue("customDisplay");
}
public void setCustomDisplay(String value)
{
setLargeStringValue("customDisplay", value);
}
@Override
public String getPrettyName()
{
return getStringValue("prettyName");
}
public String getPrettyName(XWikiContext context)
{
return getTranslatedPrettyName(context);
}
public String getTranslatedPrettyName(XWikiContext context)
{
String msgName = getFieldFullName();
if ((context == null) || (context.getWiki() == null)) {
return getPrettyName();
}
String prettyName = localizePlain(msgName);
if (prettyName == null) {
return getPrettyName();
}
return prettyName;
}
@Override
public void setPrettyName(String prettyName)
{
setStringValue("prettyName", prettyName);
}
/**
* @param property name of the property
* @return the localized value of the property, with a fallback to the inner value
*/
private String getLocalizedPropertyValue(String property)
{
String propertyName = String.format("%s_%s", getFieldFullName(), property);
String propertyValue = localizePlain(propertyName);
if (propertyValue == null) {
propertyName = getLargeStringValue(property);
if (StringUtils.isNotBlank(propertyName)) {
propertyValue = localizePlainOrKey(propertyName, propertyName);
}
}
return propertyValue;
}
/**
* Get the localized hint. A hint is a text displayed in the object editor to help the user filling some content.
*
* @return the localized hint.
* @since 9.11RC1
*/
public String getHint()
{
return getLocalizedPropertyValue("hint");
}
/**
* Set the text displayed in the object editor to help the user filling some content.
* @since 9.11RC1
*/
public void setHint(String hint)
{
setLargeStringValue("hint", hint);
}
public String getTooltip()
{
return getLargeStringValue("tooltip");
}
/**
* Gets international tooltip
*
* @param context
* @return
*/
public String getTooltip(XWikiContext context)
{
return getLocalizedPropertyValue("tooltip");
}
public void setTooltip(String tooltip)
{
setLargeStringValue("tooltip", tooltip);
}
@Override
public int getNumber()
{
return getIntValue("number");
}
@Override
public void setNumber(int number)
{
setIntValue("number", number);
}
/**
* Each type of XClass property is identified by a string that specifies the data type of the property value (e.g.
* 'String', 'Number', 'Date') without disclosing implementation details. The internal implementation of an XClass
* property type can change over time but its {@code classType} should not.
* <p>
* The {@code classType} can be used as a hint to lookup various components related to this specific XClass property
* type. See {@link com.xpn.xwiki.internal.objects.classes.PropertyClassProvider} for instance.
*
* @return an identifier for the data type of the property value (e.g. 'String', 'Number', 'Date')
*/
public String getClassType()
{
// By default the hint is computed by removing the Class suffix, if present, from the Java simple class name
// (without the package). Subclasses can overwrite this method to use a different hint format.
return StringUtils.removeEnd(getClass().getSimpleName(), "Class");
}
/**
* Sets the property class type.
*
* @param type the class type
* @deprecated since 4.3M1, the property class type cannot be modified
*/
@Deprecated
public void setClassType(String type)
{
LOGGER.warn("The property class type cannot be modified!");
}
@Override
public PropertyClass clone()
{
PropertyClass pclass = (PropertyClass) super.clone();
pclass.setObject(getObject());
return pclass;
}
@Override
public Element toXML(BaseClass bclass)
{
return toXML();
}
@Override
public Element toXML()
{
Element pel = new DOMElement(getName());
// Iterate over values sorted by field name so that the values are
// exported to XML in a consistent order.
Iterator it = getSortedIterator();
while (it.hasNext()) {
BaseProperty bprop = (BaseProperty) it.next();
pel.add(bprop.toXML());
}
Element el = new DOMElement("classType");
String classType = getClassType();
if (this.getClass().getSimpleName().equals(classType + "Class")) {
// Keep exporting the full Java class name for old/default property types to avoid breaking the XAR format
// (to allow XClasses created with the current version of XWiki to be imported in an older version).
classType = this.getClass().getName();
}
el.addText(classType);
pel.add(el);
return pel;
}
public void fromXML(Element pcel) throws XWikiException
{
List list = pcel.elements();
BaseClass bclass = getxWikiClass();
for (int i = 0; i < list.size(); i++) {
Element ppcel = (Element) list.get(i);
String name = ppcel.getName();
if (bclass == null) {
Object[] args = { getClass().getName() };
throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES,
XWikiException.ERROR_XWIKI_CLASSES_PROPERTY_CLASS_IN_METACLASS,
"Cannot find property class {0} in MetaClass object", null, args);
}
PropertyClass pclass = (PropertyClass) bclass.safeget(name);
if (pclass != null) {
BaseProperty bprop = pclass.newPropertyfromXML(ppcel);
bprop.setObject(this);
safeput(name, bprop);
}
}
}
@Override
public String toFormString()
{
return toString();
}
public void initLazyCollections()
{
}
public boolean isUnmodifiable()
{
return (getIntValue("unmodifiable") == 1);
}
public void setUnmodifiable(boolean unmodifiable)
{
if (unmodifiable) {
setIntValue("unmodifiable", 1);
} else {
setIntValue("unmodifiable", 0);
}
}
/**
* See if this property is disabled or not. A disabled property should not be editable, but existing object values
* are still kept in the database.
*
* @return {@code true} if this property is disabled and should not be used, {@code false} otherwise
* @see #setDisabled(boolean)
* @since 2.4M2
*/
public boolean isDisabled()
{
return (getIntValue("disabled", 0) == 1);
}
/**
* Disable or re-enable this property. A disabled property should not be editable, but existing object values are
* still kept in the database.
*
* @param disabled whether the property is disabled or not
* @see #isDisabled()
* @since 2.4M2
*/
public void setDisabled(boolean disabled)
{
if (disabled) {
setIntValue("disabled", 1);
} else {
setIntValue("disabled", 0);
}
}
public BaseProperty fromStringArray(String[] strings)
{
return fromString(strings[0]);
}
public boolean isValidColumnTypes(Property hibprop)
{
return true;
}
@Override
public BaseProperty fromValue(Object value)
{
BaseProperty property = newProperty();
property.setValue(value);
return property;
}
@Override
public BaseProperty newProperty()
{
return new BaseProperty();
}
public void setValidationRegExp(String validationRegExp)
{
setStringValue("validationRegExp", validationRegExp);
}
public String getValidationRegExp()
{
return getStringValue("validationRegExp");
}
public String getValidationMessage()
{
return getStringValue("validationMessage");
}
public void setValidationMessage(String validationMessage)
{
setStringValue("validationMessage", validationMessage);
}
public boolean validateProperty(BaseProperty property, XWikiContext context)
{
String regexp = getValidationRegExp();
if ((regexp == null) || (regexp.trim().equals(""))) {
return true;
}
String value = ((property == null) || (property.getValue() == null)) ? "" : property.getValue().toString();
try {
if (context.getUtil().match(regexp, value)) {
return true;
}
XWikiValidationStatus.addErrorToContext((getObject() == null) ? "" : getObject().getName(), getName(),
getTranslatedPrettyName(context), getValidationMessage(), context);
return false;
} catch (Exception e) {
XWikiValidationStatus.addExceptionToContext((getObject() == null) ? "" : getObject().getName(), getName(),
e, context);
return false;
}
}
@Override
public void flushCache()
{
this.cachedCustomDisplayer = null;
}
/**
* Compares two property definitions based on their index number.
*
* @param other the other property definition to be compared with
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
* the specified object.
* @see #getNumber()
* @since 2.4M2
*/
@Override
public int compareTo(PropertyClass other)
{
int result = this.getNumber() - other.getNumber();
// This should never happen, but just to remove the randomness in case it does happen, also compare their names.
if (result == 0) {
result = this.getName().compareTo(other.getName());
}
return result;
}
protected String getFullQueryPropertyName()
{
return "obj." + getName();
}
/**
* Returns the current cached default custom displayer for the PropertyClass. The result will be cached and can be
* flushed using {@link #flushCache()}. If it returns the empty string, then there is no default custom displayer
* for this class.
*
* @param context the current request context
* @return An identifier for the location of a custom displayer. This can be {@code class} if there's custom display
* code specified in the class itself, {@code page:currentwiki:XWiki.BooleanDisplayer} if such a document
* exists in the current wiki, {@code page:xwiki:XWiki.StringDisplayer} if such a document exists in the
* main wiki, or {@code template:displayer_boolean.vm} if a template on the filesystem or in the current
* skin exists.
*/
protected String getCachedDefaultCustomDisplayer(XWikiContext context)
{
// First look at custom displayer in class. We should not cache this one.
String customDisplay = getCustomDisplay();
if (StringUtils.isNotEmpty(customDisplay)) {
return CLASS_DISPLAYER_IDENTIFIER;
}
// Then look for pages or templates
if (this.cachedCustomDisplayer == null) {
this.cachedCustomDisplayer = getDefaultCustomDisplayer(getTypeName(), context);
}
return this.cachedCustomDisplayer;
}
/**
* Method to find the default custom displayer to use for a specific Property Class.
*
* @param propertyClassName the type of the property; this is defined in each subclass, such as {@code boolean},
* {@code string} or {@code dblist}
* @param context the current request context
* @return An identifier for the location of a custom displayer. This can be {@code class} if there's custom display
* code specified in the class itself, {@code page:currentwiki:XWiki.BooleanDisplayer} if such a document
* exists in the current wiki, {@code page:xwiki:XWiki.StringDisplayer} if such a document exists in the
* main wiki, or {@code template:displayer_boolean.vm} if a template on the filesystem or in the current
* skin exists.
*/
protected String getDefaultCustomDisplayer(String propertyClassName, XWikiContext context)
{
LOGGER.debug("Looking up default custom displayer for property class name [{}]", propertyClassName);
try {
// First look into the current wiki
String pageName = StringUtils.capitalize(propertyClassName) + "Displayer";
DocumentReference reference = new DocumentReference(context.getWikiId(), "XWiki", pageName);
if (context.getWiki().exists(reference, context)) {
LOGGER.debug("Found default custom displayer for property class name in local wiki: [{}]", pageName);
return DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX + "XWiki." + pageName;
}
// Look in the main wiki
if (!context.isMainWiki()) {
reference = new DocumentReference(context.getMainXWiki(), "XWiki", pageName);
if (context.getWiki().exists(reference, context)) {
LOGGER.debug("Found default custom displayer for property class name in main wiki: [{}]", pageName);
return DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX + context.getMainXWiki() + ":XWiki." + pageName;
}
}
// Look in templates
String templateName = "displayer_" + propertyClassName + ".vm";
TemplateManager templateManager = Utils.getComponent(TemplateManager.class);
Template existingTemplate = templateManager.getTemplate(templateName);
if (existingTemplate != null) {
LOGGER.debug("Found default custom displayer for property class name as template: [{}]", templateName);
return TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX + templateName;
}
} catch (Throwable e) {
// If we fail we consider there is no custom displayer
LOGGER.error("Error while trying to evaluate if a property has a custom displayer", e);
}
return null;
}
/**
* Get a short name identifying this type of property. This is derived from the java class name, lowercasing the
* part before {@code Class}.
*
* @return a string, for example {@code string}, {@code dblist}, {@code number}
*/
private String getTypeName()
{
return StringUtils.substringBeforeLast(this.getClass().getSimpleName(), "Class").toLowerCase();
}
/**
* Apply a 3 ways merge on passed current, previous and new version of the same property. The passed current version
* is modified as result of the merge.
*
* @param currentProperty the current version of the element and the one to modify
* @param previousProperty the previous version of the element
* @param newProperty the new version of the property
* @param configuration the configuration of the merge Indicate how to deal with some conflicts use cases, etc.
* @param context the XWiki context
* @param mergeResult the merge report
* @return the merged version
* @since 6.2M1
*/
public <T extends EntityReference> void mergeProperty(BaseProperty<T> currentProperty,
BaseProperty<T> previousProperty, BaseProperty<T> newProperty, MergeConfiguration configuration,
XWikiContext context, MergeResult mergeResult)
{
currentProperty.merge(previousProperty, newProperty, configuration, context, mergeResult);
}
}
|
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static java.util.Objects.requireNonNull;
import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.EFFECTIVE_MODEL;
import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.FULL_DECLARATION;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Preconditions;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.ContextMutation;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnNamespaceItemAdded;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnPhaseFinished;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class ModifierImpl implements ModelActionBuilder {
private static final Logger LOG = LoggerFactory.getLogger(ModifierImpl.class);
private final InferenceContext ctx = new InferenceContext() { };
private final Set<AbstractPrerequisite<?>> unsatisfied = new HashSet<>(1);
private final Set<AbstractPrerequisite<?>> mutations = new HashSet<>(1);
private InferenceAction action;
private boolean actionApplied = false;
private <D> AbstractPrerequisite<D> addReq(final AbstractPrerequisite<D> prereq) {
LOG.trace("Modifier {} adding prerequisite {}", this, prereq);
unsatisfied.add(prereq);
return prereq;
}
private <T> AbstractPrerequisite<T> addMutation(final AbstractPrerequisite<T> mutation) {
LOG.trace("Modifier {} adding mutation {}", this, mutation);
mutations.add(mutation);
return mutation;
}
private void checkNotRegistered() {
Preconditions.checkState(action == null, "Action was already registered.");
}
private boolean removeSatisfied() {
final Iterator<AbstractPrerequisite<?>> it = unsatisfied.iterator();
while (it.hasNext()) {
final AbstractPrerequisite<?> prereq = it.next();
if (prereq.isDone()) {
// We are removing current prerequisite from list.
LOG.trace("Modifier {} prerequisite {} satisfied", this, prereq);
it.remove();
}
}
return unsatisfied.isEmpty();
}
boolean isApplied() {
return actionApplied;
}
void failModifier() {
removeSatisfied();
action.prerequisiteFailed(unsatisfied);
action = null;
}
private void applyAction() {
Preconditions.checkState(!actionApplied);
action.apply(ctx);
actionApplied = true;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <K, C extends StmtContext<?,?,?>, N extends StatementNamespace<K, ?, ?>> AbstractPrerequisite<C>
requiresCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key,
final ModelProcessingPhase phase) {
checkNotRegistered();
AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
addReq(addedToNs);
contextImpl(context).onNamespaceItemAddedAction((Class) namespace, key, addedToNs);
return addedToNs;
}
private <C extends StmtContext<?, ?, ?>> AbstractPrerequisite<C> requiresCtxImpl(final C context,
final ModelProcessingPhase phase) {
checkNotRegistered();
PhaseFinished<C> phaseFin = new PhaseFinished<>();
addReq(phaseFin);
contextImpl(context).addPhaseCompletedListener(phase, phaseFin);
return phaseFin;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private <K, C extends StmtContext.Mutable<?, ?, ?>,
N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>> AbstractPrerequisite<C> mutatesCtxImpl(
final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key,
final ModelProcessingPhase phase) {
checkNotRegistered();
PhaseModificationInNamespace<C> mod = new PhaseModificationInNamespace<>(phase);
addReq(mod);
addMutation(mod);
contextImpl(context).onNamespaceItemAddedAction((Class) namespace, key, mod);
return mod;
}
private static StatementContextBase<?,?,?> contextImpl(final Object value) {
Preconditions.checkArgument(value instanceof StatementContextBase,
"Supplied context %s is not provided by this reactor.", value);
return StatementContextBase.class.cast(value);
}
boolean tryApply() {
Preconditions.checkState(action != null, "Action was not defined yet.");
if (removeSatisfied()) {
applyAction();
return true;
}
return false;
}
@Nonnull
@Override
public <C extends Mutable<?, ?, ?>, CT extends C> Prerequisite<C> mutatesCtx(final CT context,
final ModelProcessingPhase phase) {
return addMutation(new PhaseMutation<>(contextImpl(context), phase));
}
@Nonnull
@Override
public <A,D extends DeclaredStatement<A>,E extends EffectiveStatement<A, D>>
AbstractPrerequisite<StmtContext<A, D, E>> requiresCtx(final StmtContext<A, D, E> context,
final ModelProcessingPhase phase) {
return requiresCtxImpl(context, phase);
}
@Nonnull
@Override
public <K, N extends StatementNamespace<K, ?, ?>> Prerequisite<StmtContext<?, ?, ?>> requiresCtx(
final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key,
final ModelProcessingPhase phase) {
return requiresCtxImpl(context, namespace, key, phase);
}
@Nonnull
@Override
public <D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(
final StmtContext<?, ? extends D, ?> context) {
return requiresCtxImpl(context, FULL_DECLARATION).transform(StmtContext::buildDeclared);
}
@Nonnull
@Override
public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>> Prerequisite<D>
requiresDeclared(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
final AbstractPrerequisite<StmtContext<?, D, ?>> rawContext = requiresCtxImpl(context, namespace, key,
FULL_DECLARATION);
return rawContext.transform(StmtContext::buildDeclared);
}
@Nonnull
@Override
public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>>
AbstractPrerequisite<StmtContext<?, D, ?>> requiresDeclaredCtx(final StmtContext<?, ?, ?> context,
final Class<N> namespace, final K key) {
return requiresCtxImpl(context, namespace, key, FULL_DECLARATION);
}
@Nonnull
@Override
public <E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(
final StmtContext<?, ?, ? extends E> stmt) {
return requiresCtxImpl(stmt, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
}
@Nonnull
@Override
public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>> Prerequisite<E>
requiresEffective(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
final AbstractPrerequisite<StmtContext<?,?,E>> rawContext = requiresCtxImpl(context, namespace, key,
EFFECTIVE_MODEL);
return rawContext.transform(StmtContext::buildEffective);
}
@Nonnull
@Override
public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>>
AbstractPrerequisite<StmtContext<?, ?, E>> requiresEffectiveCtx(final StmtContext<?, ?, ?> context,
final Class<N> namespace, final K key) {
return requiresCtxImpl(contextImpl(context), namespace, key, EFFECTIVE_MODEL);
}
@Nonnull
@Override
public <N extends IdentifierNamespace<?, ?>> Prerequisite<Mutable<?, ?, ?>> mutatesNs(
final Mutable<?, ?, ?> context, final Class<N> namespace) {
return addMutation(new NamespaceMutation<>(contextImpl(context), namespace));
}
@Nonnull
@Override
public <K, E extends EffectiveStatement<?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtx(final StmtContext<?, ?, ?> context,
final Class<N> namespace, final K key) {
return mutatesCtxImpl(context, namespace, key, EFFECTIVE_MODEL);
}
@Override
public void apply(final InferenceAction action) {
Preconditions.checkState(this.action == null, "Action already defined to %s", this.action);
this.action = Preconditions.checkNotNull(action);
}
private abstract class AbstractPrerequisite<T> implements Prerequisite<T> {
private boolean done = false;
private T value;
@Override
public final T resolve(final InferenceContext ctx) {
Preconditions.checkState(done);
Preconditions.checkArgument(ctx == ModifierImpl.this.ctx);
return value;
}
final boolean isDone() {
return done;
}
final boolean resolvePrereq(final T value) {
this.value = value;
this.done = true;
return isApplied();
}
final <O> Prerequisite<O> transform(final Function<? super T, O> transformation) {
return ctx -> transformation.apply(resolve(ctx));
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
}
ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper.add("value", value);
}
}
private class PhaseMutation<C> extends AbstractPrerequisite<C> implements ContextMutation {
@SuppressWarnings("unchecked")
PhaseMutation(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
context.addMutation(phase, this);
resolvePrereq((C) context);
}
@Override
public boolean isFinished() {
return isApplied();
}
}
private class PhaseFinished<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
implements OnPhaseFinished {
@SuppressWarnings("unchecked")
@Override
public boolean phaseFinished(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
return resolvePrereq((C) context);
}
}
private class NamespaceMutation<N extends IdentifierNamespace<?,?>>
extends AbstractPrerequisite<Mutable<?, ?, ?>> {
NamespaceMutation(final StatementContextBase<?, ?, ?> ctx, final Class<N> namespace) {
resolvePrereq(ctx);
}
}
private class AddedToNamespace<C extends StmtContext<?,?,?>> extends AbstractPrerequisite<C>
implements OnNamespaceItemAdded, OnPhaseFinished {
private final ModelProcessingPhase phase;
AddedToNamespace(final ModelProcessingPhase phase) {
this.phase = requireNonNull(phase);
}
@Override
public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
final Object key, final Object value) {
((StatementContextBase<?, ?, ?>) value).addPhaseCompletedListener(phase, this);
}
@SuppressWarnings("unchecked")
@Override
public boolean phaseFinished(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
return resolvePrereq((C) context);
}
@Override
ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return super.addToStringAttributes(toStringHelper).add("phase", phase);
}
}
private class PhaseModificationInNamespace<C extends Mutable<?,?,?>> extends AbstractPrerequisite<C>
implements OnNamespaceItemAdded, ContextMutation {
private final ModelProcessingPhase modPhase;
PhaseModificationInNamespace(final ModelProcessingPhase phase) {
Preconditions.checkArgument(phase != null, "Model processing phase must not be null");
this.modPhase = phase;
}
@SuppressWarnings("unchecked")
@Override
public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
final Object key, final Object value) {
StatementContextBase<?, ?, ?> targetCtx = contextImpl(value);
targetCtx.addMutation(modPhase, this);
resolvePrereq((C) targetCtx);
}
@Override
public boolean isFinished() {
return isApplied();
}
}
}
|
package com.google.sampling.experiential.server.stats.participation;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Transaction;
import com.google.common.collect.Lists;
/**
* This class persists the response statistics for the participants in an experiment by date.
*
* It allows updating a particular stat for a particular participant in an experiment for a particular date.
*
* It allows retrieval of the stats for a given participant in an experiment or for
* all participants in an experiment on a given date.
*
* Dates are stored in local time (but encoded as UTC given the appengine constraint of UTC only timezones).
* We want to query on the local logical day for a participant, e.g.
* 9am local(participant) time across participants who may be in multiple timezones
* without having to do a bunch of timezone wrangling.
*
*/
public class ResponseStatEntityManager {
private static final Logger LOG = Logger.getLogger(ResponseStatEntityManager.class.getName());
static final String KIND = "response_stats";
static final String EXPERIMENT_ID_PROPERTY = "experimentId";
static final String EXPERIMENT_GROUP_NAME_PROPERTY = "experimentGroupName";
static final String WHO_PROPERTY = "who";
static final String SCHED_R_PROPERTY = "schedR";
static final String MISSED_R_PROPERTY = "missedR";
static final String SELF_R_PROPERTY = "selfR";
static final String DATE_PROPERTY = "date";
static final String LAST_CONTACT_DATE_TIME_PROPERTY = "lastContact";
/**
* Increment the scheduled responses count for an individual in an experiment on a particular date.
* @param experimentId
* @param experimentGroupName TODO
* @param who
*/
public void updateScheduledResponseCountForWho(long experimentId, String experimentGroupName, String who, DateTime date) {
updateResponseCountForWho(experimentId, experimentGroupName, who, date, SCHED_R_PROPERTY);
}
/**
* Increment the missed responses count for an individual in an experiment on a particular date.
* @param experimentId
* @param experimentGroupName TODO
* @param who
*/
public void updateMissedResponseCountForWho(long experimentId, String experimentGroupName, String who, DateTime date) {
updateResponseCountForWho(experimentId, experimentGroupName, who, date, MISSED_R_PROPERTY);
}
/**
* Increment the self responses count for an individual in an experiment on a particular date.
* @param experimentId
* @param experimentGroupName TODO
* @param who
*/
public void updateSelfResponseCountForWho(long experimentId, String experimentGroupName, String who, DateTime date) {
updateResponseCountForWho(experimentId, experimentGroupName, who, date, SELF_R_PROPERTY);
}
// /**
// * Retrieves the response stats for a particular row (person, as who) for a particular experiment
// * on a particular date.
// *
// * This will return a separate row for each group.
// *
// * The date is converted to UTC, preserving local date but set to midnight. This allows us to query
// * on the concept of a "local" date even though appengine stores in utc.
// *
// * @param experimentId
// * @param who
// * @return
// */
// public ResponseStat getResponseStatForWhoOnDate(long experimentId, String who, DateTime date) {
// Query query = new Query(KIND);
// FilterPredicate whoFilter = createWhoFilter(who);
// FilterPredicate experimentFilter = createExperimentFilter(experimentId);
// DateTime utcLocalDate = LocalToUTCTimeZoneConverter.changeZoneToUTC(date);
// long dateMidnightUtcMillis = createDateQueryPredicateValue(utcLocalDate);
// FilterPredicate dateMidnightUTCMillisFilter = createDateFilter(dateMidnightUtcMillis);
// query.setFilter(CompositeFilterOperator.and(experimentFilter, whoFilter, dateMidnightUTCMillisFilter));
// DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
// Entity whoResult = ds.prepare(query).asSingleEntity();
// return createResponseStatFromQueryResult(whoResult);
/**
* Retrieves the response stats for each participant for a particular experiment
* on a particular date (in participant local timezone).
*
* This will have multiple rows for each participant - one row for each group that they have responses in.
*
* The date is converted to UTC, preserving local date but set to midnight. This allows us to query
* on the concept of a "local" date even though appengine stores in utc.
*
* @param experimentId
* @param who
* @return
*/
public List<ResponseStat> getResponseStatsForExperimentOnDate(long experimentId, DateTime date) {
Query query = new Query(KIND);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
DateTime utcLocalDate = LocalToUTCTimeZoneConverter.changeZoneToUTC(date);
long dateMidnightUtcMillis = createDateQueryPredicateValue(utcLocalDate);
FilterPredicate dateMidnightUTCMillisFilter = createDateFilter(dateMidnightUtcMillis);
query.setFilter(CompositeFilterOperator.and(experimentFilter, dateMidnightUTCMillisFilter));
return executeResponseStatsQuery(query);
}
/**
* Retrieves the response stats for each participant for a particular group
* on a particular date.
*
* This will have one row per participant.
*
* @param experimentId
* @param experimentGroupName
* @param date
* @return
*/
public List<ResponseStat> getResponseStatsForExperimentGroupOnDate(Long experimentId, String experimentGroupName, DateTime date) {
Query query = new Query(KIND);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
DateTime utcLocalDate = LocalToUTCTimeZoneConverter.changeZoneToUTC(date);
long dateMidnightUtcMillis = createDateQueryPredicateValue(utcLocalDate);
FilterPredicate dateMidnightUTCMillisFilter = createDateFilter(dateMidnightUtcMillis);
FilterPredicate groupFilter = createExperimentGroupFilter(experimentGroupName);
query.setFilter(CompositeFilterOperator.and(experimentFilter, groupFilter, dateMidnightUTCMillisFilter));
return executeResponseStatsQuery(query);
}
/**
* Retrieves the response stats for a particular row (person, as who) for a particular experiment
* This retrieves all dates for that person.
*
* There will be multiple rows for each date - one per group and multiple date rows
*
* @param experimentId
* @param who
* @return
*/
public List<ResponseStat> getResponseStatsForParticipant(long experimentId, String who) {
Query query = new Query(KIND);
FilterPredicate whoFilter = createWhoFilter(who);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
query.setFilter(CompositeFilterOperator.and(experimentFilter, whoFilter));
return executeResponseStatsQuery(query);
}
/**
* This will return one row for each date.
*
* @param experimentId
* @param experimentGroupName
* @param participant
* @return
*/
public List<ResponseStat> getResponseStatsForParticipantForGroup(long experimentId, String experimentGroupName, String participant) {
Query query = new Query(KIND);
FilterPredicate whoFilter = createWhoFilter(participant);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
FilterPredicate experimentGroupFilter = createExperimentGroupFilter(experimentGroupName);
query.setFilter(CompositeFilterOperator.and(experimentFilter, experimentGroupFilter, whoFilter));
return executeResponseStatsQuery(query);
}
/**
* Retrieves the response stats for every row(person, as who) for an experiment
* ordered by person by date.
*
* This will return multiple rows for each date with multiple rows for each group for each person.
* For example,
*
* experimentId, who, date
* 1, bob, experimentGroup1, 2016/1/2
* 1, bob, experimentGroup2, 2016/1/2
*
* 1, bob, experimentGroup1, 2016/1/3
*
* 1, steve, experimentGroup1, 2016/1/2
* 1, steve, experimentGroup2, 2016/1/2
*
* 1, steve, experimentGroup1, 2016/1/3
* ...
*
* @return
*/
public final List<ResponseStat> getResponseStatsForExperiment(long experimentId) {
Query query = new Query(KIND);
query.setFilter(createExperimentFilter(experimentId));
return executeResponseStatsQuery(query);
}
/**
* Retrieves the response stats for every row(person, as who) for an experimentGroup within Experiment
* ordered by person by date.
*
* This will return multiple rows - one for each date- per person
* For example,
*
* experimentId, who, date
* 1, bob, experimentGroup, 2016/1/2
* 1, bob, experimentGroup, 2016/1/3
* 1, bob, experimentGroup, 2016/1/4
*
* 1, steve, experimentGroup, 2016/1/2
* 1, steve, experimentGroup, 2016/1/3
* 1, steve, experimentGroup, 2016/1/4
* ...
*
* @return
*/
public final List<ResponseStat> getResponseStatsForExperimentGroup(long experimentId, String experimentGroup) {
Query query = new Query(KIND);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
FilterPredicate experimentGroupFilter = createExperimentGroupFilter(experimentGroup);
Filter andFilter = CompositeFilterOperator.and(experimentFilter, experimentGroupFilter);
query.setFilter(andFilter);
return executeResponseStatsQuery(query);
}
private List<ResponseStat> executeResponseStatsQuery(Query query) {
List<ResponseStat> responseStats = Lists.newArrayList();
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
for (Entity entity : ds.prepare(query).asIterable()) {
responseStats.add(createResponseStatFromQueryResult(entity));
}
return responseStats;
}
/**
* central method to update row in datastore. Creates the row if it does not already exist.
*
* Sets one of the SCHED_R, MISSED_R, SELF_R properties for participant of an experiment on a particular date.
*
*
* @param experimentId
* @param experimentGroupName TODO
* @param who
* @param date TODO
* @param prop
*/
private void updateResponseCountForWho(long experimentId, String experimentGroupName, String who, DateTime date, String prop) {
Query query = new Query(KIND);
FilterPredicate experimentFilter = createExperimentFilter(experimentId);
FilterPredicate experimentGroupFilter = createExperimentGroupFilter(experimentGroupName);
FilterPredicate whoFilter = createWhoFilter(who);
DateTime utcLocalDate = LocalToUTCTimeZoneConverter.changeZoneToUTC(date);
long dateMidnightUtcMillis = createDateQueryPredicateValue(utcLocalDate);
FilterPredicate dateMidnightUTCMillisFilter = createDateFilter(dateMidnightUtcMillis);
// bounding strategy on a date, but, since it is just a "date" that we are looking for, canonicalized in utc,
// why not just compare millis? One filter and numerical.
// List<FilterPredicate> dateBoundFilters = createFiltersBoundingDate(utcLocalDate);
// Filter andFilter = CompositeFilterOperator.and(experimentFilter, whoFilter, dateBoundFilters.get(0), dateBoundFilters.get(1));
Filter andFilter = CompositeFilterOperator.and(experimentFilter, experimentGroupFilter, whoFilter, dateMidnightUTCMillisFilter);
query.setFilter(andFilter);
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Transaction tx = ds.beginTransaction();
Entity whoResult;
int value;
try {
whoResult = ds.prepare(query).asSingleEntity();
if (whoResult == null) {
whoResult = new Entity(KIND);
whoResult.setProperty(EXPERIMENT_ID_PROPERTY, experimentId);
whoResult.setProperty(EXPERIMENT_GROUP_NAME_PROPERTY, experimentGroupName);
whoResult.setProperty(WHO_PROPERTY, who);
whoResult.setProperty(DATE_PROPERTY, dateMidnightUtcMillis);
whoResult.setUnindexedProperty(LAST_CONTACT_DATE_TIME_PROPERTY, date.toDate());
value = 1;
} else {
Long property = (Long) whoResult.getProperty(prop);
if (property != null) {
value = convertToInt(property) + 1;
} else {
value = 1;
}
// update last contact time
Date lastTime = (Date)whoResult.getProperty(LAST_CONTACT_DATE_TIME_PROPERTY);
if (lastTime == null) {
whoResult.setProperty(LAST_CONTACT_DATE_TIME_PROPERTY, date.toDate());
} else {
DateTime lastDateTime = new DateTime(lastTime);
if (lastDateTime.isBefore(date)) {
whoResult.setProperty(LAST_CONTACT_DATE_TIME_PROPERTY, date.toDate());
}
}
}
whoResult.setUnindexedProperty(prop, value);
ds.put(tx, whoResult);
tx.commit();
} catch (ConcurrentModificationException e) {
LOG.log(Level.WARNING, "You may need more shards. Consider adding more shards.");
LOG.log(Level.WARNING, e.toString(), e);
} catch (Exception e) {
LOG.log(Level.WARNING, e.toString(), e);
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
private long createDateQueryPredicateValue(DateTime utcLocalDate) {
return convertDateTimeToMidnightMillis(utcLocalDate);
}
private long convertDateTimeToMidnightMillis(DateTime utcLocalDate) {
return utcLocalDate.toDateMidnight().getMillis();
}
private FilterPredicate createExperimentFilter(long experimentId) {
return new FilterPredicate(EXPERIMENT_ID_PROPERTY, FilterOperator.EQUAL, experimentId);
}
private FilterPredicate createExperimentGroupFilter(String experimentGroupName) {
return new FilterPredicate(EXPERIMENT_GROUP_NAME_PROPERTY, FilterOperator.EQUAL, experimentGroupName);
}
private FilterPredicate createWhoFilter(String who) {
return new FilterPredicate(WHO_PROPERTY, FilterOperator.EQUAL, who);
}
private FilterPredicate createDateFilter(long dateMidnightUtcMillis) {
FilterPredicate dateMidnightUTCMillisFilter = new FilterPredicate(DATE_PROPERTY, FilterOperator.EQUAL, dateMidnightUtcMillis);
return dateMidnightUTCMillisFilter;
}
private ResponseStat createResponseStatFromQueryResult(Entity grpDateWhoStat) {
if (grpDateWhoStat == null) {
return null;
}
return new ResponseStat(
(Long)grpDateWhoStat.getProperty(EXPERIMENT_ID_PROPERTY),
(String)grpDateWhoStat.getProperty(EXPERIMENT_GROUP_NAME_PROPERTY),
(String)grpDateWhoStat.getProperty(WHO_PROPERTY),
getDateProperty(grpDateWhoStat),
convertToInt((Long)grpDateWhoStat.getProperty(SCHED_R_PROPERTY)),
convertToInt((Long) grpDateWhoStat.getProperty(MISSED_R_PROPERTY)),
convertToInt((Long) grpDateWhoStat.getProperty(SELF_R_PROPERTY)));
}
private int convertToInt(Long long1) {
if (long1 != null) {
return long1.intValue();
}
return 0;
}
private DateTime getLastContactDateTime(Entity whoResult) {
Date property = (Date)whoResult.getProperty(LAST_CONTACT_DATE_TIME_PROPERTY);
if (property != null) {
return new DateTime(property);
}
return null;
}
private DateTime getDateProperty(Entity whoResult) {
Long property = (Long)whoResult.getProperty(DATE_PROPERTY);
if (property != null) {
return new DateMidnight(property, DateTimeZone.UTC).toDateTime();
}
return null;
}
//private List<FilterPredicate> createFiltersBoundingDate(DateTime utcLocalDate) {
//DateMidnight dateMidnight = utcLocalDate.toDateMidnight();
//Date beginningOfDay = dateMidnight.toDate();
//Date nextDay = dateMidnight.plusDays(1).toDate();
//FilterPredicate lowerDateBoundFilter = new FilterPredicate(DATE_PROPERTY, FilterOperator.GREATER_THAN_OR_EQUAL, beginningOfDay);
//FilterPredicate upperDateBoundFilter = new FilterPredicate(DATE_PROPERTY, FilterOperator.LESS_THAN, nextDay);
//List<FilterPredicate> dateBoundFilters = Lists.newArrayList(lowerDateBoundFilter, upperDateBoundFilter);
//return dateBoundFilters;
//private Filter createDateFilter(DateTime date) {
//DateTime utcLocalDate = LocalToUTCTimeZoneConverter.toTimeWithUTCZone(date);
//FilterPredicate lowerDateBoundFilter = new FilterPredicate(DATE_PROPERTY, FilterOperator.GREATER_THAN, utcLocalDate.minusDays(1).toDate());
//FilterPredicate upperDateBoundFilter = new FilterPredicate(DATE_PROPERTY, FilterOperator.GREATER_THAN, utcLocalDate.plusDays(1).toDate());
//return CompositeFilterOperator.and(lowerDateBoundFilter, upperDateBoundFilter);
}
|
package gov.hhs.fha.nhinc.async;
import com.sun.xml.ws.api.message.Header;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* This class is used to test the AsyncHeaderCreator class
*/
public class AsyncHeaderCreatorTest {
/**
* Default constructor
*/
public AsyncHeaderCreatorTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has all parameters provided.
*/
@Test
public void testCreateOutboundHeadersFull() {
String url = "TestUrl";
String action = "TestAction";
String messageId = "TestMessageId";
String relatesToId = "TestRelatesToId_1";
String addrAnon = "http:
List<String> relatesToIds = new ArrayList<String>();
relatesToIds.add(relatesToId);
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(url, action, messageId, relatesToIds);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 5, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
assertEquals(url, hdr.getStringContent());
} else if ("Action".equals(elemTag)) {
assertEquals(action, hdr.getStringContent());
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("MessageID".equals(elemTag)) {
assertEquals(messageId, hdr.getStringContent());
} else if ("RelatesTo".equals(elemTag)) {
assertEquals(relatesToId, hdr.getStringContent());
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has multiple RelatesTo items provided.
*/
@Test
public void testCreateOutboundHeadersMultipleRelatesTo() {
String url = "TestUrl";
String action = "TestAction";
String messageId = "TestMessageId";
String relatesToId1 = "TestRelatesToId_1";
String relatesToId2 = "TestRelatesToId_2";
String addrAnon = "http:
List<String> relatesToIds = new ArrayList<String>();
relatesToIds.add(relatesToId1);
relatesToIds.add(relatesToId2);
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(url, action, messageId, relatesToIds);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 6, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
assertEquals(url, hdr.getStringContent());
} else if ("Action".equals(elemTag)) {
assertEquals(action, hdr.getStringContent());
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("MessageID".equals(elemTag)) {
assertEquals(messageId, hdr.getStringContent());
} else if ("RelatesTo".equals(elemTag)) {
assertTrue(hdr.getStringContent().startsWith("TestRelatesToId_"));
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has no RelatesTo items provided.
*/
@Test
public void testCreateOutboundHeadersNullRelatesTo() {
String url = "TestUrl";
String action = "TestAction";
String messageId = "TestMessageId";
String addrAnon = "http:
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(url, action, messageId, null);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 4, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
assertEquals(url, hdr.getStringContent());
} else if ("Action".equals(elemTag)) {
assertEquals(action, hdr.getStringContent());
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("MessageID".equals(elemTag)) {
assertEquals(messageId, hdr.getStringContent());
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has no MessageID header.
*/
@Test
public void testCreateOutboundHeadersNullMessageId() {
String url = "TestUrl";
String action = "TestAction";
String relatesToId = "TestRelatesToId_1";
String addrAnon = "http:
List<String> relatesToIds = new ArrayList<String>();
relatesToIds.add(relatesToId);
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(url, action, null, relatesToIds);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 4, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
assertEquals(url, hdr.getStringContent());
} else if ("Action".equals(elemTag)) {
assertEquals(action, hdr.getStringContent());
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("RelatesTo".equals(elemTag)) {
assertEquals(relatesToId, hdr.getStringContent());
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has no action provided.
*/
@Test
public void testCreateOutboundHeadersNullAction() {
String url = "TestUrl";
String messageId = "TestMessageId";
String relatesToId = "TestRelatesToId_1";
String addrAnon = "http:
List<String> relatesToIds = new ArrayList<String>();
relatesToIds.add(relatesToId);
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(url, null, messageId, relatesToIds);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 5, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
assertEquals(url, hdr.getStringContent());
} else if ("Action".equals(elemTag)) {
try {
assertFalse(hdr.readHeader().hasText());
} catch (XMLStreamException ex) {
fail("Action element has unknown form " + ex.getMessage());
}
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("MessageID".equals(elemTag)) {
assertEquals(messageId, hdr.getStringContent());
} else if ("RelatesTo".equals(elemTag)) {
assertEquals(relatesToId, hdr.getStringContent());
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
/**
* Test of createOutboundHeaders method, of class AsyncHeaderCreator.
* This case has no endpoint url provided.
*/
@Test
public void testCreateOutboundHeadersNullURL() {
String action = "TestAction";
String messageId = "TestMessageId";
String relatesToId = "TestRelatesToId_1";
String addrAnon = "http:
List<String> relatesToIds = new ArrayList<String>();
relatesToIds.add(relatesToId);
AsyncHeaderCreator hdrCreator = new AsyncHeaderCreator();
List<Header> createdHeaders = hdrCreator.createOutboundHeaders(null, action, messageId, relatesToIds);
assertNotNull("List of created headers was null", createdHeaders);
if (createdHeaders != null) {
assertEquals("Number of headers created is not correct", 5, createdHeaders.size());
for (Header hdr : createdHeaders) {
assertNotNull("Created header was null", hdr);
if (hdr != null) {
String desiredNS = "http:
assertEquals("Every header should be in the addressing namespace ", desiredNS, hdr.getNamespaceURI());
String elemTag = hdr.getLocalPart();
if ("To".equals(elemTag)) {
try {
assertFalse(hdr.readHeader().hasText());
} catch (XMLStreamException ex) {
fail("To element has unknown form " + ex.getMessage());
}
} else if ("Action".equals(elemTag)) {
assertEquals(action, hdr.getStringContent());
} else if ("ReplyTo".equals(elemTag)) {
assertEquals(addrAnon, hdr.getStringContent());
} else if ("MessageID".equals(elemTag)) {
assertEquals(messageId, hdr.getStringContent());
} else if ("RelatesTo".equals(elemTag)) {
assertEquals(relatesToId, hdr.getStringContent());
} else {
fail("Unknown header element tag: " + elemTag);
}
}
}
}
}
}
|
package org.csstudio.swt.widgets.figures;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import org.csstudio.platform.ui.util.CustomMediaFactory;
import org.csstudio.swt.widgets.introspection.Introspectable;
import org.csstudio.swt.widgets.introspection.ShapeWidgetIntrospector;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
/**
* A rectangle figure.
*
* @author Sven Wende (original author), Xihui Chen (since import from SDS 2009/10)
*
*/
public final class OPIRectangleFigure extends RectangleFigure implements Introspectable {
/**
* The fill grade (0 - 100%).
*/
private double fill = 100;
/**
* The orientation (horizontal==true | vertical==false).
*/
private boolean horizontalFill = true;
/**
* The transparent state of the background.
*/
private boolean transparent = false;
/**
* The antiAlias flag
*/
private boolean antiAlias = true;
private Color lineColor = CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_PURPLE);
/**
* {@inheritDoc}
*/
@Override
protected synchronized void fillShape(final Graphics graphics) {
graphics.setAntialias(antiAlias ? SWT.ON : SWT.OFF);
Rectangle figureBounds = getBounds().getCopy();
figureBounds.crop(this.getInsets());
if (!transparent) {
graphics.setBackgroundColor(getBackgroundColor());
graphics.fillRectangle(figureBounds);
}
if(getFill() > 0){
graphics.setBackgroundColor(getForegroundColor());
Rectangle fillRectangle;
if (horizontalFill) {
int newW = (int) Math.round(figureBounds.width * (getFill() / 100));
fillRectangle = new Rectangle(figureBounds.x,figureBounds.y,newW,figureBounds.height);
} else {
int newH = (int) Math.round(figureBounds.height * (getFill() / 100));
fillRectangle = new Rectangle(figureBounds.x,figureBounds.y+figureBounds.height-newH,figureBounds.width,newH);
}
graphics.fillRectangle(fillRectangle);
}
}
public BeanInfo getBeanInfo() throws IntrospectionException {
return new ShapeWidgetIntrospector().getBeanInfo(this.getClass());
}
/**
* Gets the fill grade.
*
* @return the fill grade
*/
public double getFill() {
return fill;
}
/**
* @return the lineColor
*/
public Color getLineColor() {
return lineColor;
}
/**
* Gets the transparent state of the background.
*
* @return the transparent state of the background
*/
public boolean getTransparent() {
return transparent;
}
/**
* @return the antiAlias
*/
public boolean isAntiAlias() {
return antiAlias;
}
/**
* Gets the orientation (horizontal==true | vertical==false).
*
* @return boolean
* The orientation
*/
public boolean isHorizontalFill() {
return horizontalFill;
}
/**
* @see Shape#outlineShape(Graphics)
*/
protected void outlineShape(Graphics graphics) {
float lineInset = Math.max(1.0f, getLineWidth()) / 2.0f;
int inset1 = (int)Math.floor(lineInset);
int inset2 = (int)Math.ceil(lineInset);
Rectangle r = Rectangle.SINGLETON.setBounds(getClientArea());
r.x += inset1 ;
r.y += inset1;
r.width -= inset1 + inset2;
r.height -= inset1 + inset2;
graphics.setForegroundColor(lineColor);
graphics.drawRectangle(r);
}
public void setAntiAlias(boolean antiAlias) {
if(this.antiAlias == antiAlias)
return;
this.antiAlias = antiAlias;
repaint();
}
/**
* Sets the fill grade.
*
* @param fill
* the fill grade.
*/
public void setFill(final double fill) {
if(this.fill == fill)
return;
this.fill = fill;
repaint();
}
/**
* Sets the orientation (horizontal==true | vertical==false).
*
* @param horizontal
* The orientation.
*/
public void setHorizontalFill(final boolean horizontal) {
if(this.horizontalFill == horizontal)
return;
this.horizontalFill = horizontal;
repaint();
}
/**
* @param lineColor the lineColor to set
*/
public void setLineColor(Color lineColor) {
if(this.lineColor != null && this.lineColor.equals(lineColor))
return;
this.lineColor = lineColor;
repaint();
}
/**
* Sets the transparent state of the background.
*
* @param transparent
* the transparent state.
*/
public void setTransparent(final boolean transparent) {
if(this.transparent == transparent)
return;
this.transparent = transparent;
repaint();
}
}
|
package com.jarvis.cache.script;
import com.jarvis.cache.CacheUtil;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
/**
* JavaScript
*
*
*/
public class JavaScriptParser extends AbstractScriptParser {
private final ScriptEngineManager manager = new ScriptEngineManager();
private final ConcurrentHashMap<String, CompiledScript> expCache = new ConcurrentHashMap<String, CompiledScript>();
private final StringBuffer funcs = new StringBuffer();
private static int versionCode;
private final ScriptEngine engine;
public JavaScriptParser() {
engine = manager.getEngineByName("javascript");
try {
addFunction(HASH, CacheUtil.class.getDeclaredMethod("getUniqueHashStr", new Class[]{Object.class}));
addFunction(EMPTY, CacheUtil.class.getDeclaredMethod("isEmpty", new Class[]{Object.class}));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void addFunction(String name, Method method) {
try {
String clsName = method.getDeclaringClass().getName();
String methodName = method.getName();
funcs.append("function " + name + "(obj){return " + clsName + "." + methodName + "(obj);}");
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
Class<T> valueType) throws Exception {
Bindings bindings = new SimpleBindings();
bindings.put(TARGET, target);
bindings.put(ARGS, arguments);
if (hasRetVal) {
bindings.put(RET_VAL, retVal);
}
CompiledScript script = expCache.get(exp);
if (null != script) {
return (T) script.eval(bindings);
}
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
script = compEngine.compile(funcs + exp);
expCache.put(exp, script);
return (T) script.eval(bindings);
} else {
return (T) engine.eval(funcs + exp, bindings);
}
}
}
|
package org.axonframework.axonserver.connector.heartbeat;
import org.axonframework.axonserver.connector.AxonServerConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Verifies if the connection is still alive, and react if it is not.
*
* @author Sara Pellegrini
* @since 4.2.1
*/
public class HeartbeatMonitor {
private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatMonitor.class);
private final Runnable onInvalidConnection;
private final ConnectionSanityCheck connectionSanityCheck;
/**
* Constructs an instance of {@link HeartbeatMonitor} that forces a disconnection
* when the AxonServer connection is no longer alive.
*
* @param connectionManager connectionManager to AxonServer
* @param context the (Bounded) Context for which the heartbeat activity is monitored
*/
public HeartbeatMonitor(AxonServerConnectionManager connectionManager,
String context) {
this(() -> connectionManager.forceDisconnection(context, new RuntimeException("Inactivity timeout.")),
new HeartbeatConnectionCheck(connectionManager, context));
}
/**
* Primary constructor of {@link HeartbeatMonitor}.
*
* @param onInvalidConnection callback to be call when the connection is no longer alive
* @param connectionSanityCheck sanity check which allows to verify if the connection is alive
*/
public HeartbeatMonitor(Runnable onInvalidConnection, ConnectionSanityCheck connectionSanityCheck) {
this.onInvalidConnection = onInvalidConnection;
this.connectionSanityCheck = connectionSanityCheck;
}
/**
* Verify if the connection with AxonServer is still alive.
* If it is not, invoke a callback in order to react to the disconnection.
*/
public void run() {
try {
boolean valid = connectionSanityCheck.isValid();
if (!valid) {
onInvalidConnection.run();
}
} catch (Exception e) {
LOGGER.warn("Impossible to correctly monitor the Axon Server connection state.");
}
}
}
|
package org.ovirt.engine.core.searchbackend;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.SqlInjectionException;
import org.ovirt.engine.core.common.utils.EnumUtils;
import org.ovirt.engine.core.compat.EnumCompat;
import org.ovirt.engine.core.compat.IntegerCompat;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.Regex;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
public class SyntaxChecker implements ISyntaxChecker {
private SearchObjectAutoCompleter mSearchObjectAC;
private BaseAutoCompleter mColonAC;
private BaseAutoCompleter mPluralAC;
private BaseAutoCompleter mSortbyAC;
private BaseAutoCompleter mPageAC;
private BaseAutoCompleter mAndAC;
private BaseAutoCompleter mOrAC;
private BaseAutoCompleter mDotAC;
private BaseAutoCompleter mSortDirectionAC;
private java.util.HashMap<SyntaxObjectType, SyntaxObjectType[]> mStateMap;
private Regex mFirstDQRegexp;
private Regex mNonSpaceRegexp;
private java.util.ArrayList<Character> mDisAllowedChars;
private static SqlInjectionChecker sqlInjectionChecker;
public SyntaxChecker(int searchReasultsLimit, boolean hasDesktop) {
mSearchObjectAC = new SearchObjectAutoCompleter(hasDesktop);
mColonAC = new BaseAutoCompleter(":");
mPluralAC = new BaseAutoCompleter("S");
mSortbyAC = new BaseAutoCompleter("SORTBY");
mPageAC = new BaseAutoCompleter("PAGE");
mSortDirectionAC = new BaseAutoCompleter(new String[] { "ASC", "DESC" });
mAndAC = new BaseAutoCompleter("AND");
mOrAC = new BaseAutoCompleter("OR");
mDotAC = new BaseAutoCompleter(".");
mDisAllowedChars = new java.util.ArrayList<Character>(java.util.Arrays.asList(new Character[] { '\'', ';' }));
mFirstDQRegexp = new Regex("^\\s*\"$");
mNonSpaceRegexp = new Regex("^\\S+$");
mStateMap = new java.util.HashMap<SyntaxObjectType, SyntaxObjectType[]>();
mStateMap.put(SyntaxObjectType.BEGIN, new SyntaxObjectType[] { SyntaxObjectType.SEARCH_OBJECT });
mStateMap.put(SyntaxObjectType.SEARCH_OBJECT, new SyntaxObjectType[] { SyntaxObjectType.COLON });
SyntaxObjectType[] afterColon =
{ SyntaxObjectType.CROSS_REF_OBJ, SyntaxObjectType.CONDITION_FIELD,
SyntaxObjectType.SORTBY, SyntaxObjectType.PAGE, SyntaxObjectType.CONDITION_VALUE,
SyntaxObjectType.END };
mStateMap.put(SyntaxObjectType.COLON, afterColon);
SyntaxObjectType[] afterCrossRefObj = { SyntaxObjectType.DOT, SyntaxObjectType.CONDITION_RELATION };
mStateMap.put(SyntaxObjectType.CROSS_REF_OBJ, afterCrossRefObj);
mStateMap.put(SyntaxObjectType.DOT, new SyntaxObjectType[] { SyntaxObjectType.CONDITION_FIELD });
mStateMap.put(SyntaxObjectType.CONDITION_FIELD, new SyntaxObjectType[] { SyntaxObjectType.CONDITION_RELATION });
mStateMap.put(SyntaxObjectType.CONDITION_RELATION, new SyntaxObjectType[] { SyntaxObjectType.CONDITION_VALUE });
SyntaxObjectType[] afterConditionValue = { SyntaxObjectType.OR, SyntaxObjectType.AND,
SyntaxObjectType.CROSS_REF_OBJ, SyntaxObjectType.CONDITION_FIELD, SyntaxObjectType.SORTBY,
SyntaxObjectType.PAGE, SyntaxObjectType.CONDITION_VALUE };
mStateMap.put(SyntaxObjectType.CONDITION_VALUE, afterConditionValue);
SyntaxObjectType[] AndOrArray = { SyntaxObjectType.CROSS_REF_OBJ, SyntaxObjectType.CONDITION_FIELD,
SyntaxObjectType.CONDITION_VALUE };
mStateMap.put(SyntaxObjectType.AND, AndOrArray);
mStateMap.put(SyntaxObjectType.OR, AndOrArray);
mStateMap.put(SyntaxObjectType.SORTBY, new SyntaxObjectType[] { SyntaxObjectType.SORT_FIELD });
mStateMap.put(SyntaxObjectType.SORT_FIELD, new SyntaxObjectType[] { SyntaxObjectType.SORT_DIRECTION });
mStateMap.put(SyntaxObjectType.SORT_DIRECTION, new SyntaxObjectType[] { SyntaxObjectType.PAGE });
mStateMap.put(SyntaxObjectType.PAGE, new SyntaxObjectType[] { SyntaxObjectType.PAGE_VALUE });
mStateMap.put(SyntaxObjectType.PAGE_VALUE, new SyntaxObjectType[] { SyntaxObjectType.END });
// get sql injection checker for active database engine.
try {
sqlInjectionChecker = getSqlInjectionChecker();
} catch (Exception e) {
log.debug("Failed to load Sql Injection Checker. " + e.getMessage());
}
}
private enum ValueParseResult {
Err,
Normal,
FreeText;
}
private ValueParseResult handleValuePhrase(boolean final2, String searchText, int idx, RefObject<Integer> startPos,
SyntaxContainer container) {
boolean addObjFlag = false;
ValueParseResult retval = ValueParseResult.Normal;
IConditionFieldAutoCompleter curConditionFieldAC;
char curChar = searchText.charAt(idx);
String strRealObj = searchText.substring(startPos.argvalue, idx + 1);
boolean betweenDoubleQuotes = searchText.substring(startPos.argvalue, idx).contains("\"");
if (curChar == '"') {
betweenDoubleQuotes = (!betweenDoubleQuotes);
if (betweenDoubleQuotes) {
if (!mFirstDQRegexp.IsMatch(strRealObj)) {
container.setErr(SyntaxError.INVALID_CONDITION_VALUE, startPos.argvalue, idx + 1);
return ValueParseResult.Err;
}
} else {
strRealObj = StringHelper.trim(strRealObj, new char[] { '\"' });
addObjFlag = true;
}
}
// Doing this condition to identify whether this is the last
// searchObject and no space is predicted !!
if (final2) {
if (((curChar == ' ') || (idx + 1 == searchText.length())) && (betweenDoubleQuotes == false)
&& (addObjFlag == false)) {
strRealObj = strRealObj.trim();
if (mNonSpaceRegexp.IsMatch(strRealObj)) {
addObjFlag = true;
} else {
startPos.argvalue = idx + 1;
}
}
} else {
if ((curChar == ' ') && (betweenDoubleQuotes == false) && (addObjFlag == false)) {
strRealObj = strRealObj.trim();
if (mNonSpaceRegexp.IsMatch(strRealObj)) {
addObjFlag = true;
} else {
startPos.argvalue = idx + 1;
}
}
}
if (addObjFlag) {
String curRefObj = container.getPreviousSyntaxObject(3, SyntaxObjectType.CROSS_REF_OBJ);
String curConditionField = container.getPreviousSyntaxObject(1, SyntaxObjectType.CONDITION_FIELD);
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(curRefObj);
if (curConditionFieldAC == null) {
container.setErr(SyntaxError.CANT_GET_CONDITION_FIELD_AC, startPos.argvalue, idx);
return ValueParseResult.Err;
}
if ((!StringHelper.EqOp(curConditionField, ""))
&& (!curConditionFieldAC.validateFieldValue(curConditionField, strRealObj))) {
container.setErr(SyntaxError.INVALID_CONDITION_VALUE, startPos.argvalue, idx);
return ValueParseResult.Err;
}
container.addSyntaxObject(SyntaxObjectType.CONDITION_VALUE, strRealObj, startPos.argvalue, idx + 1);
retval = ValueParseResult.FreeText;
startPos.argvalue = idx + 1;
container.setvalid(true);
}
return retval;
}
/**
* gets the sql injection checker class for current db vendor.
* @return SqlInjectionChecker
* @throws Exception
*/
private SqlInjectionChecker getSqlInjectionChecker() throws Exception {
// This can not be done with reflection like:
// return (SqlInjectionChecker) Class.forName(props.getProperty(SQL_INJECTION)).newInstance();
// GWT lacks support of reflection.
if (((String)Config.GetValue(ConfigValues.DBEngine)).equalsIgnoreCase("postgres")){
return new PostgresSqlInjectionChecker();
}
else {
throw new IllegalStateException("Failed to get correct sql injection checker instance name :" + SqlInjectionChecker.class);
}
}
public SyntaxContainer analyzeSyntaxState(final String searchText, boolean final2) {
final SyntaxContainer syntaxContainer = new SyntaxContainer(searchText);
IConditionFieldAutoCompleter curConditionFieldAC = null;
IAutoCompleter curConditionRelationAC = null;
final List<String> freeTextObjSearched = new ArrayList<String>();
char[] searchCharArr = searchText.toCharArray();
int curStartPos = 0;
String tryNextObj = "";
boolean keepValid;
for (int idx = 0; idx < searchCharArr.length; idx++) {
final SyntaxObjectType curState = syntaxContainer.getState();
final char curChar = searchCharArr[idx];
if (mDisAllowedChars.contains(curChar)) {
syntaxContainer.setErr(SyntaxError.INVALID_CHARECTER, curStartPos, idx + 1);
return syntaxContainer;
}
if ((curChar == ' ') && (curState != SyntaxObjectType.CONDITION_RELATION)
&& (curState != SyntaxObjectType.COLON) && (curState != SyntaxObjectType.CONDITION_VALUE)
&& (curState != SyntaxObjectType.OR) && (curState != SyntaxObjectType.AND)) {
curStartPos += 1;
continue;
}
String strRealObj = searchText.substring(curStartPos, idx + 1);
String nextObject = strRealObj.toUpperCase();
switch (curState) {
case BEGIN:
// we have found a search-object
if (!mSearchObjectAC.validate(nextObject)) {
if (!mSearchObjectAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_SEARCH_OBJECT, curStartPos, idx - curStartPos + 1);
return syntaxContainer;
}
} else {
if (searchCharArr.length >= idx + 2) // Check that this
// maybe a plural
{
// Validate that the next character is an 's'
if (mPluralAC.validate(searchText.substring(idx + 1, idx + 1 + 1))) {
// Then just move things along.
idx++;
StringBuilder sb = new StringBuilder(nextObject);
sb.append('S');
nextObject = sb.toString();
}
}
syntaxContainer.addSyntaxObject(SyntaxObjectType.SEARCH_OBJECT, nextObject, curStartPos, idx + 1);
syntaxContainer.setvalid(true);
curStartPos = idx + 1;
}
break;
case SEARCH_OBJECT:
if (!mColonAC.validate(nextObject)) {
if (!mColonAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.COLON_NOT_NEXT_TO_SEARCH_OBJECT, curStartPos, idx + 1);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.COLON, nextObject, idx, idx + 1);
curStartPos = idx + 1;
syntaxContainer.setvalid(true);
}
break;
case CROSS_REF_OBJ:
String curRefObj = syntaxContainer.getPreviousSyntaxObject(0, SyntaxObjectType.CROSS_REF_OBJ);
curConditionRelationAC = mSearchObjectAC.getObjectRelationshipAutoCompleter(curRefObj);
if (idx + 1 < searchCharArr.length) {
tryNextObj = searchText.substring(curStartPos, idx + 2).toUpperCase();
}
if (curConditionRelationAC == null) {
syntaxContainer.setErr(SyntaxError.CONDITION_CANT_CREATE_RRELATIONS_AC, curStartPos, idx + 1);
return syntaxContainer;
}
if (mDotAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.DOT, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if ((!StringHelper.EqOp(tryNextObj, "")) && (curConditionRelationAC.validate(tryNextObj))) {
break; // i.e. the relation object has another charecter
} else if (curConditionRelationAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_RELATION, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if ((!curConditionRelationAC.validateCompletion(nextObject))
&& (!mDotAC.validateCompletion(nextObject))) {
syntaxContainer.setErr(SyntaxError.INVALID_POST_CROSS_REF_OBJ, curStartPos, idx + 1);
return syntaxContainer;
}
tryNextObj = "";
break;
case DOT:
curRefObj = syntaxContainer.getPreviousSyntaxObject(1, SyntaxObjectType.CROSS_REF_OBJ);
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(curRefObj);
if (curConditionFieldAC == null) {
syntaxContainer.setErr(SyntaxError.CANT_GET_CONDITION_FIELD_AC, curStartPos, idx);
return syntaxContainer;
}
if (!curConditionFieldAC.validate(nextObject)) {
if (!curConditionFieldAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_CONDITION_FILED, curStartPos, idx + 1);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_FIELD, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
}
break;
case AND:
case OR:
keepValid = false;
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(syntaxContainer.getSearchObjectStr());
if (curConditionFieldAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_FIELD, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mSearchObjectAC.isCrossReferece(nextObject, syntaxContainer.getFirst().getBody())) {
if (searchCharArr.length >= idx + 2) // Check that this
// maybe a plural
{
// Validate that the next character is an 's'
if (mPluralAC.validate(searchText.substring(idx + 1, idx + 1 + 1))) {
// Then just move things along.
idx++;
StringBuilder sb = new StringBuilder(nextObject);
sb.append('S');
nextObject = sb.toString();
}
}
syntaxContainer.addSyntaxObject(SyntaxObjectType.CROSS_REF_OBJ, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else {
RefObject<Integer> tempRefObject = new RefObject<Integer>(curStartPos);
ValueParseResult ans = handleValuePhrase(final2, searchText, idx, tempRefObject, syntaxContainer);
curStartPos = tempRefObject.argvalue;
if (ans != ValueParseResult.Err) {
if (ans == ValueParseResult.FreeText) {
curRefObj = syntaxContainer.getSearchObjectStr();
if (freeTextObjSearched.contains(curRefObj)) {
syntaxContainer.setErr(SyntaxError.FREE_TEXT_ALLOWED_ONCE_PER_OBJ, curStartPos, idx + 1);
return syntaxContainer;
}
freeTextObjSearched.add(curRefObj);
syntaxContainer.setvalid(true);
keepValid = true;
}
} else if ((!curConditionFieldAC.validateCompletion(nextObject))
&& (!mSearchObjectAC.validateCompletion(nextObject))) {
syntaxContainer.setErr(SyntaxError.INVALID_POST_OR_AND_PHRASE, curStartPos, idx + 1);
return syntaxContainer;
}
}
if (keepValid == false) {
syntaxContainer.setvalid(false);
}
break;
case COLON:
keepValid = false;
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(syntaxContainer.getSearchObjectStr());
if (curConditionFieldAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_FIELD, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mSortbyAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.SORTBY, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mPageAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.PAGE, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mSearchObjectAC.isCrossReferece(nextObject, syntaxContainer.getFirst().getBody())) {
if (searchCharArr.length >= idx + 2) // Check that this
// maybe a plural
{
// Validate that the next character is an 's'
if (mPluralAC.validate(searchText.substring(idx + 1, idx + 1 + 1))) {
// Then just move things along.
idx++;
StringBuilder sb = new StringBuilder(nextObject);
sb.append('S');
nextObject = sb.toString();
}
}
syntaxContainer.addSyntaxObject(SyntaxObjectType.CROSS_REF_OBJ, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else {
RefObject<Integer> tempRefObject2 = new RefObject<Integer>(curStartPos);
ValueParseResult ans = handleValuePhrase(final2, searchText, idx, tempRefObject2, syntaxContainer);
curStartPos = tempRefObject2.argvalue;
if (ans != ValueParseResult.Err) {
if (ans == ValueParseResult.FreeText) {
freeTextObjSearched.add(syntaxContainer.getSearchObjectStr());
}
keepValid = true;
} else if ((!curConditionFieldAC.validateCompletion(nextObject))
&& (!mSortbyAC.validateCompletion(nextObject))
&& (!mSearchObjectAC.validateCompletion(nextObject))) {
syntaxContainer.setErr(SyntaxError.INVALID_POST_COLON_PHRASE, curStartPos, idx + 1);
return syntaxContainer;
}
}
if (keepValid == false) {
syntaxContainer.setvalid(false);
}
break;
case CONDITION_VALUE:
nextObject = nextObject.trim();
if (nextObject.length() > 0) {
keepValid = false;
curRefObj = syntaxContainer.getSearchObjectStr();
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(curRefObj);
if (curConditionFieldAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_FIELD, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mSortbyAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.SORTBY, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mPageAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.PAGE, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mSearchObjectAC.isCrossReferece(nextObject, syntaxContainer.getFirst().getBody())) {
if (searchCharArr.length >= idx + 2) // Check that this
// maybe a
// plural
{
// Validate that the next character is an 's'
if (mPluralAC.validate(searchText.substring(idx + 1, idx + 1 + 1))) {
// Then just move things along.
idx++;
StringBuilder sb = new StringBuilder(nextObject);
sb.append('S');
nextObject = sb.toString();
}
}
syntaxContainer.addSyntaxObject(SyntaxObjectType.CROSS_REF_OBJ, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mAndAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.AND, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
} else if (mOrAC.validate(nextObject)) {
syntaxContainer.addSyntaxObject(SyntaxObjectType.OR, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
}
else if ((!curConditionFieldAC.validateCompletion(nextObject))
&& (!mSortbyAC.validateCompletion(nextObject))
&& (!mSearchObjectAC.validateCompletion(nextObject))
&& (!mAndAC.validateCompletion(nextObject)) && (!mOrAC.validateCompletion(nextObject))) {
RefObject<Integer> tempRefObject3 = new RefObject<Integer>(curStartPos);
ValueParseResult ans = handleValuePhrase(final2, searchText, idx, tempRefObject3, syntaxContainer);
curStartPos = tempRefObject3.argvalue;
if (ans != ValueParseResult.Err) {
if (ans == ValueParseResult.FreeText) {
if (freeTextObjSearched.contains(curRefObj)) {
syntaxContainer.setErr(SyntaxError.FREE_TEXT_ALLOWED_ONCE_PER_OBJ, curStartPos, idx + 1);
return syntaxContainer;
}
freeTextObjSearched.add(curRefObj);
syntaxContainer.setvalid(true);
keepValid = true;
}
} else {
syntaxContainer.setErr(SyntaxError.INVALID_POST_CONDITION_VALUE_PHRASE, curStartPos, idx + 1);
return syntaxContainer;
}
}
if (keepValid == false) {
syntaxContainer.setvalid(false);
}
}
break;
case CONDITION_FIELD:
curRefObj = syntaxContainer.getPreviousSyntaxObject(2, SyntaxObjectType.CROSS_REF_OBJ);
String curConditionField = syntaxContainer.getPreviousSyntaxObject(0, SyntaxObjectType.CONDITION_FIELD);
curConditionRelationAC = mSearchObjectAC
.getFieldRelationshipAutoCompleter(curRefObj, curConditionField);
if (curConditionRelationAC == null) {
syntaxContainer.setErr(SyntaxError.CONDITION_CANT_CREATE_RRELATIONS_AC, curStartPos, idx + 1);
return syntaxContainer;
}
if (idx + 1 < searchCharArr.length) {
tryNextObj = searchText.substring(curStartPos, idx + 2).toUpperCase();
if (curConditionRelationAC.validate(tryNextObj)) {
break;
}
}
if (!curConditionRelationAC.validate(nextObject)) {
if (!curConditionRelationAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_CONDITION_RELATION, curStartPos, idx + 1);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.CONDITION_RELATION, nextObject, curStartPos, idx + 1);
}
curStartPos = idx + 1;
syntaxContainer.setvalid(false);
tryNextObj = "";
break;
case CONDITION_RELATION: {
RefObject<Integer> tempRefObject4 = new RefObject<Integer>(curStartPos);
ValueParseResult ans = handleValuePhrase(final2, searchText, idx, tempRefObject4, syntaxContainer);
curStartPos = tempRefObject4.argvalue;
if (ans == ValueParseResult.Err) {
return syntaxContainer;
}
if (ans == ValueParseResult.FreeText) {
if (syntaxContainer.getPreviousSyntaxObjectType(2) == SyntaxObjectType.CROSS_REF_OBJ) {
curRefObj = syntaxContainer.getObjSingularName(syntaxContainer.getPreviousSyntaxObject(2,
SyntaxObjectType.CROSS_REF_OBJ));
if (freeTextObjSearched.contains(curRefObj)) {
syntaxContainer.setErr(SyntaxError.FREE_TEXT_ALLOWED_ONCE_PER_OBJ, curStartPos, idx + 1);
return syntaxContainer;
}
freeTextObjSearched.add(curRefObj);
}
}
}
break;
case SORTBY:
curConditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(syntaxContainer.getSearchObjectStr());
if (!curConditionFieldAC.validate(nextObject)) {
if (!curConditionFieldAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_SORT_FIELD, curStartPos, idx + 1);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.SORT_FIELD, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
syntaxContainer.setvalid(true);
}
break;
case PAGE:
Integer pageNumber = IntegerCompat.tryParse(nextObject);
if (pageNumber == null) {
syntaxContainer.setErr(SyntaxError.INVALID_CHARECTER, curStartPos, idx + 1);
return syntaxContainer;
} else {
final StringBuilder buff = new StringBuilder();
int pos = idx;
// parsing the whole page number (can be more than one char)
while (pos < searchText.length() - 1 && Character.isDigit(nextObject.charAt(0))) {
buff.append(nextObject);
pos++;
strRealObj = searchText.substring(pos, pos + 1);
nextObject = strRealObj.toUpperCase();
}
buff.append(nextObject);
syntaxContainer.addSyntaxObject(SyntaxObjectType.PAGE_VALUE, buff.toString(), curStartPos, idx + buff.length());
// update index position
idx = pos + 1;
syntaxContainer.setvalid(true);
}
break;
case SORT_FIELD:
if (!mSortDirectionAC.validate(nextObject)) {
if (!mSortDirectionAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_SORT_DIRECTION, curStartPos, idx + 1);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.SORT_DIRECTION, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
syntaxContainer.setvalid(true);
}
break;
case PAGE_VALUE:
if (curChar != ' ') {
syntaxContainer.setErr(SyntaxError.NOTHING_COMES_AFTER_PAGE_VALUE, curStartPos, idx + 1);
return syntaxContainer;
}
break;
case SORT_DIRECTION:
if (!mPageAC.validate(nextObject)) {
if (!mPageAC.validateCompletion(nextObject)) {
syntaxContainer.setErr(SyntaxError.INVALID_PAGE_FEILD, curStartPos, idx);
return syntaxContainer;
}
} else {
syntaxContainer.addSyntaxObject(SyntaxObjectType.PAGE, nextObject, curStartPos, idx + 1);
curStartPos = idx + 1;
syntaxContainer.setvalid(true);
}
break;
default:
syntaxContainer.setErr(SyntaxError.UNIDENTIFIED_STATE, curStartPos, idx);
return syntaxContainer;
}
}
return syntaxContainer;
}
public SyntaxContainer getCompletion(String searchText) {
SyntaxContainer retval = analyzeSyntaxState(searchText, false);
if (retval.getError() == SyntaxError.NO_ERROR) {
IConditionFieldAutoCompleter conditionFieldAC;
IAutoCompleter conditionRelationAC;
IConditionValueAutoCompleter conditionValueAC;
int lastIdx = retval.getLastHandledIndex();
String curPartialWord = "";
if (lastIdx < searchText.length()) {
curPartialWord = searchText.substring(lastIdx, searchText.length());
curPartialWord = curPartialWord.trim();
}
SyntaxObjectType curState = retval.getState();
for (int idx = 0; idx < mStateMap.get(curState).length; idx++) {
switch (mStateMap.get(curState)[idx]) {
case SEARCH_OBJECT:
retval.addToACList(mSearchObjectAC.getCompletion(curPartialWord));
break;
case CROSS_REF_OBJ:
IAutoCompleter crossRefAC = mSearchObjectAC.getCrossRefAutoCompleter(retval.getFirst().getBody());
if (crossRefAC != null) {
retval.addToACList(crossRefAC.getCompletion(curPartialWord));
}
break;
case DOT:
retval.addToACList(mDotAC.getCompletion(curPartialWord));
break;
case COLON:
retval.addToACList(mColonAC.getCompletion(curPartialWord));
break;
case AND:
retval.addToACList(mAndAC.getCompletion(curPartialWord));
break;
case OR:
retval.addToACList(mOrAC.getCompletion(curPartialWord));
break;
case CONDITION_FIELD:
String relObj = retval.getPreviousSyntaxObject(1, SyntaxObjectType.CROSS_REF_OBJ);
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(relObj);
if (conditionFieldAC != null) {
retval.addToACList(conditionFieldAC.getCompletion(curPartialWord));
}
break;
case CONDITION_RELATION: {
if (curState == SyntaxObjectType.CONDITION_FIELD) {
relObj = retval.getPreviousSyntaxObject(2, SyntaxObjectType.CROSS_REF_OBJ);
String fldName = retval.getPreviousSyntaxObject(0, SyntaxObjectType.CONDITION_FIELD);
conditionRelationAC = mSearchObjectAC.getFieldRelationshipAutoCompleter(relObj, fldName);
} else // curState == SyntaxObjectType.CROSS_REF_OBJ
{
relObj = retval.getPreviousSyntaxObject(0, SyntaxObjectType.CROSS_REF_OBJ);
conditionRelationAC = mSearchObjectAC.getObjectRelationshipAutoCompleter(relObj);
}
if (conditionRelationAC != null) {
retval.addToACList(conditionRelationAC.getCompletion(curPartialWord));
}
}
break;
case CONDITION_VALUE: {
relObj = retval.getPreviousSyntaxObject(3, SyntaxObjectType.CROSS_REF_OBJ);
String fldName = retval.getPreviousSyntaxObject(1, SyntaxObjectType.CONDITION_FIELD);
conditionValueAC = mSearchObjectAC.getFieldValueAutoCompleter(relObj, fldName);
if (conditionValueAC != null) {
retval.addToACList(conditionValueAC.getCompletion(curPartialWord));
}
}
break;
case SORTBY:
retval.addToACList(mSortbyAC.getCompletion(curPartialWord));
break;
case PAGE:
retval.addToACList(mPageAC.getCompletion(curPartialWord));
break;
case SORT_FIELD:
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(retval.getSearchObjectStr());
if (conditionFieldAC != null) {
retval.addToACList(conditionFieldAC.getCompletion(curPartialWord));
}
break;
case SORT_DIRECTION:
retval.addToACList(mSortDirectionAC.getCompletion(curPartialWord));
break;
}
}
}
return retval;
}
public String generateQueryFromSyntaxContainer(SyntaxContainer syntax, boolean isSafe) {
String retval = "";
if (syntax.getvalid()) {
retval = generateSqlFromSyntaxContainer(syntax, isSafe);
}
return retval;
}
private String generateFromStatement(SyntaxContainer syntax) {
java.util.LinkedList<String> innerJoins = new java.util.LinkedList<String>();
java.util.ArrayList<String> refObjList = syntax.getCrossRefObjList();
String searchObjStr = syntax.getSearchObjectStr();
if (refObjList.size() > 0) {
if (StringHelper.EqOp(searchObjStr, SearchObjects.TEMPLATE_OBJ_NAME)) {
innerJoins.addFirst(mSearchObjectAC.getInnerJoin(SearchObjects.TEMPLATE_OBJ_NAME,
SearchObjects.VM_OBJ_NAME));
if (refObjList.contains(SearchObjects.VM_OBJ_NAME)) {
refObjList.remove(SearchObjects.VM_OBJ_NAME);
}
if (refObjList.contains(SearchObjects.VDC_USER_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.VDC_USER_OBJ_NAME));
refObjList.remove(SearchObjects.VDC_USER_OBJ_NAME);
}
if (refObjList.contains(SearchObjects.VDS_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.VDS_OBJ_NAME));
refObjList.remove(SearchObjects.VDS_OBJ_NAME);
}
if (refObjList.contains(SearchObjects.AUDIT_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.AUDIT_OBJ_NAME));
refObjList.remove(SearchObjects.AUDIT_OBJ_NAME);
}
}
else if (StringHelper.EqOp(searchObjStr, SearchObjects.VDS_OBJ_NAME)) {
if ((refObjList.contains(SearchObjects.VDC_USER_OBJ_NAME))
|| (refObjList.contains(SearchObjects.TEMPLATE_OBJ_NAME))) {
innerJoins.addFirst(mSearchObjectAC.getInnerJoin(SearchObjects.VDS_OBJ_NAME,
SearchObjects.VM_OBJ_NAME));
if (refObjList.contains(SearchObjects.VM_OBJ_NAME)) {
refObjList.remove(SearchObjects.VM_OBJ_NAME);
}
}
if (refObjList.contains(SearchObjects.VDC_USER_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.VDC_USER_OBJ_NAME));
refObjList.remove(SearchObjects.VDC_USER_OBJ_NAME);
}
if (refObjList.contains(SearchObjects.TEMPLATE_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.TEMPLATE_OBJ_NAME));
refObjList.remove(SearchObjects.TEMPLATE_OBJ_NAME);
}
}
else if (StringHelper.EqOp(searchObjStr, SearchObjects.VDC_USER_OBJ_NAME)) {
if ((refObjList.contains(SearchObjects.VDS_OBJ_NAME))
|| (refObjList.contains(SearchObjects.TEMPLATE_OBJ_NAME))) {
innerJoins.addFirst(mSearchObjectAC.getInnerJoin(SearchObjects.VDC_USER_OBJ_NAME,
SearchObjects.VM_OBJ_NAME));
if (refObjList.contains(SearchObjects.VM_OBJ_NAME)) {
refObjList.remove(SearchObjects.VM_OBJ_NAME);
}
}
if (refObjList.contains(SearchObjects.VDS_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.VDS_OBJ_NAME));
refObjList.remove(SearchObjects.VDS_OBJ_NAME);
}
if (refObjList.contains(SearchObjects.TEMPLATE_OBJ_NAME)) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.TEMPLATE_OBJ_NAME));
refObjList.remove(SearchObjects.TEMPLATE_OBJ_NAME);
}
}
else if (StringHelper.EqOp(searchObjStr, SearchObjects.AUDIT_OBJ_NAME)) {
if (refObjList.contains(SearchObjects.TEMPLATE_OBJ_NAME)) {
innerJoins.addFirst(mSearchObjectAC.getInnerJoin(SearchObjects.AUDIT_OBJ_NAME,
SearchObjects.VM_OBJ_NAME));
innerJoins.addLast(mSearchObjectAC.getInnerJoin(SearchObjects.VM_OBJ_NAME,
SearchObjects.TEMPLATE_OBJ_NAME));
refObjList.remove(SearchObjects.TEMPLATE_OBJ_NAME);
if (refObjList.contains(SearchObjects.VM_OBJ_NAME)) {
refObjList.remove(SearchObjects.VM_OBJ_NAME);
}
}
}
}
for (String cro : refObjList) {
innerJoins.addLast(mSearchObjectAC.getInnerJoin(searchObjStr, cro));
}
innerJoins.addFirst(mSearchObjectAC.getRelatedTableName(searchObjStr));
StringBuilder sb = new StringBuilder();
for (String part : innerJoins) {
sb.append(" ");
sb.append(part);
sb.append(" ");
}
return sb.toString();
}
private String generateSqlFromSyntaxContainer(SyntaxContainer syntax, boolean isSafe) {
String retval = "";
if (syntax.getvalid()) {
ListIterator<SyntaxObject> objIter = syntax.listIterator(0);
IConditionFieldAutoCompleter conditionFieldAC;
LinkedList<String> whereBuilder = new java.util.LinkedList<String>();
String searchObjStr = syntax.getSearchObjectStr();
String sortByPhrase = "";
String fromStatement = "";
String pageNumber = "";
while (objIter.hasNext()) {
SyntaxObject obj = objIter.next();
switch (obj.getType()) {
case SEARCH_OBJECT:
fromStatement = generateFromStatement(syntax);
break;
case OR:
case AND:
whereBuilder.addLast(obj.getBody());
break;
case CONDITION_VALUE:
whereBuilder.addLast(generateConditionStatment(obj, syntax.listIterator(objIter.previousIndex()),
searchObjStr, syntax.getCaseSensitive(),isSafe));
break;
case SORTBY:
break;
case PAGE_VALUE:
pageNumber = obj.getBody();
break;
case SORT_FIELD:
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(searchObjStr);
sortByPhrase =
StringFormat.format(" ORDER BY %1$s", conditionFieldAC.getDbFieldName(obj.getBody()));
break;
case SORT_DIRECTION:
sortByPhrase = StringFormat.format("%1$s %2$s", sortByPhrase, obj.getBody());
break;
default:
break;
}
}
// implying precedence rules
String[] lookFor = { "AND", "OR" };
for (int idx = 0; idx < lookFor.length; idx++) {
boolean found = true;
while (found) {
found = false;
java.util.ListIterator<String> iter = whereBuilder.listIterator(0);
while (iter.hasNext()) {
String queryPart = iter.next();
if (StringHelper.EqOp(queryPart, lookFor[idx])) {
iter.remove();
String nextPart = iter.next();
iter.remove();
String prevPart = iter.previous();
iter.set(StringFormat.format("( %1$s %2$s %3$s )", prevPart, queryPart, nextPart));
found = true;
break;
}
}
}
}
// adding WHERE if required and All implicit AND
StringBuilder wherePhrase = new StringBuilder();
if (whereBuilder.size() > 0) {
wherePhrase.append(" WHERE ");
java.util.ListIterator<String> iter = whereBuilder.listIterator(0);
while (iter.hasNext()) {
String queryPart = iter.next();
wherePhrase.append(queryPart);
if (iter.hasNext()) {
wherePhrase.append(" AND ");
}
}
}
// adding the sorting part if required
if (StringHelper.EqOp(sortByPhrase, "")) {
sortByPhrase = StringFormat.format(" ORDER BY %1$s", mSearchObjectAC.getDefaultSort(searchObjStr));
}
// adding the paging phrase
String pagePhrase = getPagePhrase(syntax, pageNumber);
String primeryKey = mSearchObjectAC.getPrimeryKeyName(searchObjStr);
String tableName = mSearchObjectAC.getRelatedTableName(searchObjStr);
String tableNameWithOutTags = mSearchObjectAC.getRelatedTableNameWithOutTags(searchObjStr);
String innerQuery =
StringFormat.format("SELECT %1$s.%2$s FROM %3$s %4$s", tableName, primeryKey, fromStatement,
wherePhrase);
// only audit log search supports the SearchFrom which enables getting records starting from a certain
// audit_log_id, this is done to make search queries from the client more efficient and eliminate the client
// from registering to such queries and comparing last data with previous.
String inQuery =
(primeryKey.equals("audit_log_id")
?
StringFormat.format("SELECT * FROM %1$s WHERE ( %2$s > %3$s and %2$s IN (%4$s)",
tableNameWithOutTags,
primeryKey,
syntax.getSearchFrom(),
innerQuery)
:
StringFormat.format("SELECT * FROM %1$s WHERE ( %2$s IN (%3$s)", tableNameWithOutTags,
primeryKey, innerQuery));
retval =
StringFormat.format(Config.<String> GetValue(ConfigValues.DBSearchTemplate), sortByPhrase, inQuery,
pagePhrase);
// Check for sql injection if query is not safe
if (! isSafe) {
if (sqlInjectionChecker.hasSqlInjection(retval)) {
throw new SqlInjectionException();
}
}
log.trace("Search: " + retval);
}
return retval;
}
private String getPagePhrase(SyntaxContainer syntax, String pageNumber) {
String result = "";
Integer page = IntegerCompat.tryParse(pageNumber);
if (page == null) {
page = 1;
}
String pagingTypeStr = Config.<String> GetValue(ConfigValues.DBPagingType);
if (EnumCompat.IsDefined(PagingType.class, pagingTypeStr)) {
PagingType pagingType = EnumUtils.valueOf(PagingType.class, pagingTypeStr, true);
String pagingSyntax = Config.<String> GetValue(ConfigValues.DBPagingSyntax);
switch (pagingType) {
case Range:
result = StringFormat
.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, page * syntax.getMaxCount());
break;
case Offset:
result = StringFormat.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, syntax.getMaxCount());
break;
}
} else {
log.error(StringFormat.format("Unknown paging type %1$s", pagingTypeStr));
}
return result;
}
private enum ConditionType {
None,
FreeText,
FreeTextSpecificObj,
ConditionWithDefaultObj,
ConditionwithSpesificObj;
}
private String generateConditionStatment(SyntaxObject obj, ListIterator<SyntaxObject> objIter,
final String searchObjStr, final boolean caseSensitive, final boolean issafe) {
IConditionFieldAutoCompleter conditionFieldAC;
IConditionValueAutoCompleter conditionValueAC = null;
// check for sql injection
String originalValue = obj.getBody();
String customizedValue = originalValue;
if (!issafe) {
// Enforce escape characters before special characters
customizedValue = SqlInjectionChecker.enforceEscapeCharacters(originalValue);
}
String customizedRelation;
String fieldName = "";
String objName;
ConditionType conditionType;
SyntaxObject prev = objIter.previous();
if (prev.getType() != SyntaxObjectType.CONDITION_RELATION) {
// free text of default search object
customizedRelation = "=";
objName = searchObjStr;
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(searchObjStr);
conditionType = ConditionType.FreeText;
} else {
customizedRelation = prev.getBody();
prev = objIter.previous();
if (prev.getType() == SyntaxObjectType.CROSS_REF_OBJ) { // free text
// search
// for some
// object
objName = prev.getBody();
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(objName);
conditionType = ConditionType.FreeTextSpecificObj;
} else // if (prev.getType() == SyntaxObjectType.CONDITION_FIELD)
{
fieldName = prev.getBody();
prev = objIter.previous();
if (prev.getType() != SyntaxObjectType.DOT) {
// standard condition with default AC (search obj)
objName = searchObjStr;
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(searchObjStr);
conditionType = ConditionType.ConditionWithDefaultObj;
} else {
// standard condition with specific AC
prev = objIter.previous();
objName = prev.getBody();
conditionFieldAC = mSearchObjectAC.getFieldAutoCompleter(objName);
conditionType = ConditionType.ConditionwithSpesificObj;
}
}
conditionValueAC = conditionFieldAC.getFieldValueAutoCompleter(fieldName);
}
final BaseConditionFieldAutoCompleter conditionAsBase =
(BaseConditionFieldAutoCompleter) ((conditionFieldAC instanceof BaseConditionFieldAutoCompleter) ? conditionFieldAC
: null);
final Class<?> curType = conditionAsBase != null ? conditionAsBase.getTypeDictionary().get(fieldName) : null;
if (curType == String.class && !StringHelper.isNullOrEmpty(customizedValue)
&& !"''".equals(customizedValue) && !"'*'".equals(customizedValue)) {
customizedValue =
StringFormat.format(BaseConditionFieldAutoCompleter.getI18NPrefix() + "%1$s", customizedValue);
}
if (conditionValueAC != null) {
customizedValue = StringFormat.format("'%1$s'",
conditionValueAC.convertFieldEnumValueToActualValue(obj.getBody()));
} else if ("".equals(fieldName) /* search on all relevant fields */ ||
(conditionFieldAC.getDbFieldType(fieldName).equals(String.class))) {
customizedValue = customizedValue.replace('*', '%');
/* enable case-insensitive search by changing operation to I/LIKE*/
if ("=".equals(customizedRelation)) {
customizedRelation = BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive);
} else if ("!=".equals(customizedRelation)) {
customizedRelation = "NOT " + BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive);
}
}
return buildCondition(caseSensitive,
conditionFieldAC,
customizedValue,
customizedRelation,
fieldName,
objName,
conditionType);
}
final String buildCondition(boolean caseSensitive,
IConditionFieldAutoCompleter conditionFieldAC,
String customizedValue,
String customizedRelation,
String fieldName,
String objName,
ConditionType conditionType) {
final String tableName = mSearchObjectAC.getRelatedTableName(objName);
switch (conditionType) {
case FreeText:
case FreeTextSpecificObj:
return conditionFieldAC.buildFreeTextConditionSql(tableName, customizedRelation, customizedValue, caseSensitive);
case ConditionWithDefaultObj:
case ConditionwithSpesificObj:
return conditionFieldAC.buildConditionSql(fieldName, customizedValue, customizedRelation, tableName, caseSensitive);
default:
return "";
}
}
private static Log log = LogFactory.getLog(SyntaxChecker.class);
}
|
package gov.nih.nci.caadapter.hl7.validation;
import gov.nih.nci.caadapter.common.Message;
import gov.nih.nci.caadapter.common.MessageResources;
import gov.nih.nci.caadapter.common.validation.ValidatorResult;
import gov.nih.nci.caadapter.common.validation.ValidatorResults;
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class HL7V3MessageValidator {
private Validator validator = null;
ValidatorResults theValidatorResults = new ValidatorResults();
/**
* @param xsdSchema is XSD associated with the HL7 v3 message
*/
public HL7V3MessageValidator() {}
public HL7V3MessageValidator(String xsdSchema) {
SchemaFactory factory = SchemaFactory.newInstance("http:
File schemaLocation = new File(xsdSchema);
Schema schema=null;
try {
schema = factory.newSchema(schemaLocation);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
validator = schema.newValidator();
}
/**
* @param xmlString is the HL7 v3 xml string to be validated
*/
public ValidatorResults validate(String xmlString) {
if (validator == null) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Error loading XSD for this Message!"});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
// 4. Parse the document you want to check.
ByteArrayInputStream domSource = new ByteArrayInputStream(xmlString.getBytes());
Source source = new StreamSource(domSource);
// 5. Check the document
try {
validator.validate(source);
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"The HL7 v3 message is valid against xsd file"});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
catch (SAXException ex) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Not Valid:" + ex.getMessage()});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
catch (Exception ex) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Unexpected Error:" + ex.getMessage()});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
}
/**
* @param xmlString is the HL7 v3 xml string to be validated
* @param xsdSchema is the XSD associated with the HL7 v3 message
*/
public ValidatorResults validate(String xmlString, String xsdSchema) {
Validator validator = getValidator(xsdSchema);
if (validator == null) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Error loading XSD for this Message!"});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
// 4. Parse the document you want to check.
ByteArrayInputStream domSource = new ByteArrayInputStream(xmlString.getBytes());
Source source = new StreamSource(domSource);
// 5. Check the document
try {
validator.validate(source);
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"The HL7 v3 message is valid against xsd file"});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
}
catch (SAXException ex) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Not Valid:" + ex.getMessage()});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
catch (Exception ex) {
Message msg = MessageResources.getMessage("EMP_IN", new Object[]{"Unexpected Error:" + ex.getMessage()});
theValidatorResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
return theValidatorResults;
}
return theValidatorResults;
}
private Validator getValidator(String xsdSchema) {
if (validator == null) {
SchemaFactory factory = SchemaFactory.newInstance("http:
File schemaLocation = new File(xsdSchema);
Schema schema=null;
try {
schema = factory.newSchema(schemaLocation);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
validator = schema.newValidator();
return validator;
}
else {
return validator;
}
}
}
|
package com.powsybl.cgmes.extensions;
import com.google.auto.service.AutoService;
import com.powsybl.commons.extensions.ExtensionAdderProvider;
import com.powsybl.iidm.network.Network;
/**
* @author Miora Vedelago <miora.ralambotiana at rte-france.com>
*/
@AutoService(ExtensionAdderProvider.class)
public class BaseVoltageMappingAdderImplProvider implements ExtensionAdderProvider<Network, BaseVoltageMapping, BaseVoltageMappingAdderImpl> {
@Override
public String getImplementationName() {
return "Default";
}
@Override
public String getExtensionName() {
return BaseVoltageMapping.NAME;
}
@Override
public Class<? super BaseVoltageMappingAdderImpl> getAdderClass() {
return BaseVoltageMappingAdderImpl.class;
}
@Override
public BaseVoltageMappingAdderImpl newAdder(Network extendable) {
return new BaseVoltageMappingAdderImpl(extendable);
}
}
|
package com.orientechnologies.orient.core.command.script.transformer.result;
import com.orientechnologies.orient.core.command.script.transformer.OScriptTransformer;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultInternal;
import java.util.Map;
public class MapTransformer implements OResultTransformer<Map<Object, Object>> {
private OScriptTransformer transformer;
public MapTransformer(OScriptTransformer transformer) {
this.transformer = transformer;
}
@Override
public OResult transform(Map<Object, Object> element) {
OResultInternal internal = new OResultInternal();
element.forEach((key, val) -> {
if (transformer.doesHandleResult(val)) {
internal.setProperty(key.toString(), transformer.toResult(val));
} else {
internal.setProperty(key.toString(), val);
}
});
return internal;
}
}
|
package img;
import java.io.InputStream;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
public class SafeImage {
Image image;
/**
* Constructs a SafeImage of the image file at the given path.
* This constructor skips giving a width and height.
* Therefore, if the image is not found, then the there will be a
* empty image of size 1x1 pixels in its place.
*
* @param path - the String representation of the path of the image file
*/
public SafeImage(String path) {
this(path, 1, 1);
}
/**
* Constructs a SafeImage of the image file at the given path.
* If the image is not found, a blank backup image will be created in
* its place with the given width and height.
*
* @param path - the String representation of the path of the image file
* @param width - an integer to be the width of the backup image.
* @param height - an integer to be the height of the backup image.
*/
public SafeImage(String path, int width, int height) {
InputStream imageStream = SafeImage.class.getResourceAsStream(path);
if (imageStream != null) {
image = new Image(SafeImage.class.getResourceAsStream(path));
} else {
image = new WritableImage(width, height);
}
}
/**
* Returns the Image object held by this SafeImage
*
* @return an Image object
*/
public Image get() {
return image;
}
}
|
package daq.pubber;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.google.common.base.Preconditions;
import com.google.daq.mqtt.util.CloudIotConfig;
import java.util.HashMap;
import udmi.schema.Entry;
import udmi.schema.Config;
import udmi.schema.Firmware;
import udmi.schema.Metadata;
import udmi.schema.PointPointsetConfig;
import udmi.schema.PointsetConfig;
import udmi.schema.PointsetEvent;
import udmi.schema.PointsetState;
import udmi.schema.State;
import udmi.schema.SystemConfig;
import udmi.schema.SystemEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import udmi.schema.SystemState;
public class Pubber {
private static final Logger LOG = LoggerFactory.getLogger(Pubber.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.setDateFormat(new ISO8601DateFormat())
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
private static final String POINTSET_TOPIC = "events/pointset";
private static final String SYSTEM_TOPIC = "events/system";
private static final String STATE_TOPIC = "state";
private static final String CONFIG_TOPIC = "config";
private static final String ERROR_TOPIC = "errors";
private static final int MIN_REPORT_MS = 200;
private static final int DEFAULT_REPORT_SEC = 10;
private static final int CONFIG_WAIT_TIME_MS = 10000;
private static final int STATE_THROTTLE_MS = 2000;
private static final String CONFIG_ERROR_STATUS_KEY = "config_error";
private static final int LOGGING_MOD_COUNT = 10;
public static final String KEY_SITE_PATH_FORMAT = "%s/devices/%s/%s_private.pkcs8";
private static final String OUT_DIR = "out";
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private final Configuration configuration;
private final AtomicInteger messageDelayMs = new AtomicInteger(DEFAULT_REPORT_SEC * 1000);
private final CountDownLatch configLatch = new CountDownLatch(1);
private final State deviceState = new State();
private final ExtraPointsetEvent devicePoints = new ExtraPointsetEvent();
private final Set<AbstractPoint> allPoints = new HashSet<>();
private MqttPublisher mqttPublisher;
private ScheduledFuture<?> scheduledFuture;
private long lastStateTimeMs;
private int sendCount;
private boolean stateDirty;
static class ExtraPointsetEvent extends PointsetEvent {
// This extraField exists only to trigger schema parsing errors.
public Object extraField;
}
public static void main(String[] args) throws Exception {
final Pubber pubber;
if (args.length == 1) {
pubber = new Pubber(args[0]);
} else if (args.length == 4) {
pubber = new Pubber(args[0], args[1], args[2], args[3]);
} else {
throw new IllegalArgumentException("Usage: config_file or { project_id site_path/ device_id serial_no }");
}
pubber.initialize();
pubber.startConnection();
LOG.info("Done with main");
}
public Pubber(String configPath) {
File configFile = new File(configPath);
try {
configuration = OBJECT_MAPPER.readValue(configFile, Configuration.class);
} catch (Exception e) {
throw new RuntimeException("While reading config " + configFile.getAbsolutePath(), e);
}
}
public Pubber(String projectId, String sitePath, String deviceId, String serialNo) {
configuration = new Configuration();
configuration.projectId = projectId;
configuration.sitePath = sitePath;
configuration.deviceId = deviceId;
configuration.serialNo = serialNo;
}
private void loadDeviceMetadata() {
Preconditions.checkState(configuration.sitePath != null, "sitePath not defined");
Preconditions.checkState(configuration.deviceId != null, "deviceId not defined");
File devicesFile = new File(new File(configuration.sitePath), "devices");
File deviceDir = new File(devicesFile, configuration.deviceId);
File deviceMetadataFile = new File(deviceDir, "metadata.json");
try {
Metadata metadata = OBJECT_MAPPER.readValue(deviceMetadataFile, Metadata.class);
if (metadata.cloud != null) {
configuration.algorithm = metadata.cloud.auth_type.value();
LOG.info("Configuring with key type " + configuration.algorithm);
}
} catch (Exception e) {
throw new RuntimeException("While reading metadata file " + deviceMetadataFile.getAbsolutePath(), e);
}
}
private void loadCloudConfig() {
Preconditions.checkState(configuration.sitePath != null, "sitePath not defined in configuration");
File cloudConfig = new File(new File(configuration.sitePath), "cloud_iot_config.json");
try {
CloudIotConfig cloudIotConfig = OBJECT_MAPPER.readValue(cloudConfig, CloudIotConfig.class);
configuration.registryId = cloudIotConfig.registry_id;
configuration.cloudRegion = cloudIotConfig.cloud_region;
} catch (Exception e) {
throw new RuntimeException("While reading config file " + cloudConfig.getAbsolutePath(), e);
}
}
private void initializeDevice() {
if (configuration.sitePath != null) {
loadCloudConfig();
loadDeviceMetadata();
}
LOG.info(String.format("Starting pubber %s, serial %s, mac %s, extra %s, gateway %s",
configuration.deviceId, configuration.serialNo, configuration.macAddr, configuration.extraField,
configuration.gatewayId));
deviceState.system = new SystemState();
deviceState.system.operational = true;
deviceState.system.serial_no = configuration.serialNo;
deviceState.system.make_model = "DAQ_pubber";
deviceState.system.firmware = new Firmware();
deviceState.system.firmware.version = "v1";
deviceState.system.statuses = new HashMap<>();
deviceState.pointset = new PointsetState();
deviceState.pointset.points = new HashMap<>();
devicePoints.points = new HashMap<>();
devicePoints.extraField = configuration.extraField;
addPoint(new RandomPoint("superimposition_reading", true,0, 100, "Celsius"));
addPoint(new RandomPoint("recalcitrant_angle", true,40, 40, "deg" ));
addPoint(new RandomBoolean("faulty_finding", false));
stateDirty = true;
}
private synchronized void maybeRestartExecutor(int intervalMs) {
if (scheduledFuture == null || intervalMs != messageDelayMs.get()) {
cancelExecutor();
messageDelayMs.set(intervalMs);
startExecutor();
}
}
private synchronized void startExecutor() {
Preconditions.checkState(scheduledFuture == null);
int delay = messageDelayMs.get();
LOG.info("Starting executor with send message delay " + delay);
scheduledFuture = executor
.scheduleAtFixedRate(this::sendMessages, delay, delay, TimeUnit.MILLISECONDS);
}
private synchronized void cancelExecutor() {
if (scheduledFuture != null) {
scheduledFuture.cancel(false);
scheduledFuture = null;
}
}
private void sendMessages() {
try {
updatePoints();
sendDeviceMessage(configuration.deviceId);
if (sendCount % LOGGING_MOD_COUNT == 0) {
publishLogMessage(configuration.deviceId,"Sent " + sendCount + " messages");
}
if (stateDirty) {
publishStateMessage();
}
sendCount++;
} catch (Exception e) {
LOG.error("Fatal error during execution", e);
terminate();
}
}
private void updatePoints() {
allPoints.forEach(point -> {
point.updateData();
updateState(point);
});
}
private void updateState(AbstractPoint point) {
if (point.isDirty()) {
deviceState.pointset.points.put(point.getName(), point.getState());
stateDirty = true;
}
}
private void terminate() {
try {
info("Terminating");
mqttPublisher.close();
cancelExecutor();
} catch (Exception e) {
info("Error terminating: " + e.getMessage());
}
}
private void startConnection() throws InterruptedException {
connect();
boolean result = configLatch.await(CONFIG_WAIT_TIME_MS, TimeUnit.MILLISECONDS);
LOG.info("synchronized start config result " + result);
if (!result) {
mqttPublisher.close();
}
}
private void addPoint(AbstractPoint point) {
String pointName = point.getName();
if (devicePoints.points.put(pointName, point.getData()) != null) {
throw new IllegalStateException("Duplicate pointName " + pointName);
}
updateState(point);
allPoints.add(point);
}
private void initialize() {
initializeDevice();
File outDir = new File(OUT_DIR);
try {
outDir.mkdir();
} catch (Exception e) {
throw new RuntimeException("While creating out dir " + outDir.getPath(), e);
}
Preconditions.checkNotNull(configuration.deviceId, "configuration deviceId not defined");
if (configuration.sitePath != null && configuration.keyFile != null) {
configuration.keyFile = String.format(KEY_SITE_PATH_FORMAT, configuration.sitePath,
configuration.deviceId, getDeviceKeyPrefix());
}
Preconditions.checkState(mqttPublisher == null, "mqttPublisher already defined");
Preconditions.checkNotNull(configuration.keyFile, "configuration keyFile not defined");
LOG.info("Loading device key file from " + configuration.keyFile);
configuration.keyBytes = getFileBytes(configuration.keyFile);
mqttPublisher = new MqttPublisher(configuration, this::reportError);
if (configuration.gatewayId != null) {
mqttPublisher.registerHandler(configuration.gatewayId, CONFIG_TOPIC,
this::gatewayHandler, Config.class);
mqttPublisher.registerHandler(configuration.gatewayId, ERROR_TOPIC,
this::errorHandler, GatewayError.class);
}
mqttPublisher.registerHandler(configuration.deviceId, CONFIG_TOPIC,
this::configHandler, Config.class);
}
private String getDeviceKeyPrefix() {
return configuration.algorithm.startsWith("RS") ? "rsa" : "ec";
}
private void connect() {
try {
mqttPublisher.connect(configuration.deviceId);
LOG.info("Connection complete.");
} catch (Exception e) {
LOG.error("Connection error", e);
LOG.error("Forcing termination");
System.exit(-1);
}
}
private void reportError(Exception toReport) {
if (toReport != null) {
LOG.error("Error receiving message: " + toReport);
Entry report = entryFromException(toReport);
deviceState.system.statuses.put(CONFIG_ERROR_STATUS_KEY, report);
publishStateMessage();
if (configLatch.getCount() > 0) {
LOG.warn("Releasing startup latch because reported error");
configHandler(null);
}
} else {
Entry previous = deviceState.system.statuses.remove(CONFIG_ERROR_STATUS_KEY);
if (previous != null) {
publishStateMessage();
}
}
}
private Entry entryFromException(Exception e) {
Entry entry = new Entry();
entry.message = e.toString();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(outputStream));
entry.detail = outputStream.toString();
entry.category = e.getStackTrace()[0].getClassName();
entry.level = 800;
return entry;
}
private void info(String msg) {
LOG.info(msg);
}
private void gatewayHandler(Config config) {
info(String.format("%s gateway config %s", getTimestamp(), isoConvert(config.timestamp)));
}
private void configHandler(Config config) {
try {
File configOut = new File(OUT_DIR, "config.json");
try {
OBJECT_MAPPER.writeValue(configOut, config);
} catch (Exception e) {
throw new RuntimeException("While writing config " + configOut.getPath(), e);
}
final int actualInterval;
if (config != null) {
String state_etag = deviceState.pointset == null ? null : deviceState.pointset.state_etag;
info(String.format("%s received new config %s %s",
getTimestamp(), state_etag, isoConvert(config.timestamp)));
deviceState.system.last_config = config.timestamp;
actualInterval = updateSystemConfig(config.pointset);
updatePointsetConfig(config.pointset);
} else {
info(getTimestamp() + " defaulting empty config");
actualInterval = DEFAULT_REPORT_SEC * 1000;
}
maybeRestartExecutor(actualInterval);
configLatch.countDown();
publishStateMessage();
reportError(null);
} catch (Exception e) {
reportError(e);
}
}
private String getTimestamp() {
return isoConvert(new Date());
}
private String isoConvert(Date timestamp) {
try {
String dateString = OBJECT_MAPPER.writeValueAsString(timestamp);
return dateString.substring(1, dateString.length() - 1);
} catch (Exception e) {
throw new RuntimeException("Creating timestamp", e);
}
}
private void updatePointsetConfig(PointsetConfig pointsetConfig) {
PointsetConfig useConfig = pointsetConfig != null ? pointsetConfig : new PointsetConfig();
allPoints.forEach(point ->
updatePointConfig(point, useConfig.points.get(point.getName())));
deviceState.pointset.state_etag = useConfig.state_etag;
}
private void updatePointConfig(AbstractPoint point, PointPointsetConfig pointConfig) {
point.setConfig(pointConfig);
updateState(point);
}
private int updateSystemConfig(PointsetConfig pointsetConfig) {
final int actualInterval;
boolean hasSampleRate = pointsetConfig != null && pointsetConfig.sample_rate_sec != null;
int reportInterval = hasSampleRate ? pointsetConfig.sample_rate_sec : DEFAULT_REPORT_SEC;
actualInterval = Integer.max(MIN_REPORT_MS, reportInterval * 1000);
return actualInterval;
}
private void errorHandler(GatewayError error) {
info(String.format("%s for %s: %s", error.error_type, error.device_id, error.description));
}
private byte[] getFileBytes(String dataFile) {
Path dataPath = Paths.get(dataFile);
try {
return Files.readAllBytes(dataPath);
} catch (Exception e) {
throw new RuntimeException("While getting data from " + dataPath.toAbsolutePath(), e);
}
}
private void sendDeviceMessage(String deviceId) {
if (mqttPublisher.clientCount() == 0) {
LOG.error("No connected clients, exiting.");
System.exit(-2);
}
devicePoints.version = 1;
devicePoints.timestamp = new Date();
info(String.format("%s sending test message", isoConvert(devicePoints.timestamp)));
publishMessage(deviceId, POINTSET_TOPIC, devicePoints);
}
private void publishLogMessage(String deviceId, String logMessage) {
SystemEvent systemEvent = new SystemEvent();
systemEvent.version = 1;
systemEvent.timestamp = new Date();
info(String.format("%s sending log message", isoConvert(systemEvent.timestamp)));
Entry logEntry = new Entry();
logEntry.category = "pubber";
logEntry.level = 400;
logEntry.timestamp = new Date();
logEntry.message = logMessage;
systemEvent.logentries.add(logEntry);
publishMessage(deviceId, SYSTEM_TOPIC, systemEvent);
}
private void publishStateMessage() {
lastStateTimeMs = sleepUntil(lastStateTimeMs + STATE_THROTTLE_MS);
deviceState.timestamp = new Date();
String deviceId = configuration.deviceId;
info(String.format("%s sending state message", isoConvert(deviceState.timestamp)));
stateDirty = false;
publishMessage(deviceId, STATE_TOPIC, deviceState);
}
private void publishMessage(String deviceId, String topic, Object message) {
mqttPublisher.publish(deviceId, topic, message);
String fileName = topic.replace("/", "_") + ".json";
File stateOut = new File(OUT_DIR, fileName);
try {
OBJECT_MAPPER.writeValue(stateOut, message);
} catch (Exception e) {
throw new RuntimeException("While writing " + stateOut.getAbsolutePath(), e);
}
}
private long sleepUntil(long targetTimeMs) {
long currentTime = System.currentTimeMillis();
long delay = targetTimeMs - currentTime;
try {
if (delay > 0) {
Thread.sleep(delay);
}
return System.currentTimeMillis();
} catch (Exception e) {
throw new RuntimeException("While sleeping for " + delay, e);
}
}
}
|
package org.apache.maven.lifecycle.goal.phase;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.lifecycle.goal.AbstractMavenGoalPhase;
import org.apache.maven.lifecycle.goal.GoalExecutionException;
import org.apache.maven.lifecycle.goal.MavenGoalExecutionContext;
import org.apache.maven.lifecycle.goal.phase.PluginResolutionPhase.PluginResolutionVisitor;
import org.apache.maven.lifecycle.session.MavenSession;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.util.AbstractGoalVisitor;
import org.apache.maven.util.GoalWalker;
import org.apache.maven.util.GraphTraversalException;
import org.codehaus.plexus.util.dag.CycleDetectedException;
/**
* @author jdcasey
*/
public class GoalMappingPhase
extends AbstractMavenGoalPhase
{
public void execute( MavenGoalExecutionContext context ) throws GoalExecutionException
{
GoalMappingVisitor visitor = new GoalMappingVisitor( context.getSession().getPluginManager() );
try
{
GoalWalker.walk( context.getGoalName(), context.getSession(), visitor );
}
catch ( GraphTraversalException e )
{
throw new GoalExecutionException( "Cannot resolve plugins required for goal execution chain", e );
}
}
public static final class GoalMappingVisitor
extends AbstractGoalVisitor
{
private PluginManager pluginManager;
private Set visited = new HashSet();
GoalMappingVisitor( PluginManager pluginManager )
{
this.pluginManager = pluginManager;
}
public void visitPrereq( String goal, String prereq, MavenSession session ) throws GraphTraversalException
{
GoalWalker.walk( prereq, session, this );
try
{
session.addImpliedExecution( goal, prereq );
visited.add( prereq );
}
catch ( CycleDetectedException e )
{
throw new GraphTraversalException( "Goal prereq causes goal-graph cycle", e );
}
}
public void visitPostGoal( String goal, String postGoal, MavenSession session ) throws GraphTraversalException
{
GoalWalker.walk( postGoal, session, this );
}
public void visitPreGoal( String goal, String preGoal, MavenSession session ) throws GraphTraversalException
{
GoalWalker.walk( preGoal, session, this );
}
public void visitGoal( String goal, MavenSession session ) throws GraphTraversalException
{
session.addSingleExecution( goal );
visited.add( goal );
}
public boolean shouldVisit( String goal, MavenSession session ) throws GraphTraversalException
{
boolean result = !visited.contains( goal );
return result;
}
}
}
|
package org.ocelotds;
/**
* Constants Class
*
* @author hhfrancois
*/
public interface Constants {
String QUOTE = "\"";
String ALGORITHM = "MD5";
String UTF_8 = "UTF-8";
String JS = ".js";
String HTML = ".htm";
String SLASH = "/";
String BACKSLASH_N = "\n";
String LOCALE = "LOCALE";
String SESSION = "SESSION";
String HANDSHAKEREQUEST = "HANDSHAKEREQUEST";
String SESSION_BEANS = "SESSIONBEANS";
String PRINCIPAL = "PRINCIPAL";
String ANONYMOUS = "ANONYMOUS";
String CONTENT = "content";
String OCELOT = "ocelot";
String OCELOT_CORE = OCELOT + "-core";
String OCELOT_HTML = OCELOT + "-html";
String OCELOT_MIN = OCELOT + "-min";
String SLASH_OCELOT_JS = SLASH + OCELOT + JS;
String SLASH_OCELOT_HTML = SLASH + OCELOT + HTML;
String MINIFY_PARAMETER = "minify";
String JSTYPE = "text/javascript;charset=UTF-8";
String HTMLTYPE = "text/html;charset=UTF-8";
String FALSE = "false";
String TRUE = "true";
String WSS = "wss";
String WS = "ws";
/**
* This string will be replaced by the contextPath in ocelot-core.js
*/
String CTXPATH = "%CTXPATH%";
String PROTOCOL = "%WSS%";
int DEFAULT_BUFFER_SIZE = 1024 * 4;
interface Options {
String STACKTRACE_LENGTH = "ocelot.stacktrace.length";
}
interface Topic {
String SUBSCRIBERS = "subscribers";
String COLON = ":";
String ALL = "ALL";
}
interface Message {
String ID = "id";
String TYPE = "type";
String DATASERVICE = "ds";
String OPERATION = "op";
String ARGUMENTS = "args";
String ARGUMENTNAMES = "argNames";
String DEADLINE = "deadline";
String RESPONSE = "response";
String LANGUAGE = "language";
String COUNTRY = "country";
interface Fault {
String MESSAGE = "message";
String CLASSNAME = "classname";
String STACKTRACE = "stacktrace";
}
}
interface Resolver {
String CDI = "cdi";
String EJB = "cdi";
String SPRING = "spring";
}
interface Cache {
String CLEANCACHE_TOPIC = "ocelot-cleancache";
String ALL = "ALL";
String USE_ALL_ARGUMENTS = "*";
}
interface Provider {
String JAVASCRIPT = "JS";
}
interface BeanManager {
String BEANMANAGER_JEE = "java:comp/BeanManager";
String BEANMANAGER_ALT = "java:comp/env/BeanManager";
}
}
|
package com.github.dreamhead.moco.parser.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.github.dreamhead.moco.HttpResponseSetting;
import com.github.dreamhead.moco.HttpServer;
import com.github.dreamhead.moco.HttpsCertificate;
import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.MocoEventTrigger;
import com.github.dreamhead.moco.RequestMatcher;
import com.github.dreamhead.moco.ResponseHandler;
import com.github.dreamhead.moco.RestSetting;
import com.github.dreamhead.moco.SocketServer;
import com.github.dreamhead.moco.internal.ActualHttpServer;
import com.github.dreamhead.moco.rest.ActualRestServer;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import static com.github.dreamhead.moco.Moco.log;
import static com.github.dreamhead.moco.MocoMount.to;
import static com.github.dreamhead.moco.util.Iterables.head;
import static com.github.dreamhead.moco.util.Iterables.tail;
@JsonIgnoreProperties({"description"})
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class SessionSetting {
private RequestSetting request;
private ResponseSetting response;
private TextContainer redirectTo;
private MountSetting mount;
private EventSetting on;
private ProxyContainer proxy;
private ResourceSetting resource;
private boolean isMount() {
return this.mount != null;
}
private boolean isAnyResponse() {
return request == null && mount == null && proxy == null && redirectTo == null && resource == null;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("request", request)
.add("response", response)
.add("redirect to", redirectTo)
.add("mount", mount)
.add("proxy", proxy)
.add("on", on)
.add("resource", resource)
.toString();
}
private boolean isRedirectResponse() {
return redirectTo != null;
}
private ResponseHandler getResponseHandler() {
if (response == null) {
throw new IllegalArgumentException("No response specified");
}
return response.getResponseHandler();
}
private RequestMatcher getRequestMatcher() {
if (request == null) {
throw new IllegalArgumentException("No request specified");
}
return request.getRequestMatcher();
}
public void bindTo(final HttpServer server) {
HttpResponseSetting setting = bindToSession(server);
if (hasEvent()) {
for (MocoEventTrigger trigger : on.triggers()) {
setting.on(trigger);
}
}
}
public void bindTo(final SocketServer server) {
if (isAnyResponse()) {
server.response(getResponseHandler());
return;
}
server.request(getRequestMatcher()).response(getResponseHandler());
}
private HttpResponseSetting bindToSession(final HttpServer server) {
if (isMount()) {
return server.mount(mount.getDir(), to(mount.getUri()), mount.getMountPredicates())
.response(mount.getResponseHandler());
}
if (isProxy()) {
if (proxy.hasUrl()) {
throw new IllegalArgumentException("It's not allowed to have URL in proxy from server");
}
return server.proxy(proxy.getProxyConfig(), proxy.getFailover());
}
if (isAnyResponse()) {
return server.response(getResponseHandler());
}
HttpResponseSetting targetRequest = server.request(getRequestMatcher());
if (isRedirectResponse()) {
return targetRequest.redirectTo(this.redirectTo.asResource());
}
return targetRequest.response(getResponseHandler());
}
private boolean isProxy() {
return this.proxy != null;
}
private boolean hasEvent() {
return this.on != null;
}
public boolean isResource() {
return resource != null;
}
public ActualHttpServer newHttpServer(final Optional<Integer> port,
final MocoConfig[] configs) {
if (isResource()) {
ActualRestServer server = new ActualRestServer(port, Optional.<HttpsCertificate>absent(), log(), configs);
RestSetting[] settings = resource.getSettings();
server.resource(resource.getName(), head(settings), tail(settings));
return server;
}
ActualHttpServer server = ActualHttpServer.createLogServer(port, configs);
bindTo(server);
return server;
}
}
|
import java.util.*;
public class MovementLogic
{
public static final int ROUTINE_A = 0;
public static final int ROUTINE_B = 1;
public static final int ROUTINE_C = 2;
public static final int ROUTINE_D = 3;
private static final int MOVED_OK = 0;
private static final int MOVE_FINISHED = 1;
private static final int DIRECTION_BLOCKED = 2;
private static final int MOVE_ERROR = 3;
private static final int LOCATION_VISITED = 4;
public MovementLogic (Map theMap, boolean debug)
{
_theMap = theMap;
_robotTrack = new Trail(_theMap);
_path = new Stack<String>();
_robotFacing = CellId.ROBOT_FACING_UP;
_currentMoveDirection = "";
_currentPosition = new Coordinate(_theMap.findStartingPoint());
_debug = debug;
}
public void createMovementFunctions ()
{
createPath();
String pathElement = _path.pop();
System.out.println("Path:");
while (pathElement != null)
{
System.out.println(pathElement);
try
{
pathElement = _path.pop();
}
catch (Exception ex)
{
pathElement = null;
}
}
}
public void createMovementRoutine ()
{
}
/*
* Create path using only L and R.
*/
private int createPath ()
{
System.out.println("createPath from: "+_currentPosition);
if (_currentPosition != null)
{
/*
* Try L then R.
*
* Robot always starts facing up. Change facing when we
* start to move but remember initial facing so we can
* refer movement directions as L or R.
*/
if (tryToMove(CellId.MOVE_LEFT, leftCoordinate(_currentPosition)) != MOVE_FINISHED)
{
return tryToMove(CellId.MOVE_RIGHT, rightCoordinate(_currentPosition));
}
else
return MOVE_FINISHED;
}
else
{
System.out.println("Robot not found!");
return MOVE_ERROR;
}
}
private int tryToMove (String direction, Coordinate coord)
{
System.out.println("tryMove: "+coord+" with direction: "+direction);
System.out.println("and current position: "+_currentPosition);
/*
* Already visited? Might be sufficient to just check .path
*/
if (_robotTrack.visited(coord) && !_robotTrack.path(coord))
{
System.out.println("Robot already visited this location.");
return LOCATION_VISITED;
}
System.out.println("Location not visited ... yet.");
if (_theMap.isScaffold(coord))
{
System.out.println("Is scaffolding!");
_currentMoveDirection = direction;
_path.push(_currentMoveDirection);
System.out.println("Pushing "+_currentMoveDirection);
_robotTrack.changeElement(coord, _currentMoveDirection);
_currentPosition = coord;
System.out.println("\n"+_robotTrack);
}
else
{
System.out.println("Not scaffolding!");
System.out.println("Robot was facing "+_robotFacing+" and moving "+direction);
if (_theMap.theEnd(_currentPosition))
return MOVE_FINISHED;
changeFacing();
System.out.println("Robot now facing "+_robotFacing);
String nextDirection = getNextDirection();
System.out.println("Next direction to try with new facing: "+nextDirection);
direction = nextDirection;
}
if (CellId.MOVE_LEFT.equals(direction))
coord = leftCoordinate(_currentPosition);
else
coord = rightCoordinate(_currentPosition);
return tryToMove(direction, coord);
}
private String getNextDirection ()
{
System.out.println("Getting next direction to move from: "+_currentPosition);
Coordinate coord = leftCoordinate(_currentPosition);
System.out.println("Left coordinate would be: "+coord);
if (_robotTrack.visited(coord) || !_robotTrack.isScaffold(coord))
{
System.out.println("Visited so try right ...");
coord = rightCoordinate(_currentPosition);
System.out.println("Right coordinate would be: "+coord);
if (_robotTrack.visited(coord))
return null;
else
return CellId.MOVE_RIGHT;
}
else
{
System.out.println("Not visited.");
return CellId.MOVE_LEFT;
}
}
private void changeFacing ()
{
switch (_robotFacing)
{
case CellId.ROBOT_FACING_UP:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_LEFT;
else
_robotFacing = CellId.ROBOT_FACING_RIGHT;
}
break;
case CellId.ROBOT_FACING_DOWN:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_RIGHT;
else
_robotFacing = CellId.ROBOT_FACING_LEFT;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_DOWN;
else
_robotFacing = CellId.ROBOT_FACING_UP;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
if (_currentMoveDirection.equals(CellId.MOVE_LEFT))
_robotFacing = CellId.ROBOT_FACING_UP;
else
_robotFacing = CellId.ROBOT_FACING_DOWN;
}
break;
}
}
/*
* Map/Trail can deal with invalid Coordinates.
*/
private final Coordinate rightCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
System.out.println("rightCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x
}
break;
case CellId.ROBOT_FACING_UP:
{
x++;
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y++;
}
break;
}
return new Coordinate(x, y);
}
private final Coordinate leftCoordinate (Coordinate coord)
{
int x = coord.getX();
int y = coord.getY();
System.out.println("leftCoordinate facing: "+_robotFacing+" and position: "+coord);
switch (_robotFacing)
{
case CellId.ROBOT_FACING_DOWN:
{
x++;
}
break;
case CellId.ROBOT_FACING_UP:
{
x
}
break;
case CellId.ROBOT_FACING_LEFT:
{
y++;
}
break;
case CellId.ROBOT_FACING_RIGHT:
default:
{
y
}
break;
}
return new Coordinate(x, y);
}
private Map _theMap;
private Trail _robotTrack;
private Stack<String> _path;
private String _robotFacing;
private String _currentMoveDirection;
private Coordinate _currentPosition;
private boolean _debug;
}
|
package com.haulmont.cuba.desktop.exception;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Messages;
import com.haulmont.cuba.desktop.App;
import com.haulmont.cuba.gui.components.IFrame;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.remoting.RemoteAccessException;
import java.util.List;
/**
* @author krivopustov
* @version $Id$
*/
public class ConnectExceptionHandler implements ExceptionHandler {
@Override
public boolean handle(Thread thread, Throwable exception) {
@SuppressWarnings("unchecked")
List<Throwable> list = ExceptionUtils.getThrowableList(exception);
for (Throwable throwable : list) {
if (throwable instanceof RemoteAccessException) {
Messages messages = AppBeans.get(Messages.NAME);
String msg = messages.getMessage(getClass(), "connectException.message");
if (throwable.getCause() == null) {
App.getInstance().getMainFrame().showNotification(msg, IFrame.NotificationType.ERROR);
} else {
String description = messages.formatMessage(getClass(), "connectException.description",
throwable.getCause().toString());
App.getInstance().getMainFrame().showNotification(msg, description, IFrame.NotificationType.ERROR);
}
return true;
}
}
return false;
}
}
|
package no.kantega.publishing.rating.dao;
import no.kantega.publishing.api.rating.Rating;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertSame;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath*:testContext.xml")
public class JdbcRatingDaoTest {
private static final String CONTENT = "content";
@Autowired
private RatingDao dao;
@Test
public void testGetRatingsForObject() {
List<Rating> ratings = dao.getRatingsForObject("1", CONTENT);
assertEquals(ratings.size(), 1);
}
@Test
public void testDeleteRatingsForObject() {
Rating r = new Rating();
r.setUserid("andska");
r.setContext(CONTENT);
r.setObjectId("5");
r.setRating(2);
r.setDate(new Date());
dao.saveOrUpdateRating(r);
// Insert one rating
List<Rating> ratings = dao.getRatingsForObject("5", CONTENT);
dao.saveOrUpdateRating(r);
assertSame(ratings.size(), 1);
// Delete rating
dao.deleteRatingsForObject("5", CONTENT);
ratings = dao.getRatingsForObject("5", CONTENT);
assertEquals(ratings.size(), 0);
}
@Test
public void testGetRatingsForUser() {
// If we base the test on dao.getRatingsForUser("andska"), the test will fail if testDeleteSpecificRatingForUser is run before this test
List<Rating> ratings = dao.getRatingsForUser("krisel");
assertEquals(ratings.size(), 2);
}
@Test
public void testGetSpecificRatingForUser() {
List<Rating> ratings = dao.getRatingsForUser("andska", "2", "content");
assertEquals(1, ratings.size());
}
@Test
public void testDeleteSpecificRatingForUser() {
List<Rating> ratings = dao.getRatingsForUser("andska", "2", "content");
assertEquals(1, ratings.size());
dao.deleteRatingsForUser("andska", "2", "content");
ratings = dao.getRatingsForUser("andska", "2", "content");
assertEquals(0, ratings.size());
}
}
|
package dk.statsbiblioteket.doms.ecm.repository;
import dk.statsbiblioteket.doms.ecm.repository.exceptions.*;
import dk.statsbiblioteket.doms.ecm.repository.utils.FedoraUtil;
import dk.statsbiblioteket.doms.webservices.ConfigCollection;
import dk.statsbiblioteket.util.caching.TimeSensitiveCache;
import org.w3c.dom.Document;
import java.util.ArrayList;
import java.util.List;
public class CachingConnector implements FedoraConnector{
private FedoraConnector connector;
/**
* The static contentmodel caches. These should not be protected, so we do
* not care about specific user creds here
*/
private static TimeSensitiveCache<String,PidList> inheritedContentModels;
private static TimeSensitiveCache<String,PidList> inheritingContentModels;
private static TimeSensitiveCache<String,PidList> contentModels;
/**
* This is the blob of user specific caches. Note that this is itself a cache
* so it will be garbage collected
*/
private static TimeSensitiveCache<FedoraUserToken,Caches> userspecificCaches;
/**
* My specific cache.
*/
private Caches myCaches;
public CachingConnector(FedoraConnector connector) {
synchronized (CachingConnector.class){
long lifetime
= Long.parseLong(ConfigCollection.getProperties().getProperty(
"dk.statsbiblioteket.doms.ecm.connectors.fedora.generalcache.lifetime",
"" + 1000 * 60 * 10));
int size
= Integer.parseInt(ConfigCollection.getProperties().getProperty(
"dk.statsbiblioteket.doms.ecm.connectors.fedora.generalcache.size",
"" + 20));
if (inheritedContentModels == null){
inheritedContentModels = new TimeSensitiveCache<String,PidList>(lifetime,true,size);
}
if (inheritingContentModels == null){
inheritingContentModels = new TimeSensitiveCache<String,PidList>(lifetime,true,size);
}
if (contentModels == null){
contentModels = new TimeSensitiveCache<String,PidList>(lifetime,true,size*2);
}
if (userspecificCaches == null){
userspecificCaches = new TimeSensitiveCache<FedoraUserToken,Caches>(lifetime,true,size);
}
this.connector = connector;
}
}
public void initialise(FedoraUserToken token) {
connector.initialise(token);
myCaches = userspecificCaches.get(token);
if (myCaches == null){
myCaches = new Caches();
userspecificCaches.put(token, myCaches);
}
}
public boolean exists(String pid) throws
IllegalStateException,
FedoraIllegalContentException,
FedoraConnectionException,
InvalidCredentialsException {
return connector.exists(pid);
}
public boolean isDataObject(String pid) throws
IllegalStateException,
FedoraIllegalContentException,
FedoraConnectionException,
InvalidCredentialsException {
return connector.isDataObject(pid);
}
public boolean isTemplate(String pid) throws
IllegalStateException,
ObjectNotFoundException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
return connector.isTemplate(pid);
}
public boolean isContentModel(String pid) throws
IllegalStateException,
FedoraIllegalContentException,
FedoraConnectionException,
InvalidCredentialsException {
return connector.isContentModel(pid);
}
public PidList query(String query) throws
IllegalStateException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
return connector.query(query);
}
public boolean addRelation(String from, String relation, String to) throws
IllegalStateException,
ObjectNotFoundException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
myCaches.removeRelations(FedoraUtil.ensurePID(from));
return connector.addRelation(from, relation, to);
}
public boolean addLiteralRelation(String from,
String relation,
String value, String datatype) throws
IllegalStateException,
ObjectNotFoundException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
myCaches.removeRelations(FedoraUtil.ensurePID(from));
return connector.addLiteralRelation(from, relation, value, datatype);
}
public String getObjectXml(String pid) throws
IllegalStateException,
ObjectNotFoundException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
pid = FedoraUtil.ensurePID(pid);
String doc = myCaches.getObjectXML(pid);
if (doc != null){
return doc;
}
doc = connector.getObjectXml(pid);
myCaches.storeObjectXML(pid,doc);
return doc;
}
public String ingestDocument(Document newobject, String logmessage) throws
IllegalStateException,
FedoraConnectionException,
FedoraIllegalContentException,
InvalidCredentialsException {
return connector.ingestDocument(newobject, logmessage);
}
public List<Relation> getRelations(String pid) throws
IllegalStateException,
FedoraConnectionException,
ObjectNotFoundException,
FedoraIllegalContentException,
InvalidCredentialsException {
pid = FedoraUtil.ensurePID(pid);
List<Relation> relations = myCaches.getRelations(pid);
if (relations != null){
return relations;
}
relations = connector.getRelations(pid);
myCaches.storeRelations(pid,relations);
return relations;
}
public List<Relation> getRelations(String pid,
String relation) throws
IllegalStateException,
FedoraConnectionException,
ObjectNotFoundException,
FedoraIllegalContentException,
InvalidCredentialsException {
List<Relation> relations = getRelations(pid);
List<Relation> result = new ArrayList<Relation>();
for (Relation relation1 : relations) {
if (relation1.getRelation().equals(relation)){
result.add(relation1);
}
}
return result;
}
public Document getDatastream(String pid, String dsid) throws
IllegalStateException,
DatastreamNotFoundException,
FedoraConnectionException,
FedoraIllegalContentException,
ObjectNotFoundException,
InvalidCredentialsException {
Document doc = myCaches.getDatastreamContents(pid, dsid);
if (doc != null){
return doc;
}
doc = connector.getDatastream(pid, dsid);
myCaches.storeDatastreamContents(pid,dsid,doc);
return doc;
}
public PidList getContentModels(String pid) throws
IllegalStateException,
FedoraConnectionException,
ObjectNotFoundException,
FedoraIllegalContentException,
InvalidCredentialsException {
pid = FedoraUtil.ensureURI(pid);
PidList models = contentModels.get(pid);
if (models != null){
return models;
}
models = connector.getContentModels(pid);
contentModels.put(pid,models);
return models;
}
public PidList getInheritingContentModels(String cmpid) throws
IllegalStateException,
FedoraConnectionException,
ObjectNotFoundException,
ObjectIsWrongTypeException,
FedoraIllegalContentException,
InvalidCredentialsException {
cmpid = FedoraUtil.ensureURI(cmpid);
PidList descendants = inheritingContentModels.get(cmpid);
if (descendants != null){
return descendants;
}
descendants = connector.getInheritingContentModels(cmpid);
inheritingContentModels.put(cmpid,descendants);
return descendants;
}
public PidList getInheritedContentModels(String cmpid) throws
FedoraConnectionException,
ObjectNotFoundException,
ObjectIsWrongTypeException,
FedoraIllegalContentException,
InvalidCredentialsException {
cmpid = FedoraUtil.ensureURI(cmpid);
PidList descendants = inheritedContentModels.get(cmpid);
if (descendants != null){
return descendants;
}
descendants = connector.getInheritedContentModels(cmpid);
inheritedContentModels.put(cmpid,descendants);
return descendants;
}
public List<String> listDatastreams(String pid) throws
IllegalStateException,
FedoraConnectionException,
ObjectNotFoundException,
FedoraIllegalContentException,
InvalidCredentialsException {
return connector.listDatastreams(pid);
}
public String getUsername() {
return connector.getUsername();
}
public boolean authenticate() throws FedoraConnectionException {
return connector.authenticate();
}
public String getUser() {
return connector.getUser();
}
}
|
package name.abuchen.portfolio.ui.util;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import name.abuchen.portfolio.model.Client;
import name.abuchen.portfolio.model.ConfigurationSet;
import name.abuchen.portfolio.model.ConfigurationSet.Configuration;
import name.abuchen.portfolio.ui.Images;
import name.abuchen.portfolio.ui.Messages;
/**
* Stores a set of named configurations whereby one is the active configuration
* at any given time. Each configuration has a name given by the user.
*/
public class ConfigurationStore
{
public interface ConfigurationStoreOwner
{
void beforeConfigurationPicked();
void onConfigurationPicked(String data);
default void onConfigurationSetUpdated()
{
}
}
private static final class InputValidator implements IInputValidator
{
@Override
public String isValid(String newText)
{
return newText == null || newText.trim().isEmpty() ? Messages.ConfigurationErrorMissingValue : null;
}
}
private static final String KEY_ACTIVE = "$picked"; //$NON-NLS-1$
private final String identifier;
private final Client client;
private final IPreferenceStore preferences;
private final List<ConfigurationStoreOwner> listeners = new ArrayList<>();
private final ConfigurationSet configSet;
private Configuration active;
private Menu contextMenu;
public ConfigurationStore(String identifier, Client client, IPreferenceStore preferences,
ConfigurationStoreOwner listener)
{
this.identifier = identifier;
this.client = client;
this.preferences = preferences;
this.listeners.add(listener);
this.configSet = client.getSettings().getConfigurationSet(identifier);
// make one active (and there always must be one active)
this.active = configSet.lookup(preferences.getString(identifier + KEY_ACTIVE))
.orElseGet(() -> configSet.getConfigurations().findFirst().orElseGet(() -> {
Configuration defaultConfig = new Configuration(Messages.ConfigurationStandard, null);
configSet.add(defaultConfig);
return defaultConfig;
}));
preferences.setValue(identifier + KEY_ACTIVE, active.getUUID());
}
public void setToolBarManager(ToolBarManager toolBar)
{
createToolBarItems(toolBar);
toolBar.update(true);
this.listeners.add(new ConfigurationStoreOwner()
{
@Override
public void onConfigurationPicked(String data)
{
onConfigurationSetUpdated();
}
@Override
public void beforeConfigurationPicked()
{
// no changes to the toolbar before switching to a new
// configuration
}
@Override
public void onConfigurationSetUpdated()
{
if (toolBar.getControl().isDisposed())
return;
toolBar.removeAll();
createToolBarItems(toolBar);
toolBar.update(true);
}
});
}
private void createToolBarItems(ToolBarManager toolBar)
{
configSet.getConfigurations().forEach(config -> {
DropDown item = new DropDown(config.getName(),
config.equals(active) ? Images.VIEW_SELECTED : Images.VIEW);
item.setMenuListener(manager -> {
if (!config.equals(active))
{
manager.add(new SimpleAction(Messages.MenuShow, a -> activate(config)));
manager.add(new Separator());
}
manager.add(new SimpleAction(Messages.ConfigurationDuplicate, a -> createNew(config)));
manager.add(new SimpleAction(Messages.ConfigurationRename, a -> rename(config)));
manager.add(new ConfirmAction(Messages.ConfigurationDelete,
MessageFormat.format(Messages.ConfigurationDeleteConfirm, config.getName()),
a -> delete(config)));
int index = configSet.indexOf(config);
if (index > 0)
{
manager.add(new Separator());
manager.add(new SimpleAction(Messages.ChartBringToFront, a -> {
configSet.remove(config);
configSet.add(0, config);
toolBar.removeAll();
createToolBarItems(toolBar);
toolBar.update(true);
}));
}
});
item.setDefaultAction(new SimpleAction(a -> activate(config)));
toolBar.add(item);
});
Action createNew = new SimpleAction(a -> createNew(null));
createNew.setImageDescriptor(Images.VIEW_PLUS.descriptor());
createNew.setToolTipText(Messages.ConfigurationNew);
toolBar.add(createNew);
}
/**
* Shows menu to manage views, e.g. create, copy, rename, and delete a view.
*
* @param shell
*/
public void showMenu(Shell shell)
{
if (contextMenu == null)
{
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this::saveMenuAboutToShow);
contextMenu = menuMgr.createContextMenu(shell);
}
contextMenu.setVisible(true);
}
/**
* Disposes the configuration store.
*/
public void dispose()
{
if (contextMenu != null && !contextMenu.isDisposed())
contextMenu.dispose();
}
private void saveMenuAboutToShow(IMenuManager manager) // NOSONAR
{
configSet.getConfigurations().forEach(config -> {
Action action = new SimpleAction(config.getName(), a -> activate(config));
action.setChecked(active == config);
manager.add(action);
});
manager.add(new Separator());
manager.add(new SimpleAction(Messages.ConfigurationNew, a -> createNew(null)));
manager.add(new SimpleAction(Messages.ConfigurationDuplicate, a -> createNew(active)));
manager.add(new SimpleAction(Messages.ConfigurationRename, a -> rename(active)));
manager.add(new ConfirmAction(Messages.ConfigurationDelete,
MessageFormat.format(Messages.ConfigurationDeleteConfirm, active.getName()),
a -> delete(active)));
}
private void createNew(Configuration template)
{
InputDialog dlg = new InputDialog(Display.getCurrent().getActiveShell(), Messages.ConfigurationNew,
Messages.ChartSeriesPickerDialogMsg, template != null ? template.getName() : null,
new InputValidator());
if (dlg.open() != InputDialog.OK)
return;
String name = dlg.getValue();
listeners.forEach(ConfigurationStoreOwner::beforeConfigurationPicked);
active = new Configuration(name, template != null ? template.getData() : null);
configSet.add(active);
client.touch();
preferences.setValue(identifier + KEY_ACTIVE, active.getUUID());
listeners.forEach(l -> l.onConfigurationPicked(active.getData()));
}
private void rename(Configuration config)
{
InputDialog dlg = new InputDialog(Display.getCurrent().getActiveShell(), Messages.ConfigurationRename,
Messages.ChartSeriesPickerDialogMsg, config.getName(), new InputValidator());
if (dlg.open() != InputDialog.OK)
return;
config.setName(dlg.getValue());
client.touch();
listeners.forEach(ConfigurationStoreOwner::onConfigurationSetUpdated);
}
private void delete(Configuration config)
{
configSet.remove(config);
if (active != config)
{
listeners.forEach(ConfigurationStoreOwner::onConfigurationSetUpdated);
return;
}
listeners.forEach(ConfigurationStoreOwner::beforeConfigurationPicked);
active = configSet.getConfigurations().findAny().orElseGet(() -> {
Configuration defaultConfig = new Configuration(Messages.ConfigurationStandard, null);
configSet.add(defaultConfig);
return defaultConfig;
});
preferences.setValue(identifier + KEY_ACTIVE, active.getUUID());
listeners.forEach(l -> l.onConfigurationPicked(active.getData()));
}
private void activate(Configuration config)
{
listeners.forEach(ConfigurationStoreOwner::beforeConfigurationPicked);
active = config;
preferences.setValue(identifier + KEY_ACTIVE, active.getUUID());
listeners.forEach(l -> l.onConfigurationPicked(config.getData()));
}
public void updateActive(String data)
{
if (!Objects.equals(data, active.getData()))
{
active.setData(data);
client.touch();
}
}
public String getActive()
{
return active.getData();
}
public String getActiveName()
{
return active.getName();
}
public String getActiveUUID()
{
return active.getUUID();
}
public void insertMigratedConfiguration(String data)
{
active = new Configuration(Messages.ConfigurationStandard, data);
configSet.add(active);
preferences.setValue(identifier + KEY_ACTIVE, active.getUUID());
client.touch();
}
}
|
package uk.gov.nationalarchives.droid.command.action;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author rbrennan
*
*/
public class NoProfileRunCommandTest {
private NoProfileRunCommand command;
private LocationResolver locationResolver;
@Before
public void setup() {
command = new NoProfileRunCommand();
command.setLocationResolver(locationResolver);
}
@Test
public void testNoProfileRunWithNoSignatureFile() {
command.setSignatureFile("test");
command.setResources(new String[] {
"test1.txt",
"test2.txt",
});
try {
command.execute();
fail("Expected CommandExecutionException");
} catch (CommandExecutionException x) {
assertEquals("Signature file not found", x.getMessage());
}
}
@Test
public void testNoProfileRunWithNoResource() throws Exception {
File sigFile = new File("sigFile");
sigFile.createNewFile();
command.setSignatureFile("sigFile");
command.setResources(new String[] {
"test1.txt",
"test2.txt",
});
try {
command.execute();
fail("Expected CommandExecutionException");
} catch (CommandExecutionException x) {
assertEquals("Resources directory not found", x.getMessage());
} finally {
sigFile.delete();
}
}
@Test
public void testNoProfileRunWithInvalidSignatureFile() throws Exception {
File sigFile = new File("sigFile");
sigFile.createNewFile();
command.setSignatureFile(sigFile.getAbsolutePath());
File resource = new File("resource");
resource.mkdir();
command.setResources(new String[] {
resource.getAbsolutePath()
});
try {
command.execute();
fail("Expected CommandExecutionException");
} catch (CommandExecutionException x) {
assertEquals("Can't parse signature file", x.getMessage());
} finally {
sigFile.delete();
resource.delete();
}
}
@Test
public void testNoProfileRunWithNoExtensionFilter() throws Exception {
command.setSignatureFile("../droid-core/test_sig_files/DROID_SignatureFile_V26.xml");
command.setResources(new String[] {
"../droid-core/test_sig_files"
});
command.execute();
}
@Test
public void testNoProfileRunWithExtensionFilter() throws Exception {
command.setSignatureFile("../droid-core/test_sig_files/DROID_SignatureFile_V26.xml");
command.setResources(new String[] {
"../droid-core/test_sig_files"
});
command.setExtensionFilter(new String[] {"oojah", "maflip"});
command.execute();
}
}
|
package uk.ac.ebi.quickgo.ontology.controller;
import uk.ac.ebi.quickgo.common.SearchableField;
import uk.ac.ebi.quickgo.graphics.model.GraphImageLayout;
import uk.ac.ebi.quickgo.ontology.model.GraphRequest;
import uk.ac.ebi.quickgo.graphics.ontology.GraphPresentation;
import uk.ac.ebi.quickgo.graphics.ontology.RenderingGraphException;
import uk.ac.ebi.quickgo.graphics.service.GraphImageService;
import uk.ac.ebi.quickgo.ontology.OntologyRestConfig;
import uk.ac.ebi.quickgo.ontology.common.OntologyFields;
import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelper;
import uk.ac.ebi.quickgo.ontology.model.OBOTerm;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationType;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship;
import uk.ac.ebi.quickgo.ontology.model.OntologySpecifier;
import uk.ac.ebi.quickgo.ontology.model.graph.AncestorGraph;
import uk.ac.ebi.quickgo.ontology.model.graph.AncestorVertex;
import uk.ac.ebi.quickgo.ontology.service.OntologyService;
import uk.ac.ebi.quickgo.ontology.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.rest.ParameterBindingException;
import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler;
import uk.ac.ebi.quickgo.rest.headers.HttpHeadersProvider;
import uk.ac.ebi.quickgo.rest.search.RetrievalException;
import uk.ac.ebi.quickgo.rest.search.SearchDispatcher;
import uk.ac.ebi.quickgo.rest.search.SearchService;
import uk.ac.ebi.quickgo.rest.search.StringToQuickGOQueryConverter;
import uk.ac.ebi.quickgo.rest.search.query.QueryRequest;
import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.query.RegularPage;
import uk.ac.ebi.quickgo.rest.search.results.QueryResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.http.HttpHeaders.CONTENT_ENCODING;
import static uk.ac.ebi.quickgo.ontology.model.OntologyRelationType.DEFAULT_TRAVERSAL_TYPES;
import static uk.ac.ebi.quickgo.ontology.model.OntologyRelationType.DEFAULT_TRAVERSAL_TYPES_CSV;
import static uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery.and;
/**
* Abstract controller defining common end-points of an OBO related
* REST API.
*
* Created 27/11/15
* @author Edd
*/
public abstract class OBOController<T extends OBOTerm> {
static final String TERMS_RESOURCE = "terms";
static final String SEARCH_RESOUCE = "search";
static final String COMPLETE_SUB_RESOURCE = "complete";
static final String HISTORY_SUB_RESOURCE = "history";
static final String XREFS_SUB_RESOURCE = "xrefs";
static final String CONSTRAINTS_SUB_RESOURCE = "constraints";
static final String XRELATIONS_SUB_RESOURCE = "xontologyrelations";
static final String GUIDELINES_SUB_RESOURCE = "guidelines";
static final String ANCESTORS_SUB_RESOURCE = "ancestors";
static final String DESCENDANTS_SUB_RESOURCE = "descendants";
static final String PATHS_SUB_RESOURCE = "paths";
static final String CHART_SUB_RESOURCE = "chart";
static final String CHART_COORDINATES_SUB_RESOURCE = CHART_SUB_RESOURCE + "/coords";
static final String BASE_64_CONTENT_ENCODING = "base64";
private static final Logger LOGGER = LoggerFactory.getLogger(OBOController.class);
private static final String COLON = ":";
private static final String DEFAULT_ENTRIES_PER_PAGE = "25";
private static final String DEFAULT_PAGE_NUMBER = "1";
private static final String PNG = "png";
final OntologyService<T> ontologyService;
final OBOControllerValidationHelper validationHelper;
private final SearchService<OBOTerm> ontologySearchService;
private final StringToQuickGOQueryConverter ontologyQueryConverter;
private final SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig;
private final GraphImageService graphImageService;
private final OntologyRestConfig.OntologyPagingConfig ontologyPagingConfig;
private final OntologySpecifier ontologySpecifier;
private final HttpHeadersProvider httpHeadersProvider;
public OBOController(OntologyService<T> ontologyService,
SearchService<OBOTerm> ontologySearchService,
SearchableField searchableField,
SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig,
GraphImageService graphImageService,
OBOControllerValidationHelper oboControllerValidationHelper,
OntologyRestConfig.OntologyPagingConfig ontologyPagingConfig,
OntologySpecifier ontologySpecifier,
HttpHeadersProvider httpHeadersProvider) {
checkArgument(ontologyService != null, "Ontology service cannot be null");
checkArgument(ontologySearchService != null, "Ontology search service cannot be null");
checkArgument(searchableField != null, "Ontology searchable field cannot be null");
checkArgument(ontologyRetrievalConfig != null, "Ontology retrieval configuration cannot be null");
checkArgument(graphImageService != null, "Graph image service cannot be null");
checkArgument(oboControllerValidationHelper != null, "OBO validation helper cannot be null");
checkArgument(ontologyPagingConfig != null, "Paging config cannot be null");
checkArgument(ontologySpecifier != null, "Ontology specifier cannot be null");
checkArgument(httpHeadersProvider != null, "Http Headers Provider cannot be null");
this.ontologyService = ontologyService;
this.ontologySearchService = ontologySearchService;
this.ontologyQueryConverter = new StringToQuickGOQueryConverter(searchableField);
this.ontologyRetrievalConfig = ontologyRetrievalConfig;
this.validationHelper = oboControllerValidationHelper;
this.graphImageService = graphImageService;
this.ontologyPagingConfig = ontologyPagingConfig;
this.ontologySpecifier = ontologySpecifier;
this.httpHeadersProvider = httpHeadersProvider;
}
/**
* An empty or unknown path should result in a bad request
*
* @return a 400 response
*/
@ApiOperation(value = "Catches any bad requests and returns an error response with a 400 status", hidden = true)
/**
* Get information about all terms and page through the results.
*
* @param page the page number of results to retrieve
* @return the specified page of results as a {@link QueryResult} instance or a 400 response
* if the page number is invalid
*/
@ApiOperation(value = "Get information on all terms and page through the results")
@RequestMapping(value = "/" + TERMS_RESOURCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> baseUrl(
@ApiParam(value = "The results page to retrieve")
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
return new ResponseEntity<>(ontologyService.findAllByOntologyType
(this.ontologySpecifier.ontologyType,
new RegularPage(page, ontologyPagingConfig.defaultPageSize())),
httpHeadersProvider.provide(),
HttpStatus.OK);
}
/**
* Get core information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get core information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, ancestors, synonyms, " +
"comment, aspect (for GO) and usage.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsCoreAttr(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get complete information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get complete information about a (CSV) list of terms based on their ids",
notes = "All fields will be populated providing they have a value.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + COMPLETE_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsComplete(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findCompleteInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get history information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get history information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, history.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + HISTORY_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsHistory(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findHistoryInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-reference information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross-reference information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, comment, xRefs.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XREFS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXRefs(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXRefsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get taxonomy constraint information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get taxonomy constraint information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, taxonConstraints, " +
"blacklist.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CONSTRAINTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsTaxonConstraints(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findTaxonConstraintsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-ontology relationship information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross ontology relationship information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, comment, xRelations.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XRELATIONS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXOntologyRelations(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXORelationsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get annotation guideline information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 200 with an empty result set.</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get annotation guideline information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, " +
"comment, annotationGuidelines.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + GUIDELINES_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsAnnotationGuideLines(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids) {
return getResultsResponse(ontologyService
.findAnnotationGuideLinesInfoByOntologyId(validationHelper.validateCSVIds
(ids)));
}
/**
* Search for an ontology term via its identifier, or a generic query search
*
* @param query the query to search against
* @param limit the amount of queries to return
* @return a {@link QueryResult} instance containing the results of the search
*/
@ApiOperation(value = "Searches a simple user query, e.g., query=apopto",
notes = "If possible, response fields include: id, name, isObsolete, aspect (for GO)")
@RequestMapping(value = "/" + SEARCH_RESOUCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<OBOTerm>> ontologySearch(
@ApiParam(value = "Some value to search for in the ontology") @RequestParam(value = "query") String query,
@ApiParam(value = "The number of results per page [1-600]")
@RequestParam(value = "limit", defaultValue = DEFAULT_ENTRIES_PER_PAGE) int limit,
@ApiParam(value = "The results page to retrieve")
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
validationHelper.validateRequestedResults(limit);
validationHelper.validatePageIsLessThanPaginationLimit(page);
QueryRequest request = buildRequest(
query,
limit,
page,
ontologyQueryConverter);
return SearchDispatcher.search(request, ontologySearchService);
}
/**
* Retrieves the ancestors of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which ancestors will be found
* @return a result instance containing the ancestors
*/
@ApiOperation(value = "Retrieves the ancestors of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + ANCESTORS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findAncestors(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids,
@ApiParam(value = "Comma-separated ontology relationships")
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findAncestorsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations,
DEFAULT_TRAVERSAL_TYPES))));
}
/**
* Retrieves the descendants of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which descendants will be found
* @return a result containing the descendants
*/
@ApiOperation(value = "Retrieves the descendants of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + DESCENDANTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findDescendants(
@ApiParam(value = "Comma-separated term IDs", required = true) @PathVariable(value = "ids") String ids,
@ApiParam(value = "Comma-separated ontology relationships")
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findDescendantsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations,
DEFAULT_TRAVERSAL_TYPES))));
}
/**
* Retrieves the paths between ontology terms
* @param ids the term ids in CSV format, from which paths begin
* @param toIds the term ids in CSV format, to which the paths lead
* @param relations the ontology relationships over which descendants will be found
* @return a result containing a list of paths between the {@code ids} terms, and {@code toIds} terms
*/
@ApiOperation(value = "Retrieves the paths between two specified sets of ontology terms. Each path is " +
"formed from a list of (term, relationship, term) triples.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + PATHS_SUB_RESOURCE + "/{toIds}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<List<OntologyRelationship>>> findPaths(
@ApiParam(value = "Comma-separated source term IDs") @PathVariable(value = "ids") String ids,
@ApiParam(value = "Comma-separated target term IDs") @PathVariable(value = "toIds") String toIds,
@ApiParam(value = "Comma-separated ontology relationships")
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.paths(
asSet(validationHelper.validateCSVIds(ids)),
asSet(validationHelper.validateCSVIds(toIds)),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations,
DEFAULT_TRAVERSAL_TYPES))
));
}
/**
* Retrieves the graphical image corresponding to ontology terms.
*
* @return the image corresponding to the requested term ids
*/
@ApiOperation(value = "Retrieves the PNG image corresponding to the specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_PNG_VALUE})
public ResponseEntity<InputStreamResource> getChart(@Valid @ModelAttribute GraphRequest request, BindingResult
bindingResult) {
checkBindingErrors(bindingResult);
final GraphPresentation graphPresentation = buildGraphPresentation(request);
Boolean base64 = request.isBase64().map(b -> b.booleanValue()).orElse(Boolean.FALSE);
try {
return createChartResponseEntity(validationHelper.validateCSVIds(request.getIds()), base64,
graphPresentation);
} catch (IOException | RenderingGraphException e) {
throw createChartGraphicsException(e);
}
}
/**
* Retrieves the graphical image coordination information corresponding to ontology terms.
*
* @return the coordinate information of the terms in the chart
*/
@ApiOperation(value = "Retrieves coordinate information about terms within the PNG chart from the " +
CHART_SUB_RESOURCE + " sub-resource")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_COORDINATES_SUB_RESOURCE,
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<GraphImageLayout> getChartCoordinates(@Valid @ModelAttribute GraphRequest request,
BindingResult bindingResult) {
checkBindingErrors(bindingResult);
final GraphPresentation graphPresentation = buildGraphPresentation(request);
try {
GraphImageLayout layout = graphImageService
.createChart(validationHelper.validateCSVIds(request.getIds()), ontologySpecifier.ontologyType
.name(), graphPresentation)
.getLayout();
return ResponseEntity
.ok()
.body(layout);
} catch (RenderingGraphException e) {
throw createChartGraphicsException(e);
}
}
/**
* Retrieves a sub-graph of the ontology graph between two sets of provided term ids
*
* @param startIds the term ids from which to the sub-graph should begin
* @param stopIds the term ids that indicate the ending of the sub-graph
* @return the specified ontology sub-graph
*/
@ApiOperation(value = "Fetches a sub-graph of the ontology")
@RequestMapping(value = TERMS_RESOURCE + "/graph", method = RequestMethod.GET, produces = {MediaType
.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<AncestorGraph>> getGraph(
@ApiParam(value = "Comma-separated term IDs specifying the beginning of the sub-graph")
@RequestParam(value = "startIds") String startIds,
@ApiParam(value = "Comma-separated term IDs specifying the end of the sub-graph")
@RequestParam(value = "stopIds", required = false) String stopIds,
@ApiParam(value = "Comma-separated relationships over which the graph will navigate")
@RequestParam(value = "relations", required = false) String relations) {
final AncestorGraph<AncestorVertex> ancestorGraph = ontologyService.findOntologySubGraphById(
asSet(validationHelper.validateCSVIds(startIds)),
asSet(validationHelper.validateCSVIds(stopIds)),
validRelations(relations).toArray(new OntologyRelationType[]{}));
if (ancestorGraph.vertices.size() == 0 && ancestorGraph.edges.size() == 0) {
return getResultsResponse(Collections.emptyList());
} else {
return getResultsResponse(Collections.singletonList(ancestorGraph));
}
}
private List<OntologyRelationType> validRelations(String relations) {
return Objects.isNull(relations) || relations.isEmpty() ? this.ontologySpecifier.allowedRelations :
validationHelper.validateRelationTypes(relations, this.ontologySpecifier.allowedRelations);
}
/**
* Wrap a collection as a {@link Set}
* @param items the items to wrap as a {@link Set}
* @param <ItemType> the type of the {@link Collection}, i.e., this method works for any type
* @return a {@link Set} wrapping the items in a {@link Collection}
*/
private static <ItemType> Set<ItemType> asSet(Collection<ItemType> items) {
return new HashSet<>(items);
}
/**
* Converts a {@link Collection} of {@link OntologyRelationType}s to a corresponding array of
* {@link OntologyRelationType}s
* @param relations the {@link OntologyRelationType}s
* @return an array of {@link OntologyRelationType}s
*/
static OntologyRelationType[] asOntologyRelationTypeArray(Collection<OntologyRelationType> relations) {
return relations.toArray(new OntologyRelationType[relations.size()]);
}
/**
* Creates a {@link ResponseEntity} containing a {@link QueryResult} for a list of results.
*
* @param results a list of results
* @return a {@link ResponseEntity} containing a {@link QueryResult} for a list of results
*/
<ResponseType> ResponseEntity<QueryResult<ResponseType>> getResultsResponse(List<ResponseType> results) {
List<ResponseType> resultsToShow;
if (results == null) {
resultsToShow = Collections.emptyList();
} else {
resultsToShow = results;
}
QueryResult<ResponseType> queryResult = new QueryResult.Builder<>(resultsToShow.size(), resultsToShow).build();
return new ResponseEntity<>(queryResult, httpHeadersProvider.provide(), HttpStatus.OK);
}
private RetrievalException createChartGraphicsException(Throwable throwable) {
String errorMessage = "Error encountered during creation of ontology chart graphics.";
LOGGER.error(errorMessage, throwable);
return new RetrievalException(errorMessage);
}
/**
* Delegates the creation of an graphical image, corresponding to the specified list
* of {@code ids} and returns the appropriate {@link ResponseEntity}.
*
* @param ids the terms whose corresponding graphical image is required
* @param base64 whether or not to encode the image as base64
* @param graphPresentation defines the look and attributes of the rendered graph
* @return the image corresponding to the specified terms
* @throws IOException if there is an error during creation of the image {@link InputStreamResource}
* @throws RenderingGraphException if there was an error during the rendering of the image
*/
private ResponseEntity<InputStreamResource> createChartResponseEntity(List<String> ids, boolean base64,
GraphPresentation graphPresentation)
throws IOException, RenderingGraphException {
RenderedImage renderedImage =
graphImageService
.createChart(ids, ontologySpecifier.ontologyType.name(), graphPresentation)
.getGraphImage()
.render();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ResponseEntity.BodyBuilder bodyBuilder;
if (base64) {
ImageIO.write(renderedImage, PNG, Base64.getMimeEncoder().wrap(os));
bodyBuilder = buildChartResponseBodyBuilder(os).header(CONTENT_ENCODING, BASE_64_CONTENT_ENCODING);
} else {
ImageIO.write(renderedImage, PNG, os);
bodyBuilder = buildChartResponseBodyBuilder(os);
}
return bodyBuilder.body(new InputStreamResource(new ByteArrayInputStream(os.toByteArray())));
}
private ResponseEntity.BodyBuilder buildChartResponseBodyBuilder(ByteArrayOutputStream os) {
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_PNG)
.contentLength(os.size());
}
private QueryRequest buildRequest(String query,
int limit,
int page,
StringToQuickGOQueryConverter converter) {
QuickGOQuery userQuery = converter.convert(query);
QuickGOQuery restrictedUserQuery = restrictQueryToOTypeResults(userQuery);
QueryRequest.Builder builder = new QueryRequest
.Builder(restrictedUserQuery)
.setPage(new RegularPage(page, limit));
if (!ontologyRetrievalConfig.getSearchReturnedFields().isEmpty()) {
ontologyRetrievalConfig.getSearchReturnedFields()
.forEach(builder::addProjectedField);
}
return builder.build();
}
/**
* Given a {@link QuickGOQuery}, create a composite {@link QuickGOQuery} by
* performing a conjunction with another query, which restricts all results
* to be of a type corresponding to ontology type}.
*
* @param query the query that is constrained
* @return the new constrained query
*/
private QuickGOQuery restrictQueryToOTypeResults(QuickGOQuery query) {
return and(query,
ontologyQueryConverter.convert(
OntologyFields.Searchable.ONTOLOGY_TYPE + COLON + ontologySpecifier.ontologyType.name()));
}
private void checkBindingErrors(BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new ParameterBindingException(bindingResult);
}
}
/**
* Map the values of the graph presentational parameters to an instance of GraphPresentation
* @param request holds the stylistic parameters requested by the client
* @return GraphPresentation instance
*/
private GraphPresentation buildGraphPresentation(GraphRequest request) {
GraphPresentation.Builder presentationBuilder = graphImageService.graphPresentationBuilder();
request.showKey().map(presentationBuilder::showKey);
request.showIds().map(presentationBuilder::showIDs);
request.getTermBoxWidth().map(presentationBuilder::termBoxWidth);
request.getTermBoxHeight().map(presentationBuilder::termBoxHeight);
request.showSlimColours().map(presentationBuilder::showSlimColours);
request.showChildren().map(presentationBuilder::showChildren);
return presentationBuilder.build();
}
}
|
package org.opennms.netmgt.dao.hibernate;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.opennms.netmgt.dao.OnmsDao;
import org.opennms.netmgt.model.OnmsCriteria;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class AbstractDaoHibernate<T, K extends Serializable> extends
HibernateDaoSupport implements OnmsDao<T, K> {
Class<T> m_entityClass;
public AbstractDaoHibernate(Class<T> entityClass) {
m_entityClass = entityClass;
}
public void initialize(Object obj) {
getHibernateTemplate().initialize(obj);
}
public void flush() {
getHibernateTemplate().flush();
}
public void clear() {
getHibernateTemplate().clear();
}
public void evict(T entity) {
getHibernateTemplate().evict(entity);
}
public void merge(T entity) {
getHibernateTemplate().merge(entity);
}
@SuppressWarnings("unchecked")
public List<T> find(String query) {
return getHibernateTemplate().find(query);
}
@SuppressWarnings("unchecked")
public List<T> find(String query, Object... values) {
return getHibernateTemplate().find(query, values);
}
@SuppressWarnings("unchecked")
public <S> List<S> findObjects(Class<S> clazz, String query, Object... values) {
return getHibernateTemplate().find(query, values);
}
protected int queryInt(final String query) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return session.createQuery(query).uniqueResult();
}
};
Object result = getHibernateTemplate().execute(callback);
return ((Number) result).intValue();
}
protected int queryInt(final String queryString, final Object... args) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(queryString);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
return query.uniqueResult();
}
};
Object result = getHibernateTemplate().execute(callback);
return ((Number) result).intValue();
}
protected T findUnique(final String query) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return session.createQuery(query).uniqueResult();
}
};
Object result = getHibernateTemplate().execute(callback);
return m_entityClass.cast(result);
}
protected T findUnique(final String queryString, final Object... args) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(queryString);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
return query.uniqueResult();
}
};
Object result = getHibernateTemplate().execute(callback);
return m_entityClass.cast(result);
}
public int countAll() {
return queryInt("select count(*) from " + m_entityClass.getName());
}
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return getHibernateTemplate().loadAll(m_entityClass);
}
@SuppressWarnings("unchecked")
public List<T> findMatching(final OnmsCriteria onmsCrit) {
onmsCrit.resultsOfType(m_entityClass);
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria attachedCrit = onmsCrit.getDetachedCriteria().getExecutableCriteria(session);
if (onmsCrit.getFirstResult() != null) {
attachedCrit.setFirstResult(onmsCrit.getFirstResult());
}
if (onmsCrit.getMaxResults() != null) {
attachedCrit.setMaxResults(onmsCrit.getMaxResults());
}
return attachedCrit.list();
}
};
return getHibernateTemplate().executeFind(callback);
}
public T get(K id) {
return m_entityClass.cast(getHibernateTemplate().get(m_entityClass,
id));
}
public T load(K id) {
return m_entityClass.cast(getHibernateTemplate().load(m_entityClass,
id));
}
public void save(T entity) {
getHibernateTemplate().save(entity);
}
public void saveOrUpdate(T entity) {
getHibernateTemplate().saveOrUpdate(entity);
}
public void update(T entity) {
getHibernateTemplate().update(entity);
}
}
|
package org.eclipse.mylar.tasklist.ui.views;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.security.auth.login.LoginException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.core.internal.dt.MylarWebRef;
import org.eclipse.mylar.tasklist.IQuery;
import org.eclipse.mylar.tasklist.IQueryHit;
import org.eclipse.mylar.tasklist.ITask;
import org.eclipse.mylar.tasklist.ITaskActivityListener;
import org.eclipse.mylar.tasklist.ITaskCategory;
import org.eclipse.mylar.tasklist.ITaskHandler;
import org.eclipse.mylar.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.tasklist.internal.Task;
import org.eclipse.mylar.tasklist.internal.TaskCategory;
import org.eclipse.mylar.tasklist.internal.TaskCompleteFilter;
import org.eclipse.mylar.tasklist.internal.TaskPriorityFilter;
import org.eclipse.mylar.tasklist.ui.IDynamicSubMenuContributor;
import org.eclipse.mylar.tasklist.ui.ITaskFilter;
import org.eclipse.mylar.tasklist.ui.ITaskListElement;
import org.eclipse.mylar.tasklist.ui.TaskEditorInput;
import org.eclipse.mylar.tasklist.ui.TaskListImages;
import org.eclipse.mylar.tasklist.ui.TaskListPatternFilter;
import org.eclipse.mylar.tasklist.ui.actions.CollapseAllAction;
import org.eclipse.mylar.tasklist.ui.actions.CopyDescriptionAction;
import org.eclipse.mylar.tasklist.ui.actions.CreateCategoryAction;
import org.eclipse.mylar.tasklist.ui.actions.CreateTaskAction;
import org.eclipse.mylar.tasklist.ui.actions.DeleteAction;
import org.eclipse.mylar.tasklist.ui.actions.FilterCompletedTasksAction;
import org.eclipse.mylar.tasklist.ui.actions.GoIntoAction;
import org.eclipse.mylar.tasklist.ui.actions.GoUpAction;
import org.eclipse.mylar.tasklist.ui.actions.ManageEditorsAction;
import org.eclipse.mylar.tasklist.ui.actions.MarkTaskCompleteAction;
import org.eclipse.mylar.tasklist.ui.actions.MarkTaskIncompleteAction;
import org.eclipse.mylar.tasklist.ui.actions.NextTaskDropDownAction;
import org.eclipse.mylar.tasklist.ui.actions.OpenTaskEditorAction;
import org.eclipse.mylar.tasklist.ui.actions.PreviousTaskDropDownAction;
import org.eclipse.mylar.tasklist.ui.actions.RemoveFromCategoryAction;
import org.eclipse.mylar.tasklist.ui.actions.RenameAction;
import org.eclipse.mylar.tasklist.ui.actions.TaskActivateAction;
import org.eclipse.mylar.tasklist.ui.actions.TaskDeactivateAction;
import org.eclipse.mylar.tasklist.ui.actions.WorkOfflineAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.dialogs.FilteredTree;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.PluginTransfer;
import org.eclipse.ui.part.ViewPart;
/**
* @author Mik Kersten
* @author Ken Sueda
*/
public class TaskListView extends ViewPart {
private static final String LABEL_NO_TASKS = "no task active";
public static final String ID = "org.eclipse.mylar.tasks.ui.views.TaskListView";
public static final String[] PRIORITY_LEVELS = {
MylarTaskListPlugin.PriorityLevel.P1.toString(),
MylarTaskListPlugin.PriorityLevel.P2.toString(),
MylarTaskListPlugin.PriorityLevel.P3.toString(),
MylarTaskListPlugin.PriorityLevel.P4.toString(),
MylarTaskListPlugin.PriorityLevel.P5.toString() };
private static final String SEPARATOR_ID_REPORTS = "reports";
private static final String PART_NAME = "Mylar Tasks";
private static TaskListView INSTANCE;
FilteredTree tree;
private DrillDownAdapter drillDownAdapter;
private ITaskCategory drilledIntoCategory = null;
private GoIntoAction goIntoAction;
private GoUpAction goUpAction;
private WorkOfflineAction workOffline;
private CopyDescriptionAction copyDescriptionAction;
private OpenTaskEditorAction openAction;
private OpenTaskEditorAction openTaskEditor; // TODO: remove?
private CreateTaskAction createTaskAction;
private CreateCategoryAction createCategoryAction;
private RenameAction rename;
private CollapseAllAction collapseAll;
private DeleteAction deleteAction;
private ManageEditorsAction autoClose;
private RemoveFromCategoryAction removeAction;
private TaskActivateAction activateAction = new TaskActivateAction();
private TaskDeactivateAction deactivateAction = new TaskDeactivateAction();
private MarkTaskCompleteAction markIncompleteAction;
private MarkTaskIncompleteAction markCompleteAction;
private FilterCompletedTasksAction filterCompleteTask;
private PriorityDropDownAction filterOnPriority;
private PreviousTaskDropDownAction previousTaskAction;
private NextTaskDropDownAction nextTaskAction;
private static TaskPriorityFilter PRIORITY_FILTER = new TaskPriorityFilter();
private static TaskCompleteFilter COMPLETE_FILTER = new TaskCompleteFilter();
List<ITaskFilter> filters = new ArrayList<ITaskFilter>();
static final String FILTER_LABEL = "<filter>";
protected String[] columnNames = new String[] { "", ".", "!", "Description" };
protected int[] columnWidths = new int[] { 70, 20, 20, 120 };
private TreeColumn[] columns;
private IMemento taskListMemento;
public static final String columnWidthIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.columnwidth";
public static final String tableSortIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.sortIndex";
private int sortIndex = 2;
private TaskActivationHistory taskHistory = new TaskActivationHistory();
/**
* True if the view should indicate that interaction monitoring is paused
*/
protected boolean isPaused = false;
private final ITaskActivityListener ACTIVITY_LISTENER = new ITaskActivityListener() {
public void taskActivated(ITask task) {
updateDescription(task);
}
public void tasksActivated(List<ITask> tasks) {
if (tasks.size() > 0) {
updateDescription(tasks.get(0));
}
}
public void taskDeactivated(ITask task) {
updateDescription(null);
}
public void taskChanged(ITask task) {
// ignore
}
public void tasklistRead() {
if (!getViewer().getControl().isDisposed()) getViewer().refresh();
}
public void tasklistModified() {
if (!getViewer().getControl().isDisposed()) getViewer().refresh();
}
};
private final class PriorityDropDownAction extends Action implements IMenuCreator {
private Menu dropDownMenu = null;
public PriorityDropDownAction() {
super();
setText("Priority Filter");
setToolTipText("Filter Priority Lower Than");
setImageDescriptor(TaskListImages.FILTER_PRIORITY);
setMenuCreator(this);
}
public void dispose() {
if (dropDownMenu != null) {
dropDownMenu.dispose();
dropDownMenu = null;
}
}
public Menu getMenu(Control parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public Menu getMenu(Menu parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public void addActionsToMenu() {
Action P1 = new Action(PRIORITY_LEVELS[0], AS_CHECK_BOX) {
@Override
public void run() {
MylarTaskListPlugin.setPriorityLevel(MylarTaskListPlugin.PriorityLevel.P1);
PRIORITY_FILTER.displayPrioritiesAbove(PRIORITY_LEVELS[0]);
getViewer().refresh();
}
};
P1.setEnabled(true);
P1.setToolTipText(PRIORITY_LEVELS[0]);
ActionContributionItem item = new ActionContributionItem(P1);
item.fill(dropDownMenu, -1);
Action P2 = new Action(PRIORITY_LEVELS[1], AS_CHECK_BOX) {
@Override
public void run() {
MylarTaskListPlugin.setPriorityLevel(MylarTaskListPlugin.PriorityLevel.P2);
PRIORITY_FILTER.displayPrioritiesAbove(PRIORITY_LEVELS[1]);
getViewer().refresh();
}
};
P2.setEnabled(true);
P2.setToolTipText(PRIORITY_LEVELS[1]);
item = new ActionContributionItem(P2);
item.fill(dropDownMenu, -1);
Action P3 = new Action(PRIORITY_LEVELS[2], AS_CHECK_BOX) {
@Override
public void run() {
MylarTaskListPlugin.setPriorityLevel(MylarTaskListPlugin.PriorityLevel.P3);
PRIORITY_FILTER.displayPrioritiesAbove(PRIORITY_LEVELS[2]);
getViewer().refresh();
}
};
P3.setEnabled(true);
P3.setToolTipText(PRIORITY_LEVELS[2]);
item = new ActionContributionItem(P3);
item.fill(dropDownMenu, -1);
Action P4 = new Action(PRIORITY_LEVELS[3], AS_CHECK_BOX) {
@Override
public void run() {
MylarTaskListPlugin.setPriorityLevel(MylarTaskListPlugin.PriorityLevel.P4);
PRIORITY_FILTER.displayPrioritiesAbove(PRIORITY_LEVELS[3]);
getViewer().refresh();
}
};
P4.setEnabled(true);
P4.setToolTipText(PRIORITY_LEVELS[3]);
item = new ActionContributionItem(P4);
item.fill(dropDownMenu, -1);
Action P5 = new Action(PRIORITY_LEVELS[4], AS_CHECK_BOX) {
@Override
public void run() {
MylarTaskListPlugin.setPriorityLevel(MylarTaskListPlugin.PriorityLevel.P5);
PRIORITY_FILTER.displayPrioritiesAbove(PRIORITY_LEVELS[4]);
getViewer().refresh();
}
};
P5.setEnabled(true);
P5.setToolTipText(PRIORITY_LEVELS[4]);
item = new ActionContributionItem(P5);
item.fill(dropDownMenu, -1);
String priority = MylarTaskListPlugin.getPriorityLevel();
if (priority.equals(PRIORITY_LEVELS[0])) {
P1.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[1])) {
P1.setChecked(true);
P2.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[2])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[3])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
P4.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[4])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
P4.setChecked(true);
P5.setChecked(true);
}
}
public void run() {
this.setChecked(isChecked());
}
}
public static TaskListView openInActivePerspective() {
try {
return (TaskListView) Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().showView(ID);
} catch (Exception e) {
return null;
}
}
public TaskListView() {
INSTANCE = this;
MylarTaskListPlugin.getTaskListManager().addListener(ACTIVITY_LISTENER); // TODO: remove on close?
}
/**
* TODO: should be updated when view mode switches to fast and vice-versa
*/
private void updateDescription(ITask task) {
if (getSite() == null || getSite().getPage() == null) return;
IViewReference reference = getSite().getPage().findViewReference(ID);
boolean isFastView = false;
if (reference != null && reference.isFastView()) {
isFastView = true;
}
if (task != null) {
setTitleToolTip(PART_NAME + " (" + task.getDescription(true) + ")");
if (isFastView) {
setContentDescription(task.getDescription(true));
} else {
setContentDescription("");
}
} else {
setTitleToolTip(PART_NAME);
if (isFastView) {
setContentDescription(LABEL_NO_TASKS);
} else {
setContentDescription("");
}
}
}
class TaskListCellModifier implements ICellModifier {
public boolean canModify(Object element, String property) {
int columnIndex = Arrays.asList(columnNames).indexOf(property);
if (columnIndex == 0 && element instanceof ITaskListElement) {
return ((ITaskListElement) element).isActivatable();
} else if (columnIndex == 2 && element instanceof ITask) {
return ((ITask) element).isLocal();
}
// int columnIndex = Arrays.asList(columnNames).indexOf(property);
// if (element instanceof ITask) {
// ITask task = (ITask)element;
// switch (columnIndex) {
// case 0: return true;
// case 1: return false;
// case 2: return task.isDirectlyModifiable();
// case 3: return task.isDirectlyModifiable();
// } else if (element instanceof AbstractCategory) {
// switch (columnIndex) {
// case 0:
// case 1:
// case 2:
// return false;
// case 3: return ((AbstractCategory)element).isDirectlyModifiable();
else if (element instanceof ITaskListElement && isInRenameAction) {
ITaskListElement taskListElement = (ITaskListElement) element;
switch (columnIndex) {
// case 0: return taskListElement.isActivatable();
// case 1: return false;
// case 2: return taskListElement.isDirectlyModifiable();
case 3:
return taskListElement.isLocal();
}
}
return false;
}
public Object getValue(Object element, String property) {
try {
int columnIndex = Arrays.asList(columnNames).indexOf(property);
if (element instanceof ITaskListElement) {
final ITaskListElement taskListElement = (ITaskListElement) element;
ITask task = null;
if (taskListElement instanceof ITask) {
task = (ITask) taskListElement;
} else if (taskListElement instanceof IQueryHit) {
if (((IQueryHit) taskListElement).hasCorrespondingActivatableTask()) {
task = ((IQueryHit) taskListElement).getOrCreateCorrespondingTask();
}
}
switch (columnIndex) {
case 0:
if (task == null) {
return Boolean.TRUE;
} else {
return new Boolean(task.isCompleted());
}
case 1:
return "";
case 2:
String priorityString = taskListElement.getPriority().substring(1);
return new Integer(priorityString);
case 3:
return taskListElement.getDescription(true);
}
} else if (element instanceof ITaskCategory) {
ITaskCategory cat = (ITaskCategory) element;
switch (columnIndex) {
case 0:
return new Boolean(false);
case 1:
return "";
case 2:
return "";
case 3:
return cat.getDescription(true);
}
} else if (element instanceof IQuery) {
IQuery cat = (IQuery) element;
switch (columnIndex) {
case 0:
return new Boolean(false);
case 1:
return "";
case 2:
return "";
case 3:
return cat.getDescription(true);
}
}
} catch (Exception e) {
MylarPlugin.log(e, e.getMessage());
}
return "";
}
public void modify(Object element, String property, Object value) {
int columnIndex = -1;
try {
columnIndex = Arrays.asList(columnNames).indexOf(property);
if (((TreeItem) element).getData() instanceof ITaskCategory) {
ITaskCategory cat = (ITaskCategory) ((TreeItem) element).getData();
switch (columnIndex) {
case 0:
// getViewer().setSelection(null);
break;
case 1:
break;
case 2:
break;
case 3:
cat.setDescription(((String) value).trim());
// getViewer().setSelection(null);
break;
}
} else if (((TreeItem) element).getData() instanceof IQuery) {
IQuery cat = (IQuery) ((TreeItem) element).getData();
switch (columnIndex) {
case 0:
// getViewer().setSelection(null);
break;
case 1:
break;
case 2:
break;
case 3:
cat.setDescription(((String) value).trim());
// getViewer().setSelection(null);
break;
}
} else if (((TreeItem) element).getData() instanceof ITaskListElement) {
final ITaskListElement taskListElement = (ITaskListElement) ((TreeItem) element).getData();
ITask task = null;
if (taskListElement instanceof ITask) {
task = (ITask) taskListElement;
} else if (taskListElement instanceof IQueryHit) {
if (((IQueryHit) taskListElement).hasCorrespondingActivatableTask()) {
task = ((IQueryHit) taskListElement).getOrCreateCorrespondingTask();
}
}
switch (columnIndex) {
case 0:
if (taskListElement instanceof IQueryHit) {
task = ((IQueryHit) taskListElement).getOrCreateCorrespondingTask();
}
if (task != null) {
if (task.isActive()) {
new TaskDeactivateAction().run();
nextTaskAction.setEnabled(taskHistory.hasNext());
previousTaskAction.setEnabled(taskHistory.hasPrevious());
} else {
new TaskActivateAction().run();
addTaskToHistory(task);
}
// getViewer().setSelection(null);
}
break;
case 1:
break;
case 2:
if (task.isLocal()) {
Integer intVal = (Integer) value;
task.setPriority("P" + (intVal + 1));
// getViewer().setSelection(null);
}
break;
case 3:
if (task.isLocal()) {
task.setDescription(((String) value).trim());
// MylarTaskListPlugin.getTaskListManager().notifyTaskPropertyChanged(task, columnNames[3]);
MylarTaskListPlugin.getTaskListManager().notifyTaskChanged(task);
}
break;
}
}
} catch (Exception e) {
MylarPlugin.fail(e, e.getMessage(), true);
}
getViewer().refresh();
}
}
public void addTaskToHistory(ITask task) {
if (!MylarTaskListPlugin.getDefault().isMultipleMode()) {
taskHistory.addTask(task);
nextTaskAction.setEnabled(taskHistory.hasNext());
previousTaskAction.setEnabled(taskHistory.hasPrevious());
}
}
public void clearTaskHistory() {
taskHistory.clear();
}
private class TaskListTableSorter extends ViewerSorter {
private String column;
public TaskListTableSorter(String column) {
super();
this.column = column;
}
/**
* compare - invoked when column is selected calls the actual comparison
* method for particular criteria
*/
@Override
public int compare(Viewer compareViewer, Object o1, Object o2) {
if (o1 instanceof ITaskCategory || o1 instanceof IQuery) {
if (o2 instanceof ITaskCategory || o2 instanceof IQuery) {
return ((ITaskListElement) o1).getDescription(false).compareTo(((ITaskListElement) o2).getDescription(false));
} else {
return -1;
}
} else if (o1 instanceof ITaskListElement) {
if (o2 instanceof ITaskCategory || o2 instanceof IQuery) {
return -1;
} else if (o2 instanceof ITaskListElement) {
ITaskListElement element1 = (ITaskListElement) o1;
ITaskListElement element2 = (ITaskListElement) o2;
// if (element1.isCompleted() && element2.isCompleted()) {
// return element1.getPriority().compareTo(element2.getPriority());
// if (element1.isCompleted()) return 1;
// if (element2.isCompleted()) return -1;
// if (element1.hasCorrespondingActivatableTask() && element2.hasCorrespondingActivatableTask()) {
// ITask task1 = element1.getOrCreateCorrespondingTask();
// ITask task2 = element2.getOrCreateCorrespondingTask();
// if (task1.isCompleted()) return 1;
// if (task2.isCompleted()) return -1;
if (column != null && column.equals(columnNames[1])) {
return 0;
} else if (column == columnNames[2]) {
return element1.getPriority().compareTo(element2.getPriority());
} else if (column == columnNames[3]) {
String c1 = element1.getStringForSortingDescription();
String c2 = element2.getStringForSortingDescription();
try {
return new Integer(c1).compareTo(new Integer(c2));
} catch (Exception e) {
}
return c1.compareTo(c2);
} else {
return 0;
}
}
} else {
return 0;
}
return 0;
}
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
init(site);
this.taskListMemento = memento;
}
@Override
public void saveState(IMemento memento) {
IMemento colMemento = memento.createChild(columnWidthIdentifier);
for (int i = 0; i < columnWidths.length; i++) {
IMemento m = colMemento.createChild("col" + i);
m.putInteger("width", columnWidths[i]);
}
IMemento sorter = memento.createChild(tableSortIdentifier);
IMemento m = sorter.createChild("sorter");
m.putInteger("sortIndex", sortIndex);
MylarTaskListPlugin.getDefault().createTaskListBackupFile();
if (MylarTaskListPlugin.getDefault() != null) {
MylarTaskListPlugin.getDefault().saveTaskListAndContexts();
}
}
private void restoreState() {
if (taskListMemento != null) {
IMemento taskListWidth = taskListMemento.getChild(columnWidthIdentifier);
if (taskListWidth != null) {
for (int i = 0; i < columnWidths.length; i++) {
IMemento m = taskListWidth.getChild("col" + i);
if (m != null) {
int width = m.getInteger("width");
columnWidths[i] = width;
columns[i].setWidth(width);
}
}
}
IMemento sorterMemento = taskListMemento.getChild(tableSortIdentifier);
if (sorterMemento != null) {
IMemento m = sorterMemento.getChild("sorter");
if (m != null) {
sortIndex = m.getInteger("sortIndex");
} else {
sortIndex = 2;
}
} else {
sortIndex = 2; // default priority
}
getViewer().setSorter(new TaskListTableSorter(columnNames[sortIndex]));
}
addFilter(PRIORITY_FILTER);
// if (MylarTaskListPlugin.getDefault().isFilterInCompleteMode())
// MylarTaskListPlugin.getTaskListManager().getTaskList().addFilter(inCompleteFilter);
if (MylarTaskListPlugin.getDefault().isFilterCompleteMode())
addFilter(COMPLETE_FILTER);
if (MylarTaskListPlugin.getDefault().isMultipleMode()) {
togglePreviousAction(false);
toggleNextAction(false);
}
getViewer().refresh();
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
@Override
public void createPartControl(Composite parent) {
tree = new FilteredTree(parent, SWT.VERTICAL | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
// addToolTipHandler();
// ((Text)tree.getFilterControl()).setText(FILTER_LABEL);
getViewer().getTree().setHeaderVisible(true);
getViewer().getTree().setLinesVisible(true);
getViewer().setColumnProperties(columnNames);
getViewer().setUseHashlookup(true);
columns = new TreeColumn[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TreeColumn(getViewer().getTree(), 0); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
final int index = i;
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sortIndex = index;
getViewer().setSorter(new TaskListTableSorter(columnNames[sortIndex]));
}
});
columns[i].addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
for (int j = 0; j < columnWidths.length; j++) {
if (columns[j].equals(e.getSource())) {
columnWidths[j] = columns[j].getWidth();
}
}
}
public void controlMoved(ControlEvent e) {
// don't care if the control is moved
}
});
}
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = new CheckboxCellEditor();
editors[1] = textEditor;
editors[2] = new ComboBoxCellEditor(getViewer().getTree(), PRIORITY_LEVELS, SWT.READ_ONLY);
editors[3] = textEditor;
getViewer().setCellEditors(editors);
getViewer().setCellModifier(new TaskListCellModifier());
getViewer().setSorter(new TaskListTableSorter(columnNames[sortIndex]));
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setContentProvider(new TasklistContentProvider(this));
TasklistLabelProvider labelProvider = new TasklistLabelProvider();
labelProvider.setBackgroundColor(parent.getBackground());
getViewer().setLabelProvider(labelProvider);
getViewer().setInput(getViewSite());
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (rename.isEnabled()) {
rename.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDescriptionAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
createTaskAction.run();
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK to support right click anywhere to select an item
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
Tree t = getViewer().getTree();
TreeItem item = t.getItem(new Point(e.x, e.y));
if (e.button == 3 && item != null) {
getViewer().setSelection(new StructuredSelection(item.getData()));
} else if (item == null) {
getViewer().setSelection(new StructuredSelection());
}
}
public void mouseUp(MouseEvent e) {
}
});
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(rename, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
ToolTipHandler toolTipHandler = new ToolTipHandler(getViewer().getControl().getShell());
toolTipHandler.activateHoverHelp(getViewer().getControl());
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = MylarTaskListPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
}
@MylarWebRef(name = "Drag and drop article", url = "http:
private void initDragAndDrop(Composite parent) {
Transfer[] types = new Transfer[] { TextTransfer.getInstance(), PluginTransfer.getInstance() };
getViewer().addDragSupport(DND.DROP_MOVE, types, new TaskListDragSourceListener(this));
getViewer().addDropSupport(DND.DROP_MOVE, types, new TaskListDropAdapter(getViewer()));
}
void expandToActiveTasks() {
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
List<ITask> activeTasks = MylarTaskListPlugin.getTaskListManager().getTaskList().getActiveTasks();
for (ITask t : activeTasks) {
getViewer().expandToLevel(t, 0);
}
}
});
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TaskListView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(getViewer().getControl());
getViewer().getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, getViewer());
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
updateDrillDownActions();
// manager.add(new Separator("reports"));
// manager.add(new Separator("local"));
// manager.add(createTaskAction);
// manager.add(createCategoryAction);
manager.add(goUpAction);
manager.add(collapseAll);
// manager.add(new Separator());
// autoClose.setEnabled(true);
manager.add(new Separator("context"));
manager.add(autoClose);
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(workOffline);
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(new Separator(SEPARATOR_ID_REPORTS));
manager.add(createTaskAction);
// manager.add(createCategoryAction);
manager.add(new Separator());
manager.add(filterCompleteTask);
manager.add(filterOnPriority);
manager.add(new Separator("navigation"));
manager.add(previousTaskAction);
manager.add(nextTaskAction);
manager.add(new Separator("context"));
// manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
void fillContextMenu(IMenuManager manager) {
updateDrillDownActions();
ITaskListElement element = null;
;
final Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
element = (ITaskListElement) selectedObject;
}
addAction(openAction, manager, element);
if ((element instanceof ITask) || (element instanceof IQueryHit)) {
ITask task = null;
boolean isLocal = element.getClass().equals(Task.class); // HACK
if (element instanceof IQueryHit) {
task = ((IQueryHit) element).getOrCreateCorrespondingTask();
} else {
task = (ITask) element;
}
if (task.isActive()) {
manager.add(deactivateAction);
} else {
manager.add(activateAction);
}
if (isLocal) {
if (task.isCompleted()) {
addAction(markCompleteAction, manager, element);
} else {
addAction(markIncompleteAction, manager, element);
}
}
// HACK: to avoid removing local tasks
if (!isLocal) {
addAction(removeAction, manager, element);
}
}
// manager.add(new Separator("tasks"));
addAction(deleteAction, manager, element);
if (element instanceof ITaskCategory) {
manager.add(goIntoAction);
}
if (drilledIntoCategory != null) {
manager.add(goUpAction);
}
// addAction(rename, manager, element);
// addAction(copyDescriptionAction, manager, element);
manager.add(new Separator("local"));
manager.add(createTaskAction);
manager.add(createCategoryAction);
manager.add(new Separator("reports"));
manager.add(new Separator("context"));
for (IDynamicSubMenuContributor contributor : MylarTaskListPlugin.getDefault().getDynamicMenuContributers()) {
MenuManager subMenuManager = contributor.getSubMenuManager(this, (ITaskListElement) selectedObject);
if (subMenuManager != null)
addMenuManager(subMenuManager, manager, element);
}
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void addMenuManager(IMenuManager menuToAdd, IMenuManager manager, ITaskListElement element) {
if (element != null && element instanceof ITask) {
manager.add(menuToAdd);
}
}
private void addAction(Action action, IMenuManager manager, ITaskListElement element) {
manager.add(action);
if (element != null) {
ITaskHandler handler = MylarTaskListPlugin.getDefault().getHandlerForElement(element);
if (handler != null) {
action.setEnabled(handler.enableAction(action, element));
} else {
updateActionEnablement(action, element);
}
}
}
private void updateActionEnablement(Action action, ITaskListElement element) {
if (element instanceof ITask) {
if (action instanceof MarkTaskCompleteAction) {
if (element.isCompleted()) {
action.setEnabled(false);
} else {
action.setEnabled(true);
}
} else if (action instanceof MarkTaskIncompleteAction) {
if (element.isCompleted()) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof DeleteAction) {
action.setEnabled(true);
} else if (action instanceof CreateTaskAction) {
action.setEnabled(false);
} else if (action instanceof OpenTaskEditorAction) {
action.setEnabled(true);
} else if (action instanceof CopyDescriptionAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
action.setEnabled(true);
}
} else if (element instanceof ITaskCategory) {
if (action instanceof MarkTaskCompleteAction) {
action.setEnabled(false);
} else if (action instanceof MarkTaskIncompleteAction) {
action.setEnabled(false);
} else if (action instanceof DeleteAction) {
if (((ITaskCategory) element).isArchive())
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof CreateTaskAction) {
if (((ITaskCategory) element).isArchive())
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof GoIntoAction) {
TaskCategory cat = (TaskCategory) element;
if (cat.getChildren().size() > 0) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof OpenTaskEditorAction) {
action.setEnabled(false);
} else if (action instanceof CopyDescriptionAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
if (((ITaskCategory) element).isArchive())
action.setEnabled(false);
else
action.setEnabled(true);
}
} else {
action.setEnabled(true);
}
// if(!canEnableGoInto){
// goIntoAction.setEnabled(false);
}
private void makeActions() {
copyDescriptionAction = new CopyDescriptionAction(this);
openAction = new OpenTaskEditorAction(this);
workOffline = new WorkOfflineAction();
goIntoAction = new GoIntoAction();
goUpAction = new GoUpAction(drillDownAdapter);
createTaskAction = new CreateTaskAction(this);
createCategoryAction = new CreateCategoryAction(this);
removeAction = new RemoveFromCategoryAction(this);
rename = new RenameAction(this);
deleteAction = new DeleteAction(this);
collapseAll = new CollapseAllAction(this);
autoClose = new ManageEditorsAction();
markIncompleteAction = new MarkTaskCompleteAction(this);
markCompleteAction = new MarkTaskIncompleteAction(this);
openTaskEditor = new OpenTaskEditorAction(this);
filterCompleteTask = new FilterCompletedTasksAction(this);
filterOnPriority = new PriorityDropDownAction();
previousTaskAction = new PreviousTaskDropDownAction(this, taskHistory);
nextTaskAction = new NextTaskDropDownAction(this, taskHistory);
}
public void toggleNextAction(boolean enable) {
nextTaskAction.setEnabled(enable);
}
public void togglePreviousAction(boolean enable) {
previousTaskAction.setEnabled(enable);
}
public NextTaskDropDownAction getNextTaskAction() {
return nextTaskAction;
}
public PreviousTaskDropDownAction getPreviousTaskAction() {
return previousTaskAction;
}
/**
* Recursive function that checks for the occurrence of a certain task id.
* All children of the supplied node will be checked.
*
* @param task
* The <code>ITask</code> object that is to be searched.
* @param taskId
* The id that is being searched for.
* @return <code>true</code> if the id was found in the node or any of its
* children
*/
protected boolean lookForId(String taskId) {
return (MylarTaskListPlugin.getTaskListManager().getTaskForHandle(taskId, true) == null);
// for (ITask task : MylarTaskListPlugin.getTaskListManager().getTaskList().getRootTasks()) {
// if (task.getHandle().equals(taskId)) {
// return true;
// for (TaskCategory cat : MylarTaskListPlugin.getTaskListManager().getTaskList().getTaskCategories()) {
// for (ITask task : cat.getChildren()) {
// if (task.getHandle().equals(taskId)) {
// return true;
// return false;
}
public void closeTaskEditors(ITask task, IWorkbenchPage page) throws LoginException, IOException {
ITaskHandler taskHandler = MylarTaskListPlugin.getDefault().getHandlerForElement(task);
if (taskHandler != null) {
taskHandler.taskClosed(task, page);
} else if (task instanceof Task) {
IEditorInput input = new TaskEditorInput((Task) task);
IEditorPart editor = page.findEditor(input);
if (editor != null) {
page.closeEditor(editor, false);
}
}
}
private void hookOpenAction() {
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
openTaskEditor.run();
}
});
}
public void showMessage(String message) {
MessageDialog.openInformation(getViewer().getControl().getShell(), "TaskList Message", message);
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
getViewer().getControl().setFocus();
}
public String getBugIdFromUser() {
InputDialog dialog = new InputDialog(Workbench.getInstance().getActiveWorkbenchWindow().getShell(), "Enter Bugzilla ID", "Enter the Bugzilla ID: ", "",
null);
int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
return dialog.getValue();
} else {
return null;
}
}
// public String[] getLabelPriorityFromUser(String kind) {
// String[] result = new String[2];
// Dialog dialog = null;
// boolean isTask = kind.equals("task");
// if (isTask) {
// dialog = new TaskInputDialog(
// Workbench.getInstance().getActiveWorkbenchWindow().getShell());
// } else {
// dialog = new InputDialog(
// Workbench.getInstance().getActiveWorkbenchWindow().getShell(),
// "Enter name",
// "Enter a name for the " + kind + ": ",
// null);
// int dialogResult = dialog.open();
// if (dialogResult == Window.OK) {
// if (isTask) {
// result[0] = ((TaskInputDialog)dialog).getTaskname();
// result[1] = ((TaskInputDialog)dialog).getSelectedPriority();
// } else {
// result[0] = ((InputDialog)dialog).getValue();
// return result;
// } else {
// return null;
public void notifyTaskDataChanged(ITask task) {
if (getViewer().getTree() != null && !getViewer().getTree().isDisposed()) {
getViewer().refresh();
expandToActiveTasks();
}
}
public static TaskListView getDefault() {
return INSTANCE;
}
public TreeViewer getViewer() {
return tree.getViewer();
}
public TaskCompleteFilter getCompleteFilter() {
return COMPLETE_FILTER;
}
public TaskPriorityFilter getPriorityFilter() {
return PRIORITY_FILTER;
}
public void addFilter(ITaskFilter filter) {
if (!filters.contains(filter))
filters.add(filter);
}
public void removeFilter(ITaskFilter filter) {
filters.remove(filter);
}
@Override
public void dispose() {
super.dispose();
}
public void updateDrillDownActions() {
if (drillDownAdapter.canGoBack()) {
goUpAction.setEnabled(true);
} else {
goUpAction.setEnabled(false);
}
// if(drillDownAdapter.canGoInto()){
// canEnableGoInto = true;
// } else {
// canEnableGoInto = false;
}
/**
* HACK: This is used for the copy action
* @return
*/
public Composite getFakeComposite() {
return tree;
}
private boolean isInRenameAction = false;
public void setInRenameAction(boolean b) {
isInRenameAction = b;
}
/**
* This method is for testing only
*/
public TaskActivationHistory getTaskActivationHistory() {
return taskHistory;
}
public void goIntoCategory() {
ISelection selection = getViewer().getSelection();
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITaskCategory) {
drilledIntoCategory = (ITaskCategory) element;
drillDownAdapter.goInto();
updateDrillDownActions();
}
}
}
public void goUpToRoot() {
drilledIntoCategory = null;
drillDownAdapter.goBack();
updateDrillDownActions();
}
public ITask getSelectedTask() {
ISelection selection = getViewer().getSelection();
if (selection.isEmpty())
return null;
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (ITask) structuredSelection.getFirstElement();
} else if (element instanceof IQueryHit) {
return ((IQueryHit) element).getOrCreateCorrespondingTask();
}
}
return null;
}
public void indicatePaused(boolean paused) {
isPaused = paused;
IStatusLineManager statusLineManager = getViewSite().getActionBars().getStatusLineManager();
if (isPaused) {
statusLineManager.setMessage(
TaskListImages.getImage(TaskListImages.TASKLIST),
"Mylar context capture paused");
} else {
statusLineManager.setMessage("");
}
}
/**
* Show the shared data folder currently in use.
* Call with "" to turn off the indication.
* TODO: Need a better way to indicate paused and/or the shared folder
*/
public void indicateSharedFolder(String folderName) {
if (folderName.equals("")) {
if (isPaused) {
setPartName("(paused) " + PART_NAME);
} else {
setPartName(PART_NAME);
}
} else {
if (isPaused) {
setPartName("(paused) " + folderName + " " + PART_NAME);
} else {
setPartName(folderName + " " + PART_NAME);
}
}
}
public ITaskCategory getDrilledIntoCategory() {
return drilledIntoCategory;
}
// @Override
// public String getTitleToolTip() {
// return "xxx";
}
|
package org.jcryptool.core.actions;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerService;
import org.jcryptool.core.CorePlugin;
import org.jcryptool.core.logging.utils.LogUtil;
import org.osgi.framework.Bundle;
/**
* a class to show all registered editors in a drop down list at the coolbar the action should open a new editors page.
*
* @author mwalthart
* @version 0.5.0
*/
public class ShowEditorsPulldownMenuAction implements IWorkbenchWindowPulldownDelegate {
private Menu showEditorsPulldownMenu;
/**
* Creates a new menu as a singleton object.
*/
public Menu getMenu(Control parent) {
if (showEditorsPulldownMenu == null) {
showEditorsPulldownMenu = createEditorsMenu(parent, showEditorsPulldownMenu);
}
MenuItem[] items = showEditorsPulldownMenu.getItems();
for (MenuItem item : items) {
item.setEnabled(true);
}
return showEditorsPulldownMenu;
}
/**
* Creates the menu.
*
* @param parent
* @param menu
* @return
*/
private static Menu createEditorsMenu(Control parent, Menu menu) {
if (menu == null) {
menu = new Menu(parent);
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(
"org.jcryptool.core.operations.editorServices"); //$NON-NLS-1$
Comparator<IConfigurationElement> comp = new Comparator<IConfigurationElement>() {
public int compare(IConfigurationElement o1, IConfigurationElement o2) {
String l1 = o1.getAttribute("label"); //$NON-NLS-1$
String l2 = o2.getAttribute("label"); //$NON-NLS-1$
String c1 = o1.getAttribute("category"); //$NON-NLS-1$
String c2 = o2.getAttribute("category"); //$NON-NLS-1$
int cat = c1.compareTo(c2);
int label = l1.compareTo(l2);
if (cat != 0) {
return cat;
} else {
if (o1.getAttribute("id").contains("org.jcryptool.editor.text") //$NON-NLS-1$ //$NON-NLS-2$
&& !o2.getAttribute("id").contains("org.jcryptool.editor.text")) {
return -1;
}
if (!o1.getAttribute("id").contains("org.jcryptool.editor.text") //$NON-NLS-1$ //$NON-NLS-2$
&& o2.getAttribute("id").contains("org.jcryptool.editor.text")) {
return 1;
}
if (label != 0) {
return label;
} else {
return o2.hashCode() - o1.hashCode();
}
}
}
};
Set<IConfigurationElement> entries = new TreeSet<IConfigurationElement>(comp);
for (IExtension extension : point.getExtensions()) {
for (IConfigurationElement element : extension.getConfigurationElements()) {
entries.add(element);
}
}
String currentCat = entries.size() > 0 ? entries.iterator().next().getAttribute("category") : null; //$NON-NLS-1$
for (IConfigurationElement element : entries) {
if (!currentCat.equals(element.getAttribute("category"))) { //$NON-NLS-1$
new MenuItem(menu, SWT.SEPARATOR);
currentCat = element.getAttribute("category"); //$NON-NLS-1$
}
final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
// Set the Labels to the entries
menuItem.setText(element.getAttribute("label")); //$NON-NLS-1$
// set the actions to the entries
try {
Object o = element.createExecutableExtension("pushAction"); //$NON-NLS-1$
menuItem.setData(o);
} catch (CoreException e) {
LogUtil.logError(CorePlugin.PLUGIN_ID, e);
}
String iconPath = element.getAttribute("icon"); // subpath of the icon within the plugin //$NON-NLS-1$
if ((iconPath != null) && (!iconPath.equals(""))) { //$NON-NLS-1$
try {
Object o = element.getAttribute("id"); // id of the plugin for path resolution //$NON-NLS-1$
if (o != null) {
Bundle bundle = Platform.getBundle(o.toString());
URL fileUrl = FileLocator.find(bundle, new Path("/"), null); //$NON-NLS-1$
fileUrl = FileLocator.toFileURL(fileUrl);
iconPath = fileUrl.getFile() + iconPath;
menuItem.setImage(new Image(null, iconPath));
}
} catch (IOException ex) {
LogUtil.logError(CorePlugin.PLUGIN_ID, ex);
}
}
// Handle selection
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
final IHandlerService handlerService
= (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
IEvaluationContext evaluationContext
= handlerService.createContextSnapshot(true);
ExecutionEvent event
= new ExecutionEvent(null, Collections.EMPTY_MAP, null, evaluationContext);
// execute the actions
Object o = ((MenuItem) e.getSource()).getData();
try {
IHandler handler = (IHandler) o;
handler.execute(event);
}
catch(Exception ex) {
LogUtil.logError(CorePlugin.PLUGIN_ID, ex);
}
}
});
}
}
return menu;
}
/**
* Removes the menu.
*/
public void dispose() {
if (showEditorsPulldownMenu != null) {
showEditorsPulldownMenu.dispose();
}
}
/**
* Unused.
*/
public void init(IWorkbenchWindow window) {
}
/**
* Rhe implementation of the on click action.
*/
public void run(IAction action) {
// connects to the extension point
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint("org.jcryptool.core.editorButton"); //$NON-NLS-1$
IExtension extension = point.getExtensions()[0];
IConfigurationElement element = extension.getConfigurationElements()[0];
final IHandlerService handlerService
= (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
IEvaluationContext evaluationContext
= handlerService.createContextSnapshot(true);
ExecutionEvent event
= new ExecutionEvent(null, Collections.EMPTY_MAP, null, evaluationContext);
try {
// runs the defined action
IHandler handler = (IHandler) element.createExecutableExtension("OnClickClass"); //$NON-NLS-1$
handler.execute(event);
} catch (CoreException ex) {
LogUtil.logError(CorePlugin.PLUGIN_ID, ex);
} catch (ExecutionException ex) {
LogUtil.logError(CorePlugin.PLUGIN_ID, ex);
}
}
/**
* Unused.
*/
public void selectionChanged(IAction action, ISelection selection) {
}
}
|
package fr.unice.polytech.al.trafficlight.electriccar.provider;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import java.io.IOException;
public class CommunicationService {
private final static Logger LOG = Logger.getLogger(CommunicationService.class);
String routeUrl = "https://route-smart-city.herokuapp.com/premium/crossroad/";
public void ImHere(String crossroadId, String trafficLightId, String carId) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPut req = new HttpPut(routeUrl + crossroadId + "/trafficlight/" + trafficLightId + "/vehicle/" + carId);
req.addHeader("accept", "application/json");
req.addHeader("Content-Type", "application/json");
HttpResponse result = httpClient.execute(req);
System.out.println("response status :" + result.getStatusLine().getStatusCode());
LOG.info("response status :" + result.getStatusLine().getStatusCode());
} catch (IOException ex) {
}
}
public void ILeave(String crossroadId, String trafficLightId, String carId) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpDelete req = new HttpDelete(routeUrl + crossroadId + "/trafficlight/" + trafficLightId + "/vehicle/" + carId);
req.addHeader("accept", "application/json");
req.addHeader("Content-Type", "application/json");
HttpResponse result = httpClient.execute(req);
System.out.println("response status :" + result.getStatusLine().getStatusCode());
LOG.info("response status :" + result.getStatusLine().getStatusCode());
} catch (IOException ex) {
}
}
}
|
package org.geomajas.gwt.client.command.event;
import org.geomajas.annotation.Api;
import com.google.gwt.event.shared.HandlerRegistration;
import org.geomajas.annotation.UserImplemented;
/**
* Classes triggering the {@link DispatchStartedEvent} should implement this interface, thereby allowing handlers to be
* registered to catch these events.
*
* @author Jan De Moerloose
* @since 1.6.0
*/
@Api
@UserImplemented
public interface HasDispatchHandlers {
/**
* Add a new handler for {@link DispatchStartedEvent} events.
*
* @param handler The handler to be registered.
* @return Returns the handlers registration object.
*/
HandlerRegistration addDispatchStartedHandler(DispatchStartedHandler handler);
/**
* Add a new handler for {@link DispatchStoppedEvent} events.
*
* @param handler The handler to be registered.
* @return Returns the handlers registration object.
*/
HandlerRegistration addDispatchStoppedHandler(DispatchStoppedHandler handler);
}
|
package org.eclipse.persistence.testing.framework.ui;
import org.eclipse.persistence.Version;
public class TestingBrowserFrame extends javax.swing.JFrame implements java.awt.event.ActionListener {
private javax.swing.JPanel ivjJFrameContentPane = null;
private TestingBrowserPanel ivjTestingBrowserPanel1 = null;
private javax.swing.JMenuItem ivjExitMenuItem = null;
private javax.swing.JMenu ivjFile = null;
private javax.swing.JMenuBar ivjTestingBrowserFrameJMenuBar = null;
private javax.swing.JSeparator ivjJSeparator1 = null;
private javax.swing.JSeparator ivjJSeparator11 = null;
private javax.swing.JSeparator ivjJSeparator2 = null;
private javax.swing.JMenuItem ivjKillMenuItem = null;
private javax.swing.JMenu ivjLoadBuildMenu = null;
private javax.swing.JMenuItem ivjLogResultsMenuItem = null;
private javax.swing.JMenuItem ivjQueryResultsMenuItem = null;
private javax.swing.JMenuItem ivjRebuildTestsMenuItem = null;
private javax.swing.JMenuItem ivjResetMenuItem = null;
private javax.swing.JMenuItem ivjResetModelsMenuItem = null;
private javax.swing.JMenuItem ivjRunMenuItem = null;
private javax.swing.JMenuItem ivjSaveResultsMenuItem = null;
private javax.swing.JMenuItem ivjSetupMenuItem = null;
private javax.swing.JMenuItem ivjStopMenuItem = null;
private javax.swing.JMenu ivjTestMenu = null;
/**
* Constructor
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
public TestingBrowserFrame() {
super();
initialize();
}
/**
* TestingBrowserFrame constructor comment.
* @param title java.lang.String
*/
public TestingBrowserFrame(String title) {
super(title);
}
/**
* Method to handle events for the ActionListener interface.
* @param e java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
public void actionPerformed(java.awt.event.ActionEvent e) {
// user code begin {1}
if (e.getSource() == getExitMenuItem()) {
this.setVisible(false);
this.dispose();
System.exit(0);
}
// user code end
if (e.getSource() == getRunMenuItem()) {
connEtoC1(e);
}
if (e.getSource() == getSetupMenuItem()) {
connEtoC2(e);
}
if (e.getSource() == getResetMenuItem()) {
connEtoC3(e);
}
if (e.getSource() == getStopMenuItem()) {
connEtoC4(e);
}
if (e.getSource() == getQueryResultsMenuItem()) {
connEtoC5(e);
}
if (e.getSource() == getSaveResultsMenuItem()) {
connEtoC6(e);
}
if (e.getSource() == getResetModelsMenuItem()) {
connEtoC7(e);
}
if (e.getSource() == getRebuildTestsMenuItem()) {
connEtoC8(e);
}
if (e.getSource() == getKillMenuItem()) {
connEtoC9(e);
}
if (e.getSource() == getLogResultsMenuItem()) {
connEtoC10(e);
}
// user code begin {2}
// user code end
}
/**
* connEtoC1: (RunMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1RunTest()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC1(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1RunTest();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC10: (LogResultsMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1LogTestResults()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC10(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1LogTestResults();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC2: (SetupMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1SetupTest()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC2(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1SetupTest();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC3: (ResetMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1ResetTest()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC3(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1ResetTest();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC4: (StopMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1StopTest()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC4(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1StopTest();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC5: (QueryResultsMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1QueryLoadBuild()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC5(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1QueryLoadBuild();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC6: (SaveResultsMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1SaveLoadBuild()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC6(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1SaveLoadBuild();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC7: (ResetModelsMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1RefreshModels()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC7(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1RefreshModels();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC8: (RebuildTestsMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1RefreshTests()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC8(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1RefreshTests();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* connEtoC9: (KillMenuItem.action.actionPerformed(java.awt.event.ActionEvent) --> TestingBrowserFrame.testingBrowserPanel1KillTest()V)
* @param arg1 java.awt.event.ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC9(java.awt.event.ActionEvent arg1) {
try {
// user code begin {1}
// user code end
this.testingBrowserPanel1KillTest();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
}
}
/**
* Return the ExitMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getExitMenuItem() {
if (ivjExitMenuItem == null) {
try {
ivjExitMenuItem = new javax.swing.JMenuItem();
ivjExitMenuItem.setName("ExitMenuItem");
ivjExitMenuItem.setText("Exit");
ivjExitMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjExitMenuItem;
}
/**
* Return the File property value.
* @return javax.swing.JMenu
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenu getFile() {
if (ivjFile == null) {
try {
ivjFile = new javax.swing.JMenu();
ivjFile.setName("File");
ivjFile.setText("File");
ivjFile.setBackground(java.awt.SystemColor.control);
ivjFile.setActionCommand("FileMenu");
ivjFile.add(getExitMenuItem());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjFile;
}
/**
* Return the JFrameContentPane property value.
* @return javax.swing.JPanel
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JPanel getJFrameContentPane() {
if (ivjJFrameContentPane == null) {
try {
ivjJFrameContentPane = new javax.swing.JPanel();
ivjJFrameContentPane.setName("JFrameContentPane");
ivjJFrameContentPane.setLayout(new java.awt.GridBagLayout());
ivjJFrameContentPane.setBackground(java.awt.SystemColor.control);
java.awt.GridBagConstraints constraintsTestingBrowserPanel1 = new java.awt.GridBagConstraints();
constraintsTestingBrowserPanel1.gridx = 1;
constraintsTestingBrowserPanel1.gridy = 1;
constraintsTestingBrowserPanel1.fill = java.awt.GridBagConstraints.BOTH;
constraintsTestingBrowserPanel1.weightx = 1.0;
constraintsTestingBrowserPanel1.weighty = 1.0;
constraintsTestingBrowserPanel1.insets = new java.awt.Insets(2, 2, 2, 2);
getJFrameContentPane().add(getTestingBrowserPanel1(), constraintsTestingBrowserPanel1);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjJFrameContentPane;
}
/**
* Return the JSeparator1 property value.
* @return javax.swing.JSeparator
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JSeparator getJSeparator1() {
if (ivjJSeparator1 == null) {
try {
ivjJSeparator1 = new javax.swing.JSeparator();
ivjJSeparator1.setName("JSeparator1");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjJSeparator1;
}
/**
* Return the JSeparator11 property value.
* @return javax.swing.JSeparator
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JSeparator getJSeparator11() {
if (ivjJSeparator11 == null) {
try {
ivjJSeparator11 = new javax.swing.JSeparator();
ivjJSeparator11.setName("JSeparator11");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjJSeparator11;
}
/**
* Return the JSeparator2 property value.
* @return javax.swing.JSeparator
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JSeparator getJSeparator2() {
if (ivjJSeparator2 == null) {
try {
ivjJSeparator2 = new javax.swing.JSeparator();
ivjJSeparator2.setName("JSeparator2");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjJSeparator2;
}
/**
* Return the KillMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getKillMenuItem() {
if (ivjKillMenuItem == null) {
try {
ivjKillMenuItem = new javax.swing.JMenuItem();
ivjKillMenuItem.setName("KillMenuItem");
ivjKillMenuItem.setText("Kill");
ivjKillMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjKillMenuItem;
}
/**
* Return the LoadBuildMenu property value.
* @return javax.swing.JMenu
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenu getLoadBuildMenu() {
if (ivjLoadBuildMenu == null) {
try {
ivjLoadBuildMenu = new javax.swing.JMenu();
ivjLoadBuildMenu.setName("LoadBuildMenu");
ivjLoadBuildMenu.setText("Test Results");
ivjLoadBuildMenu.setBackground(java.awt.SystemColor.control);
ivjLoadBuildMenu.setActionCommand("FileMenu");
ivjLoadBuildMenu.add(getRebuildTestsMenuItem());
ivjLoadBuildMenu.add(getResetModelsMenuItem());
ivjLoadBuildMenu.add(getJSeparator11());
ivjLoadBuildMenu.add(getLogResultsMenuItem());
ivjLoadBuildMenu.add(getJSeparator2());
ivjLoadBuildMenu.add(getSaveResultsMenuItem());
ivjLoadBuildMenu.add(getQueryResultsMenuItem());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjLoadBuildMenu;
}
/**
* Return the LogResultsMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getLogResultsMenuItem() {
if (ivjLogResultsMenuItem == null) {
try {
ivjLogResultsMenuItem = new javax.swing.JMenuItem();
ivjLogResultsMenuItem.setName("LogResultsMenuItem");
ivjLogResultsMenuItem.setText("Log Results");
ivjLogResultsMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjLogResultsMenuItem;
}
/**
* Return the QueryResultsMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getQueryResultsMenuItem() {
if (ivjQueryResultsMenuItem == null) {
try {
ivjQueryResultsMenuItem = new javax.swing.JMenuItem();
ivjQueryResultsMenuItem.setName("QueryResultsMenuItem");
ivjQueryResultsMenuItem.setText("Query Test Results");
ivjQueryResultsMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjQueryResultsMenuItem;
}
/**
* Return the RebuildTestsMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getRebuildTestsMenuItem() {
if (ivjRebuildTestsMenuItem == null) {
try {
ivjRebuildTestsMenuItem = new javax.swing.JMenuItem();
ivjRebuildTestsMenuItem.setName("RebuildTestsMenuItem");
ivjRebuildTestsMenuItem.setText("Rebuild Tests");
ivjRebuildTestsMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjRebuildTestsMenuItem;
}
/**
* Return the ResetMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getResetMenuItem() {
if (ivjResetMenuItem == null) {
try {
ivjResetMenuItem = new javax.swing.JMenuItem();
ivjResetMenuItem.setName("ResetMenuItem");
ivjResetMenuItem.setText("Reset");
ivjResetMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjResetMenuItem;
}
/**
* Return the ResetModelsMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getResetModelsMenuItem() {
if (ivjResetModelsMenuItem == null) {
try {
ivjResetModelsMenuItem = new javax.swing.JMenuItem();
ivjResetModelsMenuItem.setName("ResetModelsMenuItem");
ivjResetModelsMenuItem.setText("Reset Models");
ivjResetModelsMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjResetModelsMenuItem;
}
/**
* Return the RunMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getRunMenuItem() {
if (ivjRunMenuItem == null) {
try {
ivjRunMenuItem = new javax.swing.JMenuItem();
ivjRunMenuItem.setName("RunMenuItem");
ivjRunMenuItem.setText("Run");
ivjRunMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjRunMenuItem;
}
/**
* Return the SaveResultsMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getSaveResultsMenuItem() {
if (ivjSaveResultsMenuItem == null) {
try {
ivjSaveResultsMenuItem = new javax.swing.JMenuItem();
ivjSaveResultsMenuItem.setName("SaveResultsMenuItem");
ivjSaveResultsMenuItem.setText("Save Results");
ivjSaveResultsMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjSaveResultsMenuItem;
}
/**
* Return the SetupMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getSetupMenuItem() {
if (ivjSetupMenuItem == null) {
try {
ivjSetupMenuItem = new javax.swing.JMenuItem();
ivjSetupMenuItem.setName("SetupMenuItem");
ivjSetupMenuItem.setText("Setup");
ivjSetupMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjSetupMenuItem;
}
/**
* Return the StopMenuItem property value.
* @return javax.swing.JMenuItem
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuItem getStopMenuItem() {
if (ivjStopMenuItem == null) {
try {
ivjStopMenuItem = new javax.swing.JMenuItem();
ivjStopMenuItem.setName("StopMenuItem");
ivjStopMenuItem.setText("Stop");
ivjStopMenuItem.setBackground(java.awt.SystemColor.control);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjStopMenuItem;
}
/**
* Return the TestingBrowserFrameJMenuBar property value.
* @return javax.swing.JMenuBar
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenuBar getTestingBrowserFrameJMenuBar() {
if (ivjTestingBrowserFrameJMenuBar == null) {
try {
ivjTestingBrowserFrameJMenuBar = new javax.swing.JMenuBar();
ivjTestingBrowserFrameJMenuBar.setName("TestingBrowserFrameJMenuBar");
ivjTestingBrowserFrameJMenuBar.setBackground(java.awt.SystemColor.control);
ivjTestingBrowserFrameJMenuBar.add(getFile());
ivjTestingBrowserFrameJMenuBar.add(getTestMenu());
ivjTestingBrowserFrameJMenuBar.add(getLoadBuildMenu());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjTestingBrowserFrameJMenuBar;
}
/**
* Return the TestingBrowserPanel1 property value.
* @return org.eclipse.persistence.testing.framework.ui.TestingBrowserPanel
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private TestingBrowserPanel getTestingBrowserPanel1() {
if (ivjTestingBrowserPanel1 == null) {
try {
ivjTestingBrowserPanel1 = new org.eclipse.persistence.testing.framework.ui.TestingBrowserPanel();
ivjTestingBrowserPanel1.setName("TestingBrowserPanel1");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjTestingBrowserPanel1;
}
/**
* Return the TestMenu property value.
* @return javax.swing.JMenu
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private javax.swing.JMenu getTestMenu() {
if (ivjTestMenu == null) {
try {
ivjTestMenu = new javax.swing.JMenu();
ivjTestMenu.setName("TestMenu");
ivjTestMenu.setText("Test");
ivjTestMenu.setBackground(java.awt.SystemColor.control);
ivjTestMenu.setActionCommand("FileMenu");
ivjTestMenu.add(getRunMenuItem());
ivjTestMenu.add(getSetupMenuItem());
ivjTestMenu.add(getResetMenuItem());
ivjTestMenu.add(getJSeparator1());
ivjTestMenu.add(getKillMenuItem());
ivjTestMenu.add(getStopMenuItem());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
}
}
return ivjTestMenu;
}
/**
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
*/
private void handleException(Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
System.out.println("
exception.printStackTrace(System.out);
}
/**
* Initializes connections
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
// user code begin {1}
getExitMenuItem().addActionListener(this);
// user code end
getRunMenuItem().addActionListener(this);
getSetupMenuItem().addActionListener(this);
getResetMenuItem().addActionListener(this);
getStopMenuItem().addActionListener(this);
getQueryResultsMenuItem().addActionListener(this);
getSaveResultsMenuItem().addActionListener(this);
getResetModelsMenuItem().addActionListener(this);
getRebuildTestsMenuItem().addActionListener(this);
getKillMenuItem().addActionListener(this);
getLogResultsMenuItem().addActionListener(this);
}
/**
* Initialize the class.
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("TestingBrowserFrame");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setJMenuBar(getTestingBrowserFrameJMenuBar());
setSize(901, 574);
setTitle("Testing Browser" + ": EclipseLink " + Version.getVersion() + " " + Version.getBuildNumber());
setContentPane(getJFrameContentPane());
initConnections();
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
}
// user code begin {2}
// user code end
}
/**
* build a window event handler (anonymous class)
* this handler closes the window *and* shuts down the system
*/
protected static java.awt.event.WindowListener getWindowShutdown() {
return new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
java.awt.Window window = e.getWindow();
window.setVisible(false);
window.dispose();
System.exit(0);
}
};
}
/**
* main entrypoint - starts the part when it is run as an application
* @param args java.lang.String[]
*/
public static void main(java.lang.String[] args) {
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
TestingBrowserFrame aTestingBrowserFrame;
aTestingBrowserFrame = new TestingBrowserFrame();
aTestingBrowserFrame.addWindowListener(getWindowShutdown());
aTestingBrowserFrame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of javax.swing.JFrame");
exception.printStackTrace(System.out);
}
}
public void testingBrowserPanel1KillTest() {
getTestingBrowserPanel1().killTest();
}
public void testingBrowserPanel1LogTestResults() {
getTestingBrowserPanel1().logTestResults();
}
public void testingBrowserPanel1QueryLoadBuild() {
getTestingBrowserPanel1().queryLoadBuild();
}
public void testingBrowserPanel1RefreshModels() {
getTestingBrowserPanel1().refreshModels();
}
public void testingBrowserPanel1RefreshTests() {
getTestingBrowserPanel1().refreshTests();
}
public void testingBrowserPanel1ResetTest() {
getTestingBrowserPanel1().resetTest();
}
public void testingBrowserPanel1RunTest() {
getTestingBrowserPanel1().runTest();
}
public void testingBrowserPanel1SaveLoadBuild() {
getTestingBrowserPanel1().saveLoadBuild();
}
public void testingBrowserPanel1SetupTest() {
getTestingBrowserPanel1().setupTest();
}
public void testingBrowserPanel1StopTest() {
getTestingBrowserPanel1().stopTest();
}
}
|
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtension;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.patterns.ElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.Consumer;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Completion FAQ:<p>
*
* Q: How do I implement code completion?<br>
* A: Define a completion.contributor extension of type {@link CompletionContributor}.
* Or, if the place you want to complete in contains a {@link PsiReference}, just return the variants
* you want to suggest from its {@link PsiReference#getVariants()} method as {@link String}s,
* {@link PsiElement}s, or better {@link LookupElement}s.<p>
*
* Q: OK, but what to do with CompletionContributor?<br>
* A: There are two ways. The easier and preferred one is to provide constructor in your contributor and register completion providers there:
* {@link #extend(CompletionType, ElementPattern, CompletionProvider)}.<br>
* A more generic way is to override default {@link #fillCompletionVariants(CompletionParameters, CompletionResultSet)} implementation
* and provide your own. It's easier to debug, but harder to write.<p>
*
* Q: What does the {@link CompletionParameters#getPosition()} return?<br>
* A: When completion is invoked, the file being edited is first copied (the original file can be accessed from {@link com.intellij.psi.PsiFile#getOriginalFile()}
* and {@link CompletionParameters#getOriginalFile()}. Then a special 'dummy identifier' string is inserted to the copied file at caret offset (removing the selection).
* Most often this string is an identifier (see {@link CompletionInitializationContext#DUMMY_IDENTIFIER}).
* This is usually done to guarantee that there'll always be some non-empty element there, which will be easy to describe via {@link ElementPattern}s.
* Also a reference can suddenly appear in that position, which will certainly help invoking its {@link PsiReference#getVariants()}.
* Dummy identifier string can be easily changed in {@link #beforeCompletion(CompletionInitializationContext)} method.<p>
*
* Q: How do I get automatic lookup element filtering by prefix?<br>
* A: When you return variants from reference ({@link PsiReference#getVariants()}), the filtering will be done
* automatically, with prefix taken as the reference text from its start ({@link PsiReference#getRangeInElement()}) to
* the caret position.
* In {@link CompletionContributor} you will be given a {@link CompletionResultSet}
* which will match {@link LookupElement}s against its prefix matcher {@link CompletionResultSet#getPrefixMatcher()}.
* If the default prefix calculated by the IDE doesn't satisfy you, you can obtain another result set via
* {@link CompletionResultSet#withPrefixMatcher(PrefixMatcher)} and feed your lookup elements to the latter.
* It's one of the item's lookup strings ({@link LookupElement#getAllLookupStrings()} that is matched against prefix matcher.<p>
*
* Q: How do I plug into those funny texts below the items in shown lookup?<br>
* A: Use {@link CompletionResultSet#addLookupAdvertisement(String)} <p>
*
* Q: How do I change the text that gets shown when there are no suitable variants at all? <br>
* A: Use {@link CompletionContributor#handleEmptyLookup(CompletionParameters, Editor)}.
* Don't forget to check whether you are in correct place (see {@link CompletionParameters}).<p>
*
* Q: How do I affect lookup element's appearance (icon, text attributes, etc.)?<br>
* A: See {@link LookupElement#renderElement(LookupElementPresentation)}.<p>
*
* Q: I'm not satisfied that completion just inserts the item's lookup string on item selection. How to make it write something else?<br>
* A: See {@link LookupElement#handleInsert(InsertionContext)}.<p>
*
* Q: What if I select item with TAB key?<br>
* A: Semantics is, that the identifier that you're standing inside gets removed completely, and then the lookup string is inserted. You can change
* the deleting range end offset, do it in {@link CompletionContributor#beforeCompletion(CompletionInitializationContext)}
* by putting new offset to {@link CompletionInitializationContext#getOffsetMap()} as {@link CompletionInitializationContext#IDENTIFIER_END_OFFSET}.<p>
*
* Q: I know more about my environment than the IDE does, and I can swear that those 239 variants it suggests me in some place aren't all that relevant,
* so I'd be happy to filter out 42 of them. How do I do this?<br>
* A: This is a bit harder than just adding variants. First, you should invoke
* {@link CompletionResultSet#runRemainingContributors(CompletionParameters, Consumer)}.
* The consumer you provide should pass all the lookup elements to the {@link CompletionResultSet}
* given to you, except for the ones you wish to filter out. Be careful: it's too easy to break completion this way. Since you've
* ordered to invoke remaining contributors yourself, they won't be invoked automatically after yours finishes (see
* {@link CompletionResultSet#stopHere()} and {@link CompletionResultSet#isStopped()}).
* Calling {@link CompletionResultSet#stopHere()} explicitly will stop other contributors (which happened to be loaded after yours)
* from execution, and the user will never see their so useful and precious completion variants, so please be careful with this method.<p>
*
* Q: How are lookup elements sorted?<br>
* A: Basically in lexicographic order, ascending, by lookup string ({@link LookupElement#getLookupString()}).
* Also there's a number of "weigher" extensions under "completion" key (see {@link CompletionWeigher}) that bubble up the most relevant
* items. To control lookup elements order you may implement {@link CompletionWeigher} or use {@link PrioritizedLookupElement}.<br>
* To debug the order of the completion items use '<code>Dump lookup element weights to log</code>' action when the completion lookup is
* shown (Ctrl+Alt+Shift+W / Cmd+Alt+Shift+W), the action also copies the debug info to the the Clipboard.
* <p>
*
* Q: My completion is not working! How do I debug it?<br>
* A: One source of common errors is that the pattern you gave to {@link #extend(CompletionType, ElementPattern, CompletionProvider)} method
* may be incorrect. To debug this problem you can still override {@link #fillCompletionVariants(CompletionParameters, CompletionResultSet)} in
* your contributor, make it only call its super and put a breakpoint there.<br>
* If you want to know which contributor added a particular lookup element, the best place for a breakpoint will be
* {@link CompletionService#performCompletion(CompletionParameters, Consumer)}. The consumer passed there
* is the 'final' consumer, it will pass your lookup elements directly to the lookup.<br>
* If your contributor isn't even invoked, probably there was another contributor that said 'stop' to the system, and yours happened to be ordered after
* that contributor. To test this hypothesis, put a breakpoint to
* {@link CompletionService#getVariantsFromContributors(CompletionParameters, CompletionContributor, Consumer)},
* to the 'return false' line.<p>
*
* @author peter
*/
public abstract class CompletionContributor {
private final MultiMap<CompletionType, Pair<ElementPattern<? extends PsiElement>, CompletionProvider<CompletionParameters>>> myMap =
new MultiMap<>();
public final void extend(@Nullable CompletionType type,
@NotNull final ElementPattern<? extends PsiElement> place, CompletionProvider<CompletionParameters> provider) {
myMap.putValue(type, new Pair<>(place, provider));
}
/**
* The main contributor method that is supposed to provide completion variants to result, based on completion parameters.
* The default implementation looks for {@link CompletionProvider}s you could register by
* invoking {@link #extend(CompletionType, ElementPattern, CompletionProvider)} from your contributor constructor,
* matches the desired completion type and {@link ElementPattern} with actual ones, and, depending on it, invokes those
* completion providers.<p>
*
* If you want to implement this functionality directly by overriding this method, the following is for you.
* Always check that parameters match your situation, and that completion type ({@link CompletionParameters#getCompletionType()}
* is of your favourite kind. This method is run inside a read action. If you do any long activity non-related to PSI in it, please
* ensure you call {@link com.intellij.openapi.progress.ProgressManager#checkCanceled()} often enough so that the completion process
* can be cancelled smoothly when the user begins to type in the editor.
*/
public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull CompletionResultSet result) {
for (final Pair<ElementPattern<? extends PsiElement>, CompletionProvider<CompletionParameters>> pair : myMap.get(parameters.getCompletionType())) {
ProgressManager.checkCanceled();
final ProcessingContext context = new ProcessingContext();
if (pair.first.accepts(parameters.getPosition(), context)) {
pair.second.addCompletionVariants(parameters, context, result);
if (result.isStopped()) {
return;
}
}
}
for (final Pair<ElementPattern<? extends PsiElement>, CompletionProvider<CompletionParameters>> pair : myMap.get(null)) {
final ProcessingContext context = new ProcessingContext();
if (pair.first.accepts(parameters.getPosition(), context)) {
pair.second.addCompletionVariants(parameters, context, result);
if (result.isStopped()) {
return;
}
}
}
}
/**
* Invoked before completion is started. Is used mainly for determining custom offsets in editor, and to change default dummy identifier.
*/
public void beforeCompletion(@NotNull CompletionInitializationContext context) {
}
/**
* @deprecated use {@link CompletionResultSet#addLookupAdvertisement(String)}
* @return text to be shown at the bottom of lookup list
*/
@Deprecated
@Nullable
public String advertise(@NotNull CompletionParameters parameters) {
return null;
}
/**
*
* @return hint text to be shown if no variants are found, typically "No suggestions"
*/
@Nullable
public String handleEmptyLookup(@NotNull CompletionParameters parameters, final Editor editor) {
return null;
}
/**
* Called when the completion is finished quickly, lookup hasn't been shown and gives possibility to autoinsert some item (typically - the only one).
*/
@Nullable
public AutoCompletionDecision handleAutoCompletionPossibility(@NotNull AutoCompletionContext context) {
return null;
}
/**
* Don't use this method, because {@code position} can come from uncommitted PSI and be totally unrelated to the code being currently in the document/editor.
* Please consider using {@link com.intellij.codeInsight.editorActions.TypedHandlerDelegate#checkAutoPopup} instead.
*/
@Deprecated
public boolean invokeAutoPopup(@NotNull PsiElement position, char typeChar) {
return false;
}
/**
* Invoked in a read action in parallel to the completion process. Used to calculate the replacement offset
* (see {@link CompletionInitializationContext#setReplacementOffset(int)})
* if it takes too much time to spend it in {@link #beforeCompletion(CompletionInitializationContext)},
* e.g. doing {@link com.intellij.psi.PsiFile#findReferenceAt(int)}
*
* Guaranteed to be invoked before any lookup element is selected
*
* @param context context
*/
public void duringCompletion(@NotNull CompletionInitializationContext context) {
}
/**
* @return String representation of action shortcut. Useful while advertising something
* @see #advertise(CompletionParameters)
*/
@NotNull
protected static String getActionShortcut(@NonNls @NotNull final String actionId) {
return KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(actionId));
}
@NotNull
public static List<CompletionContributor> forParameters(@NotNull final CompletionParameters parameters) {
return ReadAction.compute(() -> {
PsiElement position = parameters.getPosition();
return forLanguageHonorDumbness(PsiUtilCore.getLanguageAtOffset(position.getContainingFile(), parameters.getOffset()), position.getProject());
});
}
@NotNull
public static List<CompletionContributor> forLanguage(@NotNull Language language) {
return INSTANCE.forKey(language);
}
@NotNull
public static List<CompletionContributor> forLanguageHonorDumbness(@NotNull Language language, @NotNull Project project) {
return DumbService.getInstance(project).filterByDumbAwareness(forLanguage(language));
}
private static final LanguageExtension<CompletionContributor> INSTANCE = new CompletionExtension<>("com.intellij.completion.contributor");
}
|
package com.oracle.graal.truffle.nodes.typesystem;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.extended.*;
import com.oracle.graal.nodes.spi.*;
public final class CustomizedUnsafeLoadNode extends UnsafeLoadNode {
@Input private ValueNode condition;
@Input private ValueNode locationIdentity;
public CustomizedUnsafeLoadNode(ValueNode object, ValueNode offset, Kind accessKind, ValueNode condition, ValueNode locationIdentity) {
super(object, 0, offset, accessKind);
this.condition = condition;
this.locationIdentity = locationIdentity;
}
public ValueNode getCondition() {
return condition;
}
public ValueNode getLocationIdentity() {
return locationIdentity;
}
@Override
public Node canonical(CanonicalizerTool tool) {
return this;
}
@Override
public void virtualize(VirtualizerTool tool) {
super.virtualize(tool);
}
@SuppressWarnings("unused")
@NodeIntrinsic
public static <T> T load(Object object, long offset, @ConstantNodeParameter Kind kind, boolean condition, Object locationIdentity) {
return UnsafeLoadNode.load(object, 0, offset, kind);
}
}
|
package com.intellij.openapi.projectRoots.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
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.progress.Task;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.roots.ui.configuration.*;
import com.intellij.openapi.roots.ui.configuration.UnknownSdkDownloadableSdkFix;
import com.intellij.openapi.roots.ui.configuration.UnknownSdkResolver.UnknownSdkLookup;
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTask;
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTracker;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.Consumer;
import com.intellij.util.TripleFunction;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.Update;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
import static com.intellij.openapi.progress.PerformInBackgroundOption.ALWAYS_BACKGROUND;
public class UnknownSdkTracker {
private static final Logger LOG = Logger.getInstance(UnknownSdkTracker.class);
@NotNull
public static UnknownSdkTracker getInstance(@NotNull Project project) {
return project.getService(UnknownSdkTracker.class);
}
@NotNull private final Project myProject;
@NotNull private final MergingUpdateQueue myUpdateQueue;
public UnknownSdkTracker(@NotNull Project project) {
myProject = project;
myUpdateQueue = new MergingUpdateQueue(getClass().getSimpleName(),
700,
true,
null,
myProject,
null,
false)
.usePassThroughInUnitTestMode();
}
public void updateUnknownSdks() {
myUpdateQueue.queue(new Update("update") {
@Override
public void run() {
if (!Registry.is("unknown.sdk") || !UnknownSdkResolver.EP_NAME.hasAnyExtensions()) {
showStatus(Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap());
return;
}
new UnknownSdkCollector(myProject)
.collectSdksPromise(snapshot -> {
//we cannot use snapshot#missingSdks here, because it affects other IDEs/languages where our logic is not good enough
onFixableAndMissingSdksCollected(filterOnlyAllowedEntries(snapshot.getResolvableSdks()));
});
}
});
}
private static boolean allowFixesFor(@NotNull SdkTypeId type) {
return UnknownSdkResolver.EP_NAME.findFirstSafe(it -> it.supportsResolution(type)) != null;
}
@NotNull
private static <E extends UnknownSdk> List<E> filterOnlyAllowedEntries(@NotNull List<? extends E> input) {
List<E> copy = new ArrayList<>();
for (E item : input) {
SdkType type = item.getSdkType();
if (allowFixesFor(type)) {
copy.add(item);
}
}
return copy;
}
private void onFixableAndMissingSdksCollected(@NotNull List<UnknownSdk> fixable) {
if (fixable.isEmpty()) {
showStatus(Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap());
return;
}
ProgressManager.getInstance()
.run(new Task.Backgroundable(myProject, ProjectBundle.message("progress.title.resolving.sdks"), false, ALWAYS_BACKGROUND) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setText(ProjectBundle.message("progress.text.resolving.missing.sdks"));
List<UnknownSdkLookup> lookups = collectSdkLookups(indicator);
indicator.setText(ProjectBundle.message("progress.text.looking.for.local.sdks"));
Map<UnknownSdk, UnknownSdkLocalSdkFix> localFixes = findFixesAndRemoveFixable(indicator, fixable, lookups, UnknownSdkLookup::proposeLocalFix);
indicator.setText(ProjectBundle.message("progress.text.looking.for.downloadable.sdks"));
Map<UnknownSdk, UnknownSdkDownloadableSdkFix> downloadFixes = findFixesAndRemoveFixable(indicator, fixable, lookups, UnknownSdkLookup::proposeDownload);
if (!localFixes.isEmpty()) {
indicator.setText(ProjectBundle.message("progress.text.configuring.sdks"));
configureLocalSdks(localFixes);
}
showStatus(fixable, localFixes, downloadFixes);
}
}
);
}
private void showStatus(@NotNull List<UnknownSdk> unknownSdksWithoutFix,
@NotNull Map<UnknownSdk, UnknownSdkLocalSdkFix> localFixes,
@NotNull Map<UnknownSdk, UnknownSdkDownloadableSdkFix> downloadFixes) {
UnknownSdkBalloonNotification
.getInstance(myProject)
.notifyFixedSdks(localFixes);
UnknownSdkEditorNotification
.getInstance(myProject)
.showNotifications(unknownSdksWithoutFix, downloadFixes);
}
@NotNull
private List<UnknownSdkLookup> collectSdkLookups(@NotNull ProgressIndicator indicator) {
List<UnknownSdkLookup> lookups = new ArrayList<>();
UnknownSdkResolver.EP_NAME.forEachExtensionSafe(ext -> {
UnknownSdkLookup resolver = ext.createResolver(myProject, indicator);
if (resolver != null) {
lookups.add(resolver);
}
});
return lookups;
}
public void applyDownloadableFix(@NotNull UnknownSdk info, @NotNull UnknownSdkDownloadableSdkFix fix) {
downloadFix(myProject, info, fix, sdk -> {}, sdk -> {
if (sdk != null) {
updateUnknownSdks();
}
});
}
@ApiStatus.Internal
public static void downloadFix(@Nullable Project project,
@NotNull UnknownSdk info,
@NotNull UnknownSdkDownloadableSdkFix fix,
@NotNull Consumer<? super Sdk> onSdkNameReady,
@NotNull Consumer<? super Sdk> onCompleted) {
SdkDownloadTask task;
String title = "Configuring SDK";
try {
task = ProgressManager.getInstance().run(new Task.WithResult<SdkDownloadTask, RuntimeException>(project, title, true) {
@Override
protected SdkDownloadTask compute(@NotNull ProgressIndicator indicator) {
return fix.createTask(indicator);
}
});
} catch (ProcessCanceledException e) {
onCompleted.consume(null);
throw e;
} catch (Exception error) {
LOG.warn("Failed to download " + info.getSdkType().getPresentableName() + " " + fix.getDownloadDescription() + " for " + info + ". " + error.getMessage(), error);
ApplicationManager.getApplication().invokeLater(() -> {
Messages.showErrorDialog(ProjectBundle.message("dialog.message.failed.to.download.0.1", fix.getDownloadDescription(),
error.getMessage()), title);
});
onCompleted.consume(null);
return;
}
ApplicationManager.getApplication().invokeLater(() -> {
try {
Disposable lifetime = Disposer.newDisposable();
String actualSdkName = info.getSdkName();
if (actualSdkName == null) {
actualSdkName = task.getSuggestedSdkName();
}
Sdk sdk = ProjectJdkTable.getInstance().createSdk(actualSdkName, info.getSdkType());
SdkDownloadTracker downloadTracker = SdkDownloadTracker.getInstance();
downloadTracker.registerSdkDownload(sdk, task);
downloadTracker.tryRegisterDownloadingListener(sdk, lifetime, new ProgressIndicatorBase(), success -> {
Disposer.dispose(lifetime);
onCompleted.consume(success ? sdk : null);
});
registerNewSdkInJdkTable(actualSdkName, sdk);
onSdkNameReady.consume(sdk);
downloadTracker.startSdkDownloadIfNeeded(sdk);
} catch (Exception error) {
LOG.warn("Failed to download " + info.getSdkType().getPresentableName() + " " + fix.getDownloadDescription() + " for " + info + ". " + error.getMessage(), error);
ApplicationManager.getApplication().invokeLater(() -> {
Messages.showErrorDialog(
ProjectBundle.message("dialog.message.failed.to.download.0.1", fix.getDownloadDescription(), error.getMessage()), title);
});
onCompleted.consume(null);
}
});
}
public void showSdkSelectionPopup(@Nullable String sdkName,
@Nullable SdkType sdkType,
@NotNull JComponent underneathRightOfComponent) {
SdkPopupFactory
.newBuilder()
.withProject(myProject)
.withSdkTypeFilter(type -> sdkType == null || Objects.equals(type, sdkType))
.onSdkSelected(sdk -> {
registerNewSdkInJdkTable(sdkName, sdk);
updateUnknownSdks();
})
.buildPopup()
.showUnderneathToTheRightOf(underneathRightOfComponent);
}
private void configureLocalSdks(@NotNull Map<UnknownSdk, UnknownSdkLocalSdkFix> localFixes) {
if (localFixes.isEmpty()) return;
for (Map.Entry<UnknownSdk, UnknownSdkLocalSdkFix> e : localFixes.entrySet()) {
UnknownSdk info = e.getKey();
UnknownSdkLocalSdkFix fix = e.getValue();
configureLocalSdk(info, fix, sdk -> {});
}
updateUnknownSdks();
}
@ApiStatus.Internal
public static void configureLocalSdk(@NotNull UnknownSdk info,
@NotNull UnknownSdkLocalSdkFix fix,
@NotNull Consumer<? super Sdk> onCompleted) {
ApplicationManager.getApplication().invokeLater(() -> {
try {
String actualSdkName = info.getSdkName();
if (actualSdkName == null) {
actualSdkName = fix.getSuggestedSdkName();
}
Sdk sdk = ProjectJdkTable.getInstance().createSdk(actualSdkName, info.getSdkType());
SdkModificator mod = sdk.getSdkModificator();
mod.setHomePath(FileUtil.toSystemIndependentName(fix.getExistingSdkHome()));
mod.setVersionString(fix.getVersionString());
mod.commitChanges();
try {
info.getSdkType().setupSdkPaths(sdk);
}
catch (Exception error) {
LOG.warn("Failed to setupPaths for " + sdk + ". " + error.getMessage(), error);
}
registerNewSdkInJdkTable(actualSdkName, sdk);
LOG.info("Automatically set Sdk " + info + " to " + fix.getExistingSdkHome());
onCompleted.consume(sdk);
} catch (Exception error) {
LOG.warn("Failed to configure " + info.getSdkType().getPresentableName() + " " + " for " + info + " for path " + fix + ". " + error.getMessage(), error);
onCompleted.consume(null);
}
});
}
@NotNull
private static <R> Map<UnknownSdk, R> findFixesAndRemoveFixable(@NotNull ProgressIndicator indicator,
@NotNull List<UnknownSdk> infos,
@NotNull List<UnknownSdkLookup> lookups,
@NotNull TripleFunction<UnknownSdkLookup, UnknownSdk, ProgressIndicator, R> fun) {
indicator.pushState();
Map<UnknownSdk, R> result = new LinkedHashMap<>();
for (Iterator<UnknownSdk> iterator = infos.iterator(); iterator.hasNext(); ) {
UnknownSdk info = iterator.next();
for (UnknownSdkLookup lookup : lookups) {
indicator.pushState();
R fix = fun.fun(lookup, info, indicator);
indicator.popState();
if (fix != null) {
result.put(info, fix);
iterator.remove();
break;
}
}
}
indicator.popState();
return result;
}
private static void registerNewSdkInJdkTable(@Nullable String sdkName, @NotNull Sdk sdk) {
WriteAction.run(() -> {
ProjectJdkTable table = ProjectJdkTable.getInstance();
if (sdkName != null) {
Sdk clash = table.findJdk(sdkName);
if (clash != null) {
LOG.warn("SDK with name " + sdkName + " already exists: clash=" + clash + ", new=" + sdk);
return;
}
SdkModificator mod = sdk.getSdkModificator();
mod.setName(sdkName);
mod.commitChanges();
}
table.addJdk(sdk);
});
}
}
|
package com.intellij.ide.ui.laf.darcula.ui;
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil;
import com.intellij.openapi.ui.ComboBoxWithWidePopup;
import com.intellij.openapi.ui.ErrorBorderCapable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.JBColor;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.beans.PropertyChangeListener;
import static com.intellij.ide.ui.laf.darcula.DarculaUIUtil.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaComboBoxUI extends BasicComboBoxUI implements Border, ErrorBorderCapable {
private static final Color NON_EDITABLE_BACKGROUND = JBColor.namedColor("ComboBox.darcula.nonEditableBackground", new JBColor(0xfcfcfc, 0x3c3f41));
public DarculaComboBoxUI() {}
@SuppressWarnings("unused")
@Deprecated
public DarculaComboBoxUI(JComboBox c) {}
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "unused"})
public static ComponentUI createUI(final JComponent c) {
return new DarculaComboBoxUI();
}
private KeyListener editorKeyListener;
private FocusListener editorFocusListener;
private PropertyChangeListener propertyListener;
@Override
protected void installDefaults() {
super.installDefaults();
installDarculaDefaults();
}
@Override
protected void uninstallDefaults() {
super.uninstallDefaults();
uninstallDarculaDefaults();
}
protected void installDarculaDefaults() {
comboBox.setBorder(this);
}
protected void uninstallDarculaDefaults() {
comboBox.setBorder(null);
}
@Override protected void installListeners() {
super.installListeners();
propertyListener = createPropertyListener();
comboBox.addPropertyChangeListener(propertyListener);
}
@Override public void uninstallListeners() {
super.uninstallListeners();
if (propertyListener != null) {
comboBox.removePropertyChangeListener(propertyListener);
propertyListener = null;
}
}
@Override
protected ComboPopup createPopup() {
return new CustomComboPopup(comboBox);
}
protected PropertyChangeListener createPropertyListener() {
return e -> {
if ("enabled".equals(e.getPropertyName())) {
EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class);
if (etf != null) {
boolean enabled = e.getNewValue() == Boolean.TRUE;
Color color = UIManager.getColor(enabled ? "TextField.background" : "ComboBox.disabledBackground");
etf.setBackground(color);
}
}
};
}
@Override
protected JButton createArrowButton() {
Color bg = comboBox.getBackground();
Color fg = comboBox.getForeground();
JButton button = new BasicArrowButton(SwingConstants.SOUTH, bg, fg, fg, fg) {
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
Rectangle r = new Rectangle(getSize());
JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1));
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g2.translate(r.x, r.y);
float bw = BW.getFloat();
float lw = LW.getFloat();
float arc = COMPONENT_ARC.getFloat() - bw - lw;
Path2D innerShape = new Path2D.Float();
innerShape.moveTo(lw, bw + lw);
innerShape.lineTo(r.width - bw - lw - arc, bw + lw);
innerShape.quadTo(r.width - bw - lw, bw + lw , r.width - bw - lw, bw + lw + arc);
innerShape.lineTo(r.width - bw - lw, r.height - bw - lw - arc);
innerShape.quadTo(r.width - bw - lw, r.height - bw - lw, r.width - bw - lw - arc, r.height - bw - lw);
innerShape.lineTo(lw, r.height - bw - lw);
innerShape.closePath();
g2.setColor(getArrowButtonBackgroundColor(comboBox.isEnabled(), comboBox.isEditable()));
g2.fill(innerShape);
// Paint vertical line
if (comboBox.isEditable()) {
g2.setColor(getOutlineColor(comboBox.isEnabled(), false));
g2.fill(new Rectangle2D.Float(0, bw + lw, LW.getFloat(), r.height - (bw + lw) * 2));
}
g2.setColor(getArrowButtonForegroundColor(comboBox.isEnabled()));
g2.fill(getArrowShape(this));
} finally {
g2.dispose();
}
}
@Override
public Dimension getPreferredSize() {
return getArrowButtonPreferredSize(comboBox);
}
};
button.setBorder(JBUI.Borders.empty());
button.setOpaque(false);
return button;
}
@SuppressWarnings("unused")
@Deprecated
protected Color getArrowButtonFillColor(Color defaultColor) {
return getArrowButtonBackgroundColor(comboBox.isEnabled(), comboBox.isEditable());
}
@NotNull
static Dimension getArrowButtonPreferredSize(@Nullable JComboBox comboBox) {
Insets i = comboBox != null ? comboBox.getInsets() : getDefaultComboBoxInsets();
int height = (isCompact(comboBox) ? COMPACT_HEIGHT.get() : MINIMUM_HEIGHT.get()) + i.top + i.bottom;
return new Dimension(ARROW_BUTTON_WIDTH.get() + i.left, height);
}
static Shape getArrowShape(Component button) {
Rectangle r = new Rectangle(button.getSize());
JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1));
int tW = JBUI.scale(9);
int tH = JBUI.scale(5);
int xU = (r.width - tW) / 2 - JBUI.scale(1);
int yU = (r.height - tH) / 2 + JBUI.scale(1);
Path2D path = new Path2D.Float();
path.moveTo(xU, yU);
path.lineTo(xU + tW, yU);
path.lineTo(xU + tW/2.0f, yU + tH);
path.lineTo(xU, yU);
path.closePath();
return path;
}
@NotNull
private static JBInsets getDefaultComboBoxInsets() {
return JBUI.insets(3);
}
@Override
public void paint(Graphics g, JComponent c) {
Container parent = c.getParent();
if (parent != null) {
g.setColor(DarculaUIUtil.isTableCellEditor(c) && editor != null ? editor.getBackground() : parent.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
Graphics2D g2 = (Graphics2D)g.create();
Rectangle r = new Rectangle(c.getSize());
JBInsets.removeFrom(r, JBUI.insets(1));
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g2.translate(r.x, r.y);
float bw = BW.getFloat();
float arc = COMPONENT_ARC.getFloat();
boolean editable = comboBox.isEnabled() && editor != null && comboBox.isEditable();
g2.setColor(editable ? editor.getBackground() : comboBox.isEnabled() ? NON_EDITABLE_BACKGROUND : UIUtil.getPanelBackground());
g2.fill(new RoundRectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2, arc, arc));
} finally {
g2.dispose();
}
if (!comboBox.isEditable()) {
checkFocus();
paintCurrentValue(g, rectangleForCurrentValue(), hasFocus);
}
}
/**
* @deprecated Use {@link DarculaUIUtil#isTableCellEditor(Component)} instead
*/
@Deprecated
protected static boolean isTableCellEditor(JComponent c) {
return DarculaUIUtil.isTableCellEditor(c);
}
@Override
public void paintCurrentValue(Graphics g, Rectangle bounds, boolean hasFocus) {
ListCellRenderer renderer = comboBox.getRenderer();
@SuppressWarnings("unchecked") Component c = renderer.getListCellRendererComponent(listBox, comboBox.getSelectedItem(), -1, false, false);
c.setFont(comboBox.getFont());
c.setBackground(comboBox.isEnabled() ? NON_EDITABLE_BACKGROUND : UIUtil.getPanelBackground());
if (hasFocus && !isPopupVisible(comboBox)) {
c.setForeground(listBox.getForeground());
} else {
c.setForeground(comboBox.isEnabled() ? comboBox.getForeground() : JBColor.namedColor("ComboBox.disabledForeground", comboBox.getForeground()));
}
// paint selection in table-cell-editor mode correctly
boolean changeOpaque = c instanceof JComponent && DarculaUIUtil.isTableCellEditor(comboBox) && c.isOpaque();
if (changeOpaque) {
((JComponent)c).setOpaque(false);
}
boolean shouldValidate = false;
if (c instanceof JPanel) {
shouldValidate = true;
}
Rectangle r = new Rectangle(bounds);
Insets iPad = null;
if (c instanceof SimpleColoredComponent) {
SimpleColoredComponent scc = (SimpleColoredComponent)c;
iPad = scc.getIpad();
scc.setIpad(JBUI.emptyInsets());
}
currentValuePane.paintComponent(g, c, comboBox, r.x, r.y, r.width, r.height, shouldValidate);
// return opaque for combobox popup items painting
if (changeOpaque) {
((JComponent)c).setOpaque(true);
}
if (c instanceof SimpleColoredComponent) {
SimpleColoredComponent scc = (SimpleColoredComponent)c;
scc.setIpad(iPad);
}
}
@Override
protected ComboBoxEditor createEditor() {
ComboBoxEditor comboBoxEditor = super.createEditor();
// Reset fixed columns amount set to 9 by default
if (comboBoxEditor instanceof BasicComboBoxEditor) {
JTextField tf = (JTextField)comboBoxEditor.getEditorComponent();
tf.setColumns(0);
}
installEditorKeyListener(comboBoxEditor);
return comboBoxEditor;
}
protected void installEditorKeyListener(@NotNull ComboBoxEditor cbe) {
Component ec = cbe.getEditorComponent();
if (ec != null) {
editorKeyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
process(e);
}
@Override
public void keyReleased(KeyEvent e) {
process(e);
}
private void process(KeyEvent e) {
final int code = e.getKeyCode();
if ((code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN) && e.getModifiers() == 0) {
comboBox.dispatchEvent(e);
}
}
};
ec.addKeyListener(editorKeyListener);
}
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (!(c instanceof JComponent)) return;
Graphics2D g2 = (Graphics2D)g.create();
float bw = BW.getFloat();
Rectangle r = new Rectangle(x, y, width, height);
try {
checkFocus();
if (!DarculaUIUtil.isTableCellEditor(c)) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
JBInsets.removeFrom(r, JBUI.insets(1));
g2.translate(r.x, r.y);
float lw = LW.getFloat();
float arc = COMPONENT_ARC.getFloat();
Object op = comboBox.getClientProperty("JComponent.outline");
if (comboBox.isEnabled() && op != null) {
paintOutlineBorder(g2, r.width, r.height, arc, true, hasFocus, Outline.valueOf(op.toString()));
} else {
if (hasFocus) {
paintOutlineBorder(g2, r.width, r.height, arc, true, true, Outline.focus);
}
Path2D border = new Path2D.Float(Path2D.WIND_EVEN_ODD);
border.append(new RoundRectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2, arc, arc), false);
border.append(new RoundRectangle2D.Float(bw + lw, bw + lw, r.width - (bw + lw) * 2, r.height - (bw + lw) * 2, arc - lw, arc - lw), false);
g2.setColor(getOutlineColor(c.isEnabled(), hasFocus));
g2.fill(border);
}
} else {
paintCellEditorBorder(g2, c, r, hasFocus);
}
} finally {
g2.dispose();
}
}
protected void checkFocus() {
hasFocus = false;
if (!comboBox.isEnabled()) {
hasFocus = false;
return;
}
hasFocus = hasFocus(comboBox);
if (hasFocus) return;
ComboBoxEditor ed = comboBox.getEditor();
if (ed != null) {
hasFocus = hasFocus(ed.getEditorComponent());
}
}
protected static boolean hasFocus(Component c) {
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
return owner != null && SwingUtilities.isDescendingFrom(owner, c);
}
@Override
public Insets getBorderInsets(Component c) {
return DarculaUIUtil.isTableCellEditor(c) ? JBUI.insets(2) : getDefaultComboBoxInsets();
}
@Override
public boolean isBorderOpaque() {
return false;
}
protected Dimension getSizeWithButton(Dimension size, Dimension editorSize) {
Insets i = getInsets();
Dimension abSize = arrowButton.getPreferredSize();
if (abSize == null) {
abSize = JBUI.emptySize();
}
if (isCompact(comboBox) && size != null) {
JBInsets.removeFrom(size, padding); // don't count paddings in compact mode
}
int editorHeight = editorSize != null ? editorSize.height + i.top + i.bottom: 0;
int editorWidth = editorSize != null ? editorSize.width + i.left + padding.left + padding.right : 0;
editorWidth = Math.max(editorWidth, MINIMUM_WIDTH.get() + i.left);
int width = size != null ? size.width : 0;
int height = size != null ? size.height : 0;
width = Math.max(editorWidth + abSize.width, width + padding.left);
height = Math.max(Math.max(editorHeight, Math.max(abSize.height, height)),
(isCompact(comboBox) ? COMPACT_HEIGHT.get() : MINIMUM_HEIGHT.get()) + i.top + i.bottom);
return new Dimension(width, height);
}
@Override
public Dimension getPreferredSize(JComponent c) {
return getSizeWithButton(super.getPreferredSize(c), editor != null ? editor.getPreferredSize() : null);
}
@Override
public Dimension getMinimumSize(JComponent c) {
return getSizeWithButton(super.getMinimumSize(c), editor != null ? editor.getMinimumSize() : null);
}
@Override
protected void configureEditor() {
super.configureEditor();
if (editor instanceof JComponent) {
JComponent jEditor = (JComponent)editor;
jEditor.setOpaque(false);
jEditor.setBorder(JBUI.Borders.empty());
editorFocusListener = new FocusAdapter() {
@Override public void focusGained(FocusEvent e) {
update();
}
@Override public void focusLost(FocusEvent e) {
update();
}
private void update() {
if (comboBox != null) {
comboBox.repaint();
}
}
};
if (editor instanceof JTextComponent) {
editor.addFocusListener(editorFocusListener);
} else {
EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class);
if (etf != null) {
etf.addFocusListener(editorFocusListener);
Color c = UIManager.getColor(comboBox.isEnabled() ? "TextField.background" : "ComboBox.disabledBackground");
etf.setBackground(c);
}
}
}
if (Registry.is("ide.ui.composite.editor.for.combobox")) {
// BasicComboboxUI sets focusability depending on the combobox focusability.
// JPanel usually is unfocusable and uneditable.
// It could be set as an editor when people want to have a composite component as an editor.
// In such cases we should restore unfocusable state for panels.
if (editor instanceof JPanel) {
editor.setFocusable(false);
}
}
}
@Override protected void unconfigureEditor() {
super.unconfigureEditor();
if (editorKeyListener != null) {
editor.removeKeyListener(editorKeyListener);
}
if (editor instanceof JTextComponent) {
if (editorFocusListener != null) {
editor.removeFocusListener(editorFocusListener);
}
} else {
EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class);
if (etf != null) {
if (editorFocusListener != null) {
etf.removeFocusListener(editorFocusListener);
}
}
}
}
@Override
protected LayoutManager createLayoutManager() {
return new ComboBoxLayoutManager() {
@Override
public void layoutContainer(Container parent) {
JComboBox cb = (JComboBox)parent;
if (arrowButton != null) {
Dimension aps = arrowButton.getPreferredSize();
if (cb.getComponentOrientation().isLeftToRight()) {
arrowButton.setBounds(cb.getWidth() - aps.width, 0, aps.width, cb.getHeight());
} else {
arrowButton.setBounds(0, 0, aps.width, cb.getHeight());
}
}
layoutEditor();
}
};
}
protected void layoutEditor() {
if (comboBox.isEditable() && editor != null) {
Rectangle er = rectangleForCurrentValue();
Dimension eps = editor.getPreferredSize();
if (eps.height < er.height) {
int delta = (er.height - eps.height) / 2;
er.y += delta;
}
er.height = eps.height;
editor.setBounds(er);
}
}
@Override
protected Rectangle rectangleForCurrentValue() {
Rectangle rect = super.rectangleForCurrentValue();
JBInsets.removeFrom(rect, padding);
rect.width += comboBox.isEditable() ? 0: padding.right;
return rect;
}
// Wide popup that uses preferred size
protected static class CustomComboPopup extends BasicComboPopup {
public CustomComboPopup(JComboBox combo) {
super(combo);
}
@Override
protected void configurePopup() {
super.configurePopup();
Border border = UIManager.getBorder("ComboPopup.border");
if (border != null) {
setBorder(border);
}
}
@Override
public void updateUI() {
setUI(new BasicPopupMenuUI() {
@Override
public void uninstallDefaults() {}
@Override
public void installDefaults() {
if (popupMenu.getLayout() == null || popupMenu.getLayout() instanceof UIResource)
popupMenu.setLayout(new DefaultMenuLayout(popupMenu, BoxLayout.Y_AXIS));
popupMenu.setOpaque(true);
LookAndFeel.installColorsAndFont(popupMenu, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font");
}
});
}
@Override
public void show(Component invoker, int x, int y) {
if (comboBox instanceof ComboBoxWithWidePopup) {
Dimension popupSize = comboBox.getSize();
int minPopupWidth = ((ComboBoxWithWidePopup)comboBox).getMinimumPopupWidth();
Insets insets = getInsets();
popupSize.width = Math.max(popupSize.width, minPopupWidth);
popupSize.setSize(popupSize.width - (insets.right + insets.left), getPopupHeightForRowCount(comboBox.getMaximumRowCount()));
scroller.setMaximumSize(popupSize);
scroller.setPreferredSize(popupSize);
scroller.setMinimumSize(popupSize);
list.revalidate();
}
super.show(invoker, x, y);
}
}
}
|
package org.chromium.debug.ui.actions;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.chromium.debug.core.model.ConnectedTargetData;
import org.chromium.debug.core.util.ScriptTargetMapping;
import org.chromium.debug.ui.TableUtils;
import org.chromium.debug.ui.TableUtils.ColumnBasedLabelProvider;
import org.chromium.debug.ui.TableUtils.ColumnData;
import org.chromium.debug.ui.TableUtils.ColumnLabelProvider;
import org.chromium.debug.ui.TableUtils.ValueAdapter;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
/**
* A UI control that presents the list of connections with remote V8 VMs. User may choose
* several VMs.
*/
public class ChooseVmControl {
public static Logic create(Composite parent) {
final Table table = new Table(parent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
table.setFont(parent.getFont());
final CheckboxTableViewer tableViewer = new CheckboxTableViewer(table);
table.setHeaderVisible(true);
tableViewer.setContentProvider(new ContentProviderImpl());
ValueAdapter<ScriptTargetMapping, ConnectedTargetData> pairToTargetAdapter =
new ValueAdapter<ScriptTargetMapping, ConnectedTargetData>() {
public ConnectedTargetData convert(ScriptTargetMapping from) {
return from.getConnectedTargetData();
}
};
List<ColumnData<ScriptTargetMapping, ?>> columnDataList =
createLaunchTargetColumns(pairToTargetAdapter);
for (ColumnData<?,?> data : columnDataList) {
data.getLabelProvider().createColumn(table);
}
ValueAdapter<Object, ScriptTargetMapping> rowElementAdapter =
TableUtils.createCastAdapter(ScriptTargetMapping.class);
ColumnBasedLabelProvider<ScriptTargetMapping> labelProvider =
new ColumnBasedLabelProvider<ScriptTargetMapping>(rowElementAdapter, columnDataList);
tableViewer.setLabelProvider(labelProvider);
final List<Logic.Listener> listeners = new ArrayList<Logic.Listener>(1);
tableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
for (Logic.Listener listener : listeners) {
listener.checkStateChanged();
}
}
});
return new Logic() {
public Control getControl() {
return table;
}
public void setData(List<? extends ScriptTargetMapping> targets) {
TableData input = new TableData(targets);
tableViewer.setInput(input);
}
public List<ScriptTargetMapping> getSelected() {
final Object[] array = tableViewer.getCheckedElements();
return new AbstractList<ScriptTargetMapping>() {
@Override
public ScriptTargetMapping get(int index) {
return (ScriptTargetMapping) array[index];
}
@Override
public int size() {
return array.length;
}
};
}
public void selectAll() {
tableViewer.setAllChecked(true);
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
};
}
/**
* A public logic-oriented interface to this control.
*/
public interface Logic {
Control getControl();
void setData(List<? extends ScriptTargetMapping> targets);
List<ScriptTargetMapping> getSelected();
void selectAll();
void addListener(Listener listener);
void removeListener(Listener listener);
interface Listener {
void checkStateChanged();
}
}
/**
* A non-generic class that wraps generic List. Eclipse works in terms of Objects, but you cannot
* safely cast to generic types on runtime (e.g. to List<String>) so we wrap the value before
* passing it into Eclipse.
*/
private static class TableData {
final List<? extends ScriptTargetMapping> targets;
TableData(List<? extends ScriptTargetMapping> targets) {
this.targets = targets;
}
}
private static class ContentProviderImpl implements IStructuredContentProvider {
public Object[] getElements(Object inputElement) {
TableData input = (TableData) inputElement;
return input.targets.toArray();
}
public void dispose() {}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
}
private static class LaunchNameLabelProvider extends ColumnLabelProvider<ConnectedTargetData> {
private Map<ConnectedTargetData, Image> createdImages =
new HashMap<ConnectedTargetData, Image>();
@Override
public Image getColumnImage(ConnectedTargetData connectedTargetData) {
Image result = createdImages.get(connectedTargetData);
if (result == null) {
ImageDescriptor imageDescriptor = DebugUITools.getDefaultImageDescriptor(
connectedTargetData.getDebugTarget().getLaunch().getLaunchConfiguration());
result = imageDescriptor.createImage();
createdImages.put(connectedTargetData, result);
}
return result;
}
@Override
public String getColumnText(ConnectedTargetData connectedTargetData) {
return connectedTargetData.getDebugTarget().getLaunch().getLaunchConfiguration().getName();
}
@Override
public TableColumn createColumn(Table table) {
TableColumn launchCol = new TableColumn(table, SWT.NONE);
launchCol.setText(Messages.ChooseVmControl_LAUNCH);
launchCol.setWidth(200);
return launchCol;
}
@Override
public void dispose() {
for (Image image : createdImages.values()) {
image.dispose();
}
}
}
private static class TargetNameLabelProvider extends ColumnLabelProvider<ConnectedTargetData> {
@Override
public Image getColumnImage(ConnectedTargetData connectedTargetData) {
return null;
}
@Override
public String getColumnText(ConnectedTargetData connectedTargetData) {
return connectedTargetData.getName();
}
@Override
public TableColumn createColumn(Table table) {
TableColumn targetCol = new TableColumn(table, SWT.NONE);
targetCol.setText(Messages.ChooseVmControl_TARGET);
targetCol.setWidth(200);
return targetCol;
}
}
/**
* Returns the list of column providers for launch/target columns that could be used in other
* controls; they only have to provide there row->column value adapter.
*/
public static <R> List<ColumnData<R, ?>> createLaunchTargetColumns(
ValueAdapter<R, ConnectedTargetData> rowValueAdapter) {
List<ColumnData<R, ?>> result = new ArrayList<ColumnData<R, ?>>(2);
result.add(ColumnData.create(rowValueAdapter, new LaunchNameLabelProvider()));
result.add(ColumnData.create(rowValueAdapter, new TargetNameLabelProvider()));
return result;
}
}
|
package org.jboss.reddeer.swt.handler;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.jboss.reddeer.common.logging.Logger;
import org.jboss.reddeer.swt.condition.WaitCondition;
import org.jboss.reddeer.swt.exception.SWTLayerException;
import org.jboss.reddeer.swt.exception.WaitTimeoutExpiredException;
import org.jboss.reddeer.swt.util.Display;
import org.jboss.reddeer.swt.util.ResultRunnable;
import org.jboss.reddeer.swt.wait.TimePeriod;
import org.jboss.reddeer.swt.wait.WaitUntil;
import org.jboss.reddeer.swt.handler.WidgetHandler;
/**
* Contains methods for handling UI operations on {@link TreeItem} widgets.
*
* @author Lucia Jelinkova
*
*/
public class TreeItemHandler {
private static final Logger logger = Logger.getLogger(TreeItemHandler.class);
private static TreeItemHandler instance;
private TreeItemHandler() {
}
/**
* Gets instance of TreeItemHandler.
*
* @return instance of TreeItemHandler
*/
public static TreeItemHandler getInstance() {
if (instance == null) {
instance = new TreeItemHandler();
}
return instance;
}
/**
* Gets text from cell of specified {@link TreeItem} on the position specified by index.
*
* @param treeItem tree item to handle
* @param cellIndex index of cell to get text
* @return text of the cell
*/
public String getText(final TreeItem treeItem, final int cellIndex) {
String text = Display.syncExec(new ResultRunnable<String>() {
@Override
public String run() {
return treeItem.getText(cellIndex);
}
});
return text;
}
/**
* Gets tool tip of specified {@link TreeItem}.
*
* @param item item to handle
* @return tool tip text of specified tree item
*/
public String getToolTipText(final TreeItem item) {
String text = Display.syncExec(new ResultRunnable<String>() {
@Override
public String run() {
return item.getParent().getToolTipText();
}
});
return text;
}
/**
* Finds out whether specified {@link TreeItem} is checked or not.
*
* @param item item to handle
* @return true if specified tree item is expanded, false otherwise
*/
public boolean isExpanded(final TreeItem item) {
return Display.syncExec(new ResultRunnable<Boolean>() {
@Override
public Boolean run() {
return item.getExpanded();
}
});
}
/**
* Sets specified text to column on the position specified
* by index in specified {@link TreeItem}.
*
* @param treeItem tree item to handle
* @param cellIndex index of cell to set text
* @param text text to set
*/
public void setText(final TreeItem treeItem, final int cellIndex, final String text) {
Display.syncExec(new Runnable() {
@Override
public void run() {
treeItem.setText(cellIndex, text);
}
});
}
/**
* Selects specified {@link TreeItem}s in currently focused tree.
* @param treeItems tree items to select
*/
public void selectItems(final TreeItem... selection) {
logger.info("Select tree items: ");
final Tree swtTree = getParent(selection[0]);
TreeHandler.getInstance().setFocus(swtTree);
Display.syncExec(new Runnable() {
public void run() {
if (!(SWT.MULTI == (swtTree.getStyle() & SWT.MULTI))
&& selection.length > 1) {
throw new SWTLayerException("Tree does not support SWT.MULTI, cannot make multiple selections");
}
logger.debug("Set Tree selection");
swtTree.setSelection(selection);
}
});
TreeHandler.getInstance().notifySelect(swtTree);
logger.debug("Selected Tree Items:");
for (TreeItem treeItem : selection) {
logger.debug(" " + WidgetHandler.getInstance().getText(treeItem));
}
}
/**
* See {@link TreeItem#select()}.
*
* @param swtTreeItem tree item to handle
*/
public void select(final TreeItem swtTreeItem) {
Display.syncExec(new Runnable() {
@Override
public void run() {
logger.debug("Selecting tree item: " + swtTreeItem.getText());
swtTreeItem.getParent().setFocus();
swtTreeItem.getParent().setSelection(swtTreeItem);
}
});
logger.debug("Notify tree item "
+ WidgetHandler.getInstance().getText(swtTreeItem)
+ " about selection");
TreeHandler.getInstance().notifyTree(swtTreeItem, TreeHandler.getInstance().createEventForTree(swtTreeItem, SWT.Selection));
logger.info("Selected tree item: " + WidgetHandler.getInstance().getText(swtTreeItem));
}
/**
* See {@link TreeItem#getItem(String)}.
*
* @param swtTreeItem tree item to handle
* @param text text of tree item
* @return child item of specified tree item
*/
public TreeItem getItem(final TreeItem swtTreeItem,
final String text) {
logger.debug("Get child tree item " + text + " of tree item "
+ WidgetHandler.getInstance().getText(swtTreeItem));
expand(swtTreeItem);
TreeItem result = Display.syncExec(new ResultRunnable<TreeItem>() {
@Override
public TreeItem run() {
org.eclipse.swt.widgets.TreeItem[] items = swtTreeItem
.getItems();
boolean isFound = false;
int index = 0;
while (!isFound && index < items.length) {
if (items[index].getText().equals(text)) {
isFound = true;
} else {
index++;
}
}
if (!isFound) {
return null;
} else {
return items[index];
}
}
});
if (result != null) {
return result;
} else {
SWTLayerException exception = new SWTLayerException("Tree Item "
+ this + " has no Tree Item with text " + text);
exception.addMessageDetail("Tree Item " + this
+ " has these direct children:");
for (TreeItem treeItem : TreeHandler.getInstance().getSWTItems(getParent(swtTreeItem))) {
exception.addMessageDetail(" " + getText(treeItem, 0));
}
throw exception;
}
}
/**
* Gets children {@link TreeItem}s of specified {@link org.eclipse.swt.widgets.TreeItem}.
* @param swtTreeItem tree item to handle
* @return tree item children
*/
public List<TreeItem> getChildrenItems( final TreeItem swtTreeItem) {
expand(swtTreeItem, TimePeriod.SHORT);
return Display.syncExec(new ResultRunnable<List<TreeItem>>() {
@Override
public List<TreeItem> run() {
org.eclipse.swt.widgets.TreeItem[] items = swtTreeItem.getItems();
return Arrays.asList(items);
}
});
}
/**
* See {@link TreeItem#getParent()}.
* @param swtTreeItem tree item to handle
* @return parent tree of specified item
*/
public Tree getParent(final TreeItem swtTreeItem) {
return Display.syncExec(new ResultRunnable<Tree>() {
@Override
public Tree run() {
return swtTreeItem.getParent();
}
});
}
/**
* See {@link TreeItem#getPath()}.
*
* @param swtTreeItem tree item to handle
* @return path to specified tree item in tree
*/
public String[] getPath(final TreeItem swtTreeItem) {
return Display.syncExec(new ResultRunnable<String[]>() {
@Override
public String[] run() {
org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem;
LinkedList<String> items = new LinkedList<String>();
while (swttiDummy != null) {
items.addFirst(swttiDummy.getText());
swttiDummy = swttiDummy.getParentItem();
}
return items.toArray(new String[0]);
}
});
}
/**
* See {@link TreeItem#isChecked()}.
* @param swtTreeItem tree item to handle
* @return true if specified item is checked, false otherwise
*/
public boolean isChecked(final org.eclipse.swt.widgets.TreeItem swtTreeItem) {
return Display.syncExec(new ResultRunnable<Boolean>() {
@Override
public Boolean run() {
return swtTreeItem.getChecked();
}
});
}
/**
* See {@link TreeItem#setChecked(boolean)}.
* @param swtTreeItem tree item to handle
* @param check check value of specified tree item
*/
public void setChecked(final TreeItem swtTreeItem,
final boolean check) {
logger.debug((check ? "Check" : "Uncheck") + "Tree Item "
+ WidgetHandler.getInstance().getText(swtTreeItem) + ":");
Display.syncExec(new Runnable() {
@Override
public void run() {
swtTreeItem.setChecked(check);
}
});
logger.debug("Notify tree about check event");
TreeHandler.getInstance().notifyTree(swtTreeItem,
TreeHandler.getInstance().createEventForTree(swtTreeItem, SWT.Selection, SWT.CHECK));
logger.info((check ? "Checked: " : "Unchecked: ") + WidgetHandler.getInstance().getText(swtTreeItem));
}
/**
* See {@link TreeItem#isSelected()}.
*
* @param swtTreeItem tree item to handle
* @return true if specified item is selected, false otherwise
*/
public boolean isSelected(final TreeItem swtTreeItem) {
return Display.syncExec(new ResultRunnable<Boolean>() {
@Override
public Boolean run() {
return Arrays.asList(swtTreeItem.getParent().getSelection())
.contains(swtTreeItem);
}
});
}
/**
* See {@link TreeItem#collapse()}.
* @param swtTreeItem tree item to handle
*/
public void collapse(final TreeItem swtTreeItem) {
logger.debug("Collapse Tree Item "
+ WidgetHandler.getInstance().getText(swtTreeItem));
if (isExpanded(swtTreeItem)) {
Display.syncExec(new Runnable() {
@Override
public void run() {
logger.debug("Setting tree item " + swtTreeItem.getText()
+ " collapsed");
swtTreeItem.setExpanded(false);
}
});
logger.debug("Notify tree about collapse event");
TreeHandler.getInstance().notifyTree(swtTreeItem,
TreeHandler.getInstance().createEventForTree(swtTreeItem, SWT.Collapse));
} else {
logger.debug("Tree Item "
+ WidgetHandler.getInstance().getText(swtTreeItem)
+ " is already collapsed. No action performed");
}
logger.info("Collapsed: " + WidgetHandler.getInstance().getText(swtTreeItem));
}
/**
* See {@link TreeItem#expand}.
* @param swtTreeItem tree item to handle
*/
public void expand(final TreeItem swtTreeItem) {
expand(swtTreeItem, TimePeriod.SHORT);
}
/**
* See {@link TreeItem#expand(TimePeriod)}.
* @param swtTreeItem tree item to handle
* @param timePeriod time period to wait for
*/
public void expand(final TreeItem swtTreeItem, TimePeriod timePeriod) {
logger.debug("Expand Tree Item "
+ WidgetHandler.getInstance().getText(swtTreeItem));
final TreeExpandListener tel = new TreeExpandListener();
Display.syncExec(new Runnable() {
@Override
public void run() {
swtTreeItem.getParent().addListener(SWT.Expand, tel);
}
});
try {
new WaitUntil(new TreeHeardExpandNotification(swtTreeItem, tel,
false), timePeriod);
} catch (WaitTimeoutExpiredException ex) {
new WaitUntil(new TreeHeardExpandNotification(swtTreeItem, tel,
true), timePeriod);
}
logger.info("Expanded: " + WidgetHandler.getInstance().getText(swtTreeItem));
Display.syncExec(new Runnable() {
@Override
public void run() {
swtTreeItem.setExpanded(true);
swtTreeItem.getParent().update();
}
});
}
private class TreeExpandListener implements Listener {
private boolean heard = false;
@Override
public void handleEvent(Event arg0) {
heard = true;
}
public boolean isHeard() {
return heard;
}
}
private class TreeHeardExpandNotification implements WaitCondition {
private org.eclipse.swt.widgets.TreeItem treeItem;
private TreeExpandListener listener;
private boolean sync;
public TreeHeardExpandNotification(
org.eclipse.swt.widgets.TreeItem treeItem,
TreeExpandListener listener, boolean sync) {
this.treeItem = treeItem;
this.listener = listener;
this.sync = sync;
}
@Override
public boolean test() {
if (!isExpanded(treeItem)) {
if (sync) {
TreeHandler.getInstance().notifyTreeSync(treeItem,
TreeHandler.getInstance().createEventForTree(treeItem, SWT.Expand));
} else {
TreeHandler.getInstance().notifyTree(treeItem,
TreeHandler.getInstance().createEventForTree(treeItem, SWT.Expand));
}
return listener.isHeard();
} else {
logger.debug("Tree Item "
+ WidgetHandler.getInstance().getText(treeItem)
+ " is already expanded. No action performed");
}
return true;
}
@Override
public String description() {
return "tree heard expand notification";
}
}
}
|
package p;
abstract class B {
void f(A a) {
<error descr="Cannot access java.util.stream.Stream">a</error>.foo();
}
void f(java.util.List<? extends A> a) {
<error descr="Cannot access java.util.stream.Stream">a.get(0)</error>.foo();
}
}
|
package fr.lteconsulting.pomexplorer.commands;
import fr.lteconsulting.pomexplorer.ApplicationSession;
import fr.lteconsulting.pomexplorer.Client;
import fr.lteconsulting.pomexplorer.DefaultPomFileLoader;
import fr.lteconsulting.pomexplorer.Log;
import fr.lteconsulting.pomexplorer.PomAnalysis;
import fr.lteconsulting.pomexplorer.PomFileLoader;
import fr.lteconsulting.pomexplorer.Tools;
public class AnalyzeCommand
{
@Help( "analyse all the pom files in a directory, recursively" )
public void directory( CommandOptions options, Client client, ApplicationSession session, Log log, String directory )
{
log.html( "Analyzing directory '" + directory + "'...<br/>" );
log.html( "<i>possible options: verbose, nofetch, offline, profiles</i>" );
String[] profiles = null;
if( options.getOption( "profiles" ) != null )
profiles = ((String) options.getOption( "profiles" )).trim().split( "," );
PomFileLoader pomFileLoader = null;
if( !options.hasFlag( "nofetch" ) )
pomFileLoader = new DefaultPomFileLoader( session.session(), !options.hasFlag( "offline" ) );
else
log.html( Tools.logMessage( "<b>nofetch</b> options set, no pom resolution will be attempted" ) );
PomAnalysis.runFullRecursiveAnalysis( directory, session.session(), pomFileLoader, profiles, options.hasFlag( "verbose" ), log );
log.html( "Analyzis completed.<br/>" );
}
}
|
package org.jboss.resteasy.plugins.server.servlet;
/**
* Constant list of bootstrap classes. This is used by JBoss AS to determine whether or not it should scan or not
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ResteasyBootstrapClasses
{
public static String[] BOOTSTRAP_CLASSES = {
HttpServletDispatcher.class.getName(),
ResteasyBootstrap.class.getName(),
"org.springframework.web.servlet.DispatcherServlet",
FilterDispatcher.class.getName(),
"org.jboss.resteasy.plugins.server.servlet.JBossWebDispatcherServlet",
"org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher",
"org.jboss.resteasy.plugins.server.servlet.Tomcat6CometDispatcherServlet"
};
}
|
package net.ontopia.presto.spi.impl.couchdb;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.ontopia.presto.spi.PrestoChangeSet;
import net.ontopia.presto.spi.PrestoField;
import net.ontopia.presto.spi.PrestoSchemaProvider;
import net.ontopia.presto.spi.PrestoTopic;
import net.ontopia.presto.spi.PrestoType;
import net.ontopia.presto.spi.PrestoUpdate;
import org.codehaus.jackson.node.ObjectNode;
import org.ektorp.CouchDbConnector;
import org.ektorp.DocumentOperationResult;
import org.ektorp.UpdateConflictException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CouchChangeSet implements PrestoChangeSet {
private static Logger log = LoggerFactory.getLogger(CouchChangeSet.class.getName());
static interface CouchChange {
enum Type {CREATE, UPDATE, DELETE};
Type getType();
CouchTopic getTopic();
boolean hasUpdate();
}
class CouchDelete implements CouchChange {
private final CouchTopic topic;
private CouchDelete(CouchTopic topic) {
this.topic = topic;
}
@Override
public Type getType() {
return Type.DELETE;
}
@Override
public CouchTopic getTopic() {
return topic;
}
@Override
public boolean hasUpdate() {
return true;
}
}
private final CouchDataProvider dataProvider;
private final Set<PrestoTopic> deleted = new HashSet<PrestoTopic>();
private final Map<PrestoTopic,CouchUpdate> updates = new HashMap<PrestoTopic,CouchUpdate>();
private final List<CouchChange> changes = new ArrayList<CouchChange>();
private boolean saved;
CouchChangeSet(CouchDataProvider dataProvider) {
this.dataProvider = dataProvider;
}
CouchTopic newInstance(PrestoType type) {
return dataProvider.newInstance(type);
}
@Override
public PrestoUpdate createTopic(PrestoType type) {
CouchUpdate update = new CouchUpdate(this, type);
changes.add(update);
return update;
}
@Override
public PrestoUpdate updateTopic(PrestoTopic topic, PrestoType type) {
CouchUpdate update = updates.get(topic);
if (update == null) {
update = new CouchUpdate(this, (CouchTopic)topic, type);
changes.add(update);
updates.put(topic, update);
}
return update;
}
@Override
public void deleteTopic(PrestoTopic topic, PrestoType type) {
deleteTopic(topic, type, true);
}
private void deleteTopic(PrestoTopic topic, PrestoType type, boolean removeDependencies) {
if (deleted.contains(topic)) {
return;
}
changes.add(new CouchDelete((CouchTopic)topic));
deleted.add(topic);
// find and remove dependencies
if (removeDependencies) {
removeDependencies(topic, type);
}
// clear incoming foreign keys
for (PrestoField field : type.getFields()) {
if (field.getInverseFieldId() != null) {
boolean isNew = false;
removeInverseFieldValue(isNew, topic, field, topic.getValues(field));
}
}
}
private void removeDependencies(PrestoTopic topic, PrestoType type) {
PrestoSchemaProvider schemaProvider = type.getSchemaProvider();
for (PrestoTopic dependency : findDependencies(topic, type)) {
if (!dependency.equals(topic)) {
PrestoType dependencyType = schemaProvider.getTypeById(dependency.getTypeId());
deleteTopic(dependency, dependencyType, false);
}
}
}
// dependent topics / cascading deletes
private Collection<PrestoTopic> findDependencies(PrestoTopic topic, PrestoType type) {
Collection<PrestoTopic> dependencies = new HashSet<PrestoTopic>();
findDependencies(topic, type, dependencies);
return dependencies;
}
private void findDependencies(PrestoTopic topic, PrestoType type, Collection<PrestoTopic> dependencies) {
for (PrestoField field : type.getFields()) {
if (field.isReferenceField() && field.isCascadingDelete()) {
PrestoSchemaProvider schemaProvider = type.getSchemaProvider();
for (Object value : topic.getValues(field)) {
PrestoTopic valueTopic = (PrestoTopic)value;
String typeId = valueTopic.getTypeId();
PrestoType valueType = schemaProvider.getTypeById(typeId);
if (valueType.isRemovableCascadingDelete()) {
if (!dependencies.contains(valueTopic)) {
dependencies.add(valueTopic);
findDependencies(valueTopic, valueType, dependencies);
}
}
}
}
}
}
@Override
public void save() {
if (saved) {
log.warn("PrestoChangeSet.save() method called multiple times.");
return; // idempotent
}
this.saved = true;
if (changes.size() == 1) {
CouchChange change = changes.get(0);
if (change.hasUpdate()) {
CouchTopic topic = change.getTopic();
if (change.getType().equals(CouchChange.Type.CREATE)) {
create(topic);
} else if (change.getType().equals(CouchChange.Type.UPDATE)) {
if (!deleted.contains(topic)) {
update(topic);
}
} else if (change.getType().equals(CouchChange.Type.DELETE)) {
delete(topic);
}
}
} else if (changes.size() > 1) {
updateBulk(changes);
}
}
// CouchDB document CRUD operations
protected void create(CouchTopic topic) {
dataProvider.getCouchConnector().create(topic.getData());
log.info("Created: " + topic.getId() + " " + topic.getName());
}
protected void update(CouchTopic topic) {
dataProvider.getCouchConnector().update(topic.getData());
log.info("Updated: " + topic.getId() + " " + topic.getName());
}
protected void updateBulk(List<CouchChange> changes) {
List<ObjectNode> bulkDocuments = new ArrayList<ObjectNode>();
for (CouchChange change : changes) {
if (change.hasUpdate()) {
CouchTopic topic = change.getTopic();
if (change.getType().equals(CouchChange.Type.DELETE)) {
ObjectNode data = topic.getData();
data.put("_deleted", true);
}
log.info("Bulk update document: " + change.getType() + " " + topic.getId());
bulkDocuments.add(topic.getData());
}
}
CouchDbConnector couchConnector = dataProvider.getCouchConnector();
for (DocumentOperationResult dor : couchConnector.executeAllOrNothing(bulkDocuments)) {
log.warn("Bulk update error (probably caused conflict): " + dor);
}
}
protected boolean delete(CouchTopic topic) {
log.info("Removing: " + topic.getId() + " " + topic.getName());
try {
dataProvider.getCouchConnector().delete(topic.getData());
return true;
} catch (UpdateConflictException e) {
CouchTopic topic2 = (CouchTopic)dataProvider.getTopicById(topic.getId());
if (topic2 != null) {
dataProvider.getCouchConnector().delete(topic2.getData());
return true;
} else {
return false;
}
}
}
// inverse fields (foreign keys)
void addInverseFieldValue(boolean isNew, PrestoTopic topic, PrestoField field, Collection<?> values) {
String inverseFieldId = field.getInverseFieldId();
if (inverseFieldId != null) {
for (Object value : values) {
CouchTopic valueTopic = (CouchTopic)value;
if (!topic.equals(valueTopic)) {
PrestoType valueType = field.getSchemaProvider().getTypeById(valueTopic.getTypeId());
PrestoField inverseField = valueType.getFieldById(inverseFieldId);
PrestoUpdate inverseUpdate = updateTopic(valueTopic, valueType);
inverseUpdate.addValues(inverseField, Collections.singleton(topic), CouchDataProvider.DEFAULT_INDEX);
}
}
}
}
void removeInverseFieldValue(boolean isNew, PrestoTopic topic, PrestoField field, Collection<?> values) {
if (!isNew) {
String inverseFieldId = field.getInverseFieldId();
if (inverseFieldId != null) {
for (Object value : values) {
CouchTopic valueTopic = (CouchTopic)value;
if (!topic.equals(valueTopic)) {
PrestoType valueType = field.getSchemaProvider().getTypeById(valueTopic.getTypeId());
if (field.isCascadingDelete() && valueType.isRemovableCascadingDelete()) {
deleteTopic(valueTopic, valueType);
} else {
PrestoField inverseField = valueType.getFieldById(inverseFieldId);
PrestoUpdate inverseUpdate = updateTopic(valueTopic, valueType);
inverseUpdate.removeValues(inverseField, Collections.singleton(topic));
}
}
}
}
}
}
}
|
package org.jboss.resteasy.test.security.smime;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import junit.framework.Assert;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.security.PemUtils;
import org.jboss.resteasy.security.smime.EnvelopedInput;
import org.jboss.resteasy.security.smime.EnvelopedOutput;
import org.jboss.resteasy.security.smime.SignedInput;
import org.jboss.resteasy.security.smime.SignedOutput;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.jboss.resteasy.test.EmbeddedContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* RESTEASY-962
*
* @author <a href="mailto:ron.sigal@jboss.com">Ron Sigal</a>
* @date April 10, 2015
*/
public class VerifyDecryptTest
{
protected static ResteasyDeployment deployment;
protected static Dispatcher dispatcher;
protected static final MediaType MULTIPART_MIXED = new MediaType("multipart", "mixed");
protected static X509Certificate cert;
protected static PrivateKey privateKey;
@Path("/")
public static class TestResource
{
@POST
@Path("encrypt")
public String encrypt(EnvelopedInput<String> input) throws Exception
{
String secret = input.getEntity(privateKey, cert);
System.out.println("secret: " + secret);
return secret;
}
@POST
@Path("sign")
public String sign(SignedInput<String> input) throws Exception
{
if (!input.verify(cert))
{
throw new WebApplicationException(500);
}
String secret = input.getEntity();
System.out.println("secret: " + secret);
return secret;
}
@POST
@Path("encryptSign")
public String encryptSign(SignedInput<EnvelopedInput<String>> input) throws Exception
{
if (!input.verify(cert))
{
throw new WebApplicationException(500);
}
final EnvelopedInput<String> envelop = input.getEntity();
String secret = envelop.getEntity(privateKey, cert);
System.out.println("secret: " + secret);
return secret;
}
@POST
@Path("signEncrypt")
public String signEncrypt(EnvelopedInput<SignedInput<String>> input) throws Exception
{
SignedInput<String> signedInput = input.getEntity(privateKey, cert);
if (!signedInput.verify(cert))
{
throw new WebApplicationException(500);
}
String secret = signedInput.getEntity();
System.out.println("secret: " + secret);
return secret;
}
@Path("encryptedEncrypted")
@POST
public String encryptedEncrypted(EnvelopedInput<EnvelopedInput<String>> input) throws Exception
{
EnvelopedInput<String> envelope = input.getEntity(privateKey, cert);
String secret = envelope.getEntity(privateKey, cert);
System.out.println("secret: " + secret);
return secret;
}
@Path("encryptSignSign")
@POST
public String encryptSignSign(SignedInput<SignedInput<EnvelopedInput<String>>> input) throws Exception
{
if (!input.verify(cert))
{
throw new WebApplicationException(500);
}
SignedInput<EnvelopedInput<String>> inner = input.getEntity();
if (!inner.verify(cert))
{
throw new WebApplicationException(500);
}
final EnvelopedInput<String> envelop = inner.getEntity();
String secret = envelop.getEntity(privateKey, cert);
System.out.println("secret: " + secret);
return secret;
}
@Path("multipartEncrypted")
@POST
public String post(EnvelopedInput<MultipartInput> input) throws Exception
{
MultipartInput multipart = input.getEntity(privateKey, cert);
InputPart inputPart = multipart.getParts().iterator().next();
String secret = inputPart.getBody(String.class, null);
System.out.println("secret: " + secret);
return secret;
}
}
@Before
public void before() throws Exception
{
InputStream certIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("mycert.pem");
cert = PemUtils.decodeCertificate(certIs);
InputStream privateIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("mycert-private.pem");
privateKey = PemUtils.decodePrivateKey(privateIs);
deployment = EmbeddedContainer.start();
dispatcher = deployment.getDispatcher();
deployment.getRegistry().addPerRequestResource(TestResource.class);
}
@After
public void after() throws Exception
{
EmbeddedContainer.stop();
dispatcher = null;
deployment = null;
}
@Test
public void testEncrypt() throws Exception
{
EnvelopedOutput output = new EnvelopedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
output.setCertificate(cert);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/encrypt");
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testSign() throws Exception
{
SignedOutput signed = new SignedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
signed.setPrivateKey(privateKey);
signed.setCertificate(cert);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/sign");
Response res = target.request().post(Entity.entity(signed, "multipart/signed"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testEncryptSign() throws Exception
{
EnvelopedOutput output = new EnvelopedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
output.setCertificate(cert);
SignedOutput signed = new SignedOutput(output, "application/pkcs7-mime");
signed.setCertificate(cert);
signed.setPrivateKey(privateKey);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/encryptSign");
Response res = target.request().post(Entity.entity(signed,"multipart/signed"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testSignEncrypt() throws Exception
{
SignedOutput signed = new SignedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
signed.setPrivateKey(privateKey);
signed.setCertificate(cert);
EnvelopedOutput output = new EnvelopedOutput(signed, "multipart/signed");
output.setCertificate(cert);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/signEncrypt");
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testEncryptedEncrypted()
{
MultipartOutput multipart = new MultipartOutput();
multipart.addPart("xanadu", MediaType.TEXT_PLAIN_TYPE);
EnvelopedOutput innerPart = new EnvelopedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
innerPart.setCertificate(cert);
EnvelopedOutput output = new EnvelopedOutput(innerPart, "application/pkcs7-mime");
output.setCertificate(cert);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/encryptedEncrypted");
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testEncryptSignSign() throws Exception
{
EnvelopedOutput output = new EnvelopedOutput("xanadu", MediaType.TEXT_PLAIN_TYPE);
output.setCertificate(cert);
SignedOutput signed = new SignedOutput(output, "application/pkcs7-mime");
signed.setCertificate(cert);
signed.setPrivateKey(privateKey);
SignedOutput resigned = new SignedOutput(signed, "multipart/signed");
resigned.setCertificate(cert);
resigned.setPrivateKey(privateKey);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/encryptSignSign");
Response res = target.request().post(Entity.entity(resigned,"multipart/signed"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
@Test
public void testMultipartEncrypted()
{
MultipartOutput multipart = new MultipartOutput();
multipart.addPart("xanadu", MediaType.TEXT_PLAIN_TYPE);
EnvelopedOutput output = new EnvelopedOutput(multipart, MULTIPART_MIXED);
output.setCertificate(cert);
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8081/multipartEncrypted");
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
String result = res.readEntity(String.class);
System.out.println("result: " + result);
Assert.assertEquals("xanadu", result);
}
}
|
package org.eclipse.persistence.testing.tests.jpa.delimited;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa.delimited.*;
/**
* Test the EntityManager API using a model that uses delimited-identifiers
*/
public class DelimitedPUTestSuite extends JUnitTestCase {
private static Employee emp = null;
private static Address addr = null;
private static PhoneNumber pn = null;
private static Employee emp2 = null;
private static LargeProject lproj = null;
private static SmallProject sproj = null;
public DelimitedPUTestSuite() {
super();
}
public DelimitedPUTestSuite(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("DelimitedPUTestSuite");
suite.addTest(new DelimitedPUTestSuite("testPopulate"));
suite.addTest(new DelimitedPUTestSuite("testReadEmployee"));
suite.addTest(new DelimitedPUTestSuite("testNativeQuery"));
suite.addTest(new DelimitedPUTestSuite("testUpdateEmployee"));
return suite;
}
public void testPopulate(){
// Temporarily disable testing on MySQL until build scripts can be updated to
if (getServerSession("delimited").getDatasourcePlatform().isMySQL()){
return;
}
EntityManager em = createEntityManager("delimited");
beginTransaction(em);
createEmployee();
createAddress();
createPhoneNumber();
createEmployee2();
createLargeProject();
createSmallProject();
addr.getEmployees().add(emp);
emp.setAddress(addr);
emp.addPhoneNumber(pn);
pn.setOwner(emp);
emp.addManagedEmployee(emp2);
emp2.setManager(emp);
lproj.setTeamLeader(emp);
emp.addProject(lproj);
lproj.addTeamMember(emp2);
emp2.addProject(lproj);
sproj.setTeamLeader(emp2);
emp2.addProject(sproj);
em.persist(emp);
em.persist(addr);
em.persist(pn);
em.persist(emp2);
em.persist(lproj);
em.persist(sproj);
commitTransaction(em);
// refresh phone number
beginTransaction(em);
em.refresh(pn);
commitTransaction(em);
clearCache("delimited");
closeEntityManager(em);
}
public void testReadEmployee() {
// Temporarily disable testing on MySQL until build scripts can be updated to
if (getServerSession("delimited").getDatasourcePlatform().isMySQL()){
return;
}
EntityManager em = createEntityManager("delimited");
Employee returnedEmp = (Employee)em.createQuery("select e from Employee e where e.firstName = 'Del' and e.lastName = 'Imited'").getSingleResult();
Assert.assertTrue("testCreateEmployee emp not properly persisted", getServerSession("delimited").compareObjects(emp, returnedEmp));
Employee returnedWorker = (Employee)em.createQuery("select e from Employee e where e.firstName = 'Art' and e.lastName = 'Vandeleigh'").getSingleResult();
Assert.assertTrue("testCreateEmployee emp2 not properly persisted", getServerSession("delimited").compareObjects(emp2, returnedWorker));
closeEntityManager(em);
}
public void testNativeQuery(){
// Temporarily disable testing on MySQL until build scripts can be updated to
if (getServerSession("delimited").getDatasourcePlatform().isMySQL()){
return;
}
clearCache("delimited");
EntityManager em = createEntityManager("delimited");
List result = em.createNamedQuery("findAllSQLEmployees").getResultList();
Assert.assertTrue("testNativeQuery did not return result ", result.size() == 2);
closeEntityManager(em);
}
public void testUpdateEmployee() {
// Temporarily disable testing on MySQL until build scripts can be updated to
if (getServerSession("delimited").getDatasourcePlatform().isMySQL()){
return;
}
EntityManager em = createEntityManager("delimited");
try {
beginTransaction(em);
Employee returnedEmp = (Employee)em.createQuery("select e from Employee e where e.firstName = 'Del' and e.lastName = 'Imited'").getSingleResult();
returnedEmp.setFirstName("Redel");
PhoneNumber pn = new PhoneNumber();
pn.setType("home");
pn.setAreaCode("123");
returnedEmp.addPhoneNumber(pn);
returnedEmp.getAddress().setCity("Reident");
em.flush();
clearCache("delimited");
returnedEmp = em.find(Employee.class, returnedEmp.getId());
Assert.assertTrue("testUpdateEmployee did not properly update firstName", returnedEmp.getFirstName().equals("Redel"));
Assert.assertTrue("testUpdateEmployee did not properly update address", returnedEmp.getAddress().getCity().equals("Reident"));
Assert.assertTrue("testUpdateEmployee did not properly add phone number", returnedEmp.getPhoneNumbers().size() == 2);;
commitTransaction(em);
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
private static Employee createEmployee(){
emp = new Employee();
emp.setFirstName("Del");
emp.setLastName("Imited");
emp.setFemale();
emp.addResponsibility("Supervise projects");
emp.addResponsibility("Delimit Identifiers");
Date startDate = Date.valueOf("2009-06-01");
Date endDate = Date.valueOf("2009-08-01");
EmploymentPeriod period = new EmploymentPeriod(startDate, endDate);
emp.setPeriod(period);
return emp;
}
private static Employee createEmployee2(){
emp2 = new Employee();
emp2.setFirstName("Art");
emp2.setLastName("Vandeleigh");
emp2.setMale();
return emp2;
}
private static Address createAddress(){
addr = new Address();
addr.setCity("Ident");
addr.setCountry("Ifier");
addr.setPostalCode("A0A1B1");
addr.setProvince("Delimitia");
addr.setStreet("Del St.");
return addr;
}
private static PhoneNumber createPhoneNumber(){
pn = new PhoneNumber();
pn.setAreaCode("709");
pn.setNumber("5551234");
pn.setType("work");
return pn;
}
private static LargeProject createLargeProject(){
lproj = new LargeProject();
lproj.setBudget(10000000);
lproj.setDescription("Allow delimited identifiers in persistence.xml");
lproj.setName("PUDefaults");
return lproj;
}
private static SmallProject createSmallProject(){
sproj = new SmallProject();
sproj.setDescription("Allow delimited identifiers in annotations");
sproj.setName("Annotations");
return sproj;
}
}
|
package torrent;
import org.johnnei.utils.ThreadUtils;
import torrent.download.MagnetLink;
import torrent.frame.TorrentFrame;
public class JavaTorrent extends Thread {
public static final String BUILD = "JavaTorrent 0.01.0 Dev";
private TorrentFrame frame;
public static void main(String[] args) {
System.out.println("Parsing Magnet Link...");
if (args.length == 0) {
System.err.println("Magnet Link not found");
System.exit(1);
}
MagnetLink magnet = new MagnetLink(args[0]);
if (magnet.isDownloadable()) {
magnet.getTorrent().start();
} else {
System.err.println("Magnet link error occured");
}
TorrentFrame frame = new TorrentFrame();
frame.addTorrent(magnet.getTorrent());
new JavaTorrent(frame).start();
}
public JavaTorrent(TorrentFrame frame) {
this.frame = frame;
}
public void run() {
while (true) {
long startTime = System.currentTimeMillis();
frame.updateData();
frame.repaint();
int duration = 1000 - (int)(System.currentTimeMillis() - startTime);
ThreadUtils.sleep(duration);
}
}
}
|
package org.eclipse.persistence.testing.tests.wdf.jpa1.query;
import static javax.persistence.FlushModeType.AUTO;
import static javax.persistence.FlushModeType.COMMIT;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.eclipse.persistence.platform.database.OraclePlatform;
import org.eclipse.persistence.testing.framework.wdf.Bugzilla;
import org.eclipse.persistence.testing.framework.wdf.JPAEnvironment;
import org.eclipse.persistence.testing.framework.wdf.ToBeInvestigated;
import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Department;
import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Project;
import org.eclipse.persistence.testing.models.wdf.jpa1.types.BasicTypesFieldAccess;
import org.eclipse.persistence.testing.tests.wdf.jpa1.JPA1Base;
import org.junit.Test;
@SuppressWarnings("unchecked")
public class TestSimpleQuery extends JPA1Base {
private final Set<Department> ALL_DEPARTMENTS = new HashSet<Department>();
private final Department dep10 = new Department(10, "ten");
private final Department dep20 = new Department(20, "twenty");
private void init() throws SQLException {
clearAllTables();
ALL_DEPARTMENTS.add(dep10);
ALL_DEPARTMENTS.add(dep20);
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
em.persist(dep10);
em.persist(dep20);
env.commitTransactionAndClear(em);
} finally {
closeEntityManager(em);
}
}
@Test
public void testSelectAllDepartments() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d");
List result = query.getResultList();
verify(result.size() == 2, "wrong resultcount");
Iterator iter = result.iterator();
Set<Department> actualSet = new HashSet<Department>();
while (iter.hasNext()) {
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
actualSet.add(entity);
}
verify(ALL_DEPARTMENTS.equals(actualSet), "the sets are somehow different");
} finally {
closeEntityManager(em);
}
}
@Test
public void testSelectDepartmentByName() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d where d.name = ?1");
query.setParameter(1, "twenty");
List result = query.getResultList();
Iterator iter = result.iterator();
verify(iter.hasNext(), "row not found");
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
query = em.createQuery("select distinct d from Department d where d.name = ?1");
query.setParameter(1, "twenty");
result = query.getResultList();
iter = result.iterator();
verify(iter.hasNext(), "row not found");
entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
query = em.createQuery("select d from Department d where d.name like 'twenty'");
result = query.getResultList();
iter = result.iterator();
verify(iter.hasNext(), "row not found");
entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
query = em.createQuery("select d from Department d where d.name like 'twen%'");
result = query.getResultList();
iter = result.iterator();
verify(iter.hasNext(), "row not found");
entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
@Test
public void testSelectInTransaction() throws SQLException {
init();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
Query query = em.createQuery("select d from Department d");
List result = query.getResultList();
verify(result.size() == 2, "wrong resultcount");
Iterator iter = result.iterator();
while (iter.hasNext()) {
Object entity = iter.next();
verify(em.contains(entity), "entity manager doesn't contain result read inside transaction");
}
env.rollbackTransactionAndClear(em);
} finally {
closeEntityManager(em);
}
}
@Test
public void testIntIsNull() throws SQLException {
init();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
Project project = new Project(null);
em.persist(project);
final int projectId = project.getId().intValue();
env.commitTransactionAndClear(em);
Query query = em.createQuery("select p from Project p where p.name IS NULL");
List result = query.getResultList();
verify(result.size() == 1, "wrong resultcount");
Iterator iter = result.iterator();
while (iter.hasNext()) {
project = (Project) iter.next();
verify(project.getId().intValue() == projectId, "wrong project");
}
query = em.createQuery("select distinct p from Project p where p.name IS NULL");
result = query.getResultList();
verify(result.size() == 1, "wrong resultcount");
iter = result.iterator();
while (iter.hasNext()) {
project = (Project) iter.next();
verify(project.getId().intValue() == projectId, "wrong project");
}
} finally {
closeEntityManager(em);
}
}
private void verifyComparisonPrepdicateResult(EntityManager em, String txt, int... ids) {
Query query = em.createQuery(txt);
List result = query.getResultList();
Set<Integer> actual = new HashSet<Integer>();
for (Object object : result) {
BasicTypesFieldAccess fa = (BasicTypesFieldAccess) object;
actual.add(new Integer(fa.getId()));
}
Set<Integer> expected = new HashSet<Integer>();
for (int i : ids) {
expected.add(new Integer(i));
}
verify(expected.equals(actual), "expecetd and actual sets are different for query >>" + txt + "<<");
}
@Test
public void testComparisonPrepdicate() throws SQLException {
init();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
BasicTypesFieldAccess fa = new BasicTypesFieldAccess(17);
fa.setPrimitiveInt(17);
em.persist(fa);
fa = new BasicTypesFieldAccess(18);
fa.setPrimitiveInt(18);
em.persist(fa);
fa = new BasicTypesFieldAccess(19);
fa.setPrimitiveInt(19);
em.persist(fa);
fa = new BasicTypesFieldAccess(20);
fa.setPrimitiveInt(20);
em.persist(fa);
env.commitTransactionAndClear(em);
verifyComparisonPrepdicateResult(em, "Select Object(a) from BasicTypesFieldAccess a where a.primitiveInt = 17", 17);
verifyComparisonPrepdicateResult(em, "Select Object(a) from BasicTypesFieldAccess a where a.primitiveInt > 17", 18,
19, 20);
} finally {
closeEntityManager(em);
}
}
@Test
public void testNamedQuery() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createNamedQuery("getDepartmentByName"); // select d from Department d where d.name = ?1
query.setParameter(1, "twenty");
List result = query.getResultList();
Iterator iter = result.iterator();
verify(iter.hasNext(), "row not found");
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
@Test
@ToBeInvestigated
public void testUndefinedNamedQuery() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
try {
Query query = em.createNamedQuery("Hutzliputz");
query.getResultList();
flop("undefined query created");
} catch (IllegalArgumentException e) {
}
try {
Query query = em.createNamedQuery(null);
query.getResultList();
flop("undefined query created");
} catch (IllegalArgumentException e) {
}
} finally {
closeEntityManager(em);
}
}
@Test
public void testNamedParameter() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "twenty");
List result = query.getResultList();
Iterator iter = result.iterator();
verify(iter.hasNext(), "row not found");
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
@Test
public void testWrongParameter() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
try {
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter(1, "twenty");
query.getResultList();
flop("missing exception");
} catch (RuntimeException e) {
}
} finally {
closeEntityManager(em);
}
}
@Test
public void testCachedQueryWithClear() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
Query query = em.createNamedQuery("getDepartmentCached");
query.setParameter(1, "twenty");
List<Department> result = query.getResultList();
verify(result.size() == 1, "wrong result size");
em.clear();
result = query.getResultList();
verify(result.size() == 1, "wrong result size");
} finally {
closeEntityManager(em);
}
}
@Test
public void testCachedQueryWithoutClear() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
Query query = em.createNamedQuery("getDepartmentCached");
query.setParameter(1, "twenty");
List<Department> result = query.getResultList();
verify(result.size() == 1, "wrong result size");
result = query.getResultList();
verify(result.size() == 1, "wrong result size");
} finally {
closeEntityManager(em);
}
}
@Test
public void testUnCachedQuery() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
Query query = em.createNamedQuery("getDepartmentUnCached");
query.setParameter(1, "twenty");
List<Department> result = query.getResultList();
verify(result.size() == 1, "wrong result size");
result = query.getResultList();
verify(result.size() == 1, "wrong result size");
} finally {
closeEntityManager(em);
}
}
@Test
@ToBeInvestigated
public void testQueryStringNotValid() throws SQLException {
// TODO enable test as soon as functionality is implemented
init();
EntityManager em = getEnvironment().getEntityManager();
try {
boolean caught = false;
Query query;
try {
query = em.createQuery("this is not a valid query");
try {
query.getResultList();
} catch (PersistenceException ex) {
caught = true;
}
} catch (IllegalArgumentException e) {
caught = true;
}
verify(caught,
"illegal query threw neither IllegalArgumentExceptionon create nor PersistenceException on getResultList");
caught = false;
try {
query = em.createQuery((String) null);
try {
query.getResultList();
} catch (PersistenceException ex) {
caught = true;
}
} catch (IllegalArgumentException e) {
caught = true;
}
verify(caught,
"null query threw neither IllegalArgumentExceptionon create nor PersistenceException on getResultList");
} finally {
closeEntityManager(em);
}
}
@Test
public void testExecuteQueryMultipleTimesWithSameParameter() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "twenty");
List result = query.getResultList();
result = query.getResultList();
Iterator iter = result.iterator();
verify(iter.hasNext(), "row not found");
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
@Test
public void testExecuteQueryMultipleTimesWithDifferentParameter() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d where d.name = ?1 and d.id = ?2");
query.setParameter(1, "twenty");
query.setParameter(2, Integer.valueOf(20));
List result = query.getResultList();
Iterator iter = result.iterator();
verify(iter.hasNext(), "row not found");
Department entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
verify(!iter.hasNext(), "too many rows");
query.setParameter(1, "ten");
query.setParameter(2, Integer.valueOf(10));
result = query.getResultList();
iter = result.iterator();
verify(iter.hasNext(), "row not found");
entity = (Department) iter.next();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep10), " got wrong department");
verify(!iter.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
@Test
public void testSingleResultOk() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
boolean extended = getEnvironment().usesExtendedPC();
try {
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "twenty");
Object entity = query.getSingleResult();
if (extended) {
verify(em.contains(entity), "entity manager doesn't contain result read outside transaction");
} else {
verify(!em.contains(entity), "entity manager contains result read outside transaction");
}
verify(entity.equals(dep20), " got wrong department");
} finally {
closeEntityManager(em);
}
}
@Test
public void testNoResult() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "hutzliputz");
try {
query.getSingleResult();
flop("missing NoResultException");
} catch (NoResultException e) {
}
} finally {
closeEntityManager(em);
}
}
@Test
public void testNonUniqueResult() throws SQLException {
init();
EntityManager em = getEnvironment().getEntityManager();
try {
Query query = em.createQuery("select d from Department d");
try {
query.getSingleResult();
flop("missing NonUniqueResultException");
} catch (NonUniqueResultException e) {
}
} finally {
closeEntityManager(em);
}
}
@Test
public void testQueryWithFlush() throws SQLException {
clearAllTables();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
em.persist(dep10);
env.commitTransactionAndClear(em);
env.beginTransaction(em);
Department dep = em.find(Department.class, new Integer(10));
dep.setName("newName");
em.flush();
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "newName");
Department entity = (Department) query.getSingleResult();
verify(entity.getName().equals("newName"), " wrong department name");
env.commitTransactionAndClear(em);
} finally {
closeEntityManager(em);
}
}
private void verifyRowCount(Query query, int maxRows, int startPos, int expected) {
query.setMaxResults(maxRows);
query.setFirstResult(startPos);
assertEquals(query.getMaxResults(), maxRows);
assertEquals(query.getFirstResult(), startPos);
int count = query.getResultList().size();
verify(count == expected, "wrong row count: " + count);
assertEquals(query.getMaxResults(), maxRows);
assertEquals(query.getFirstResult(), startPos);
}
@Test
@Bugzilla(bugid=301274)
public void testMaxResult() throws SQLException {
clearAllTables();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
for (int i = 0; i < 10; i++) {
em.persist(new Project("P" + i));
}
env.commitTransaction(em);
em.clear();
Query query = em.createQuery("select p from Project p");
verifyRowCount(query, 5, 0, 5);
verifyRowCount(query, 10, 0, 10);
verifyRowCount(query, 15, 0, 10);
verifyRowCount(query, 5, 5, 5);
verifyRowCount(query, 10, 5, 5);
verifyRowCount(query, 15, 5, 5);
verifyRowCount(query, 5, 7, 3);
verifyRowCount(query, 10, 7, 3);
verifyRowCount(query, 15, 7, 3);
} finally {
closeEntityManager(em);
}
}
@Test
@Bugzilla(bugid=301274)
public void testMaxResultUnlimited() throws SQLException {
clearAllTables();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
for (int i = 0; i < 10; i++) {
em.persist(new Project("P" + i));
}
env.commitTransaction(em);
em.clear();
Query query = em.createQuery("select p from Project p");
verifyRowCount(query, Integer.MAX_VALUE, 0, 10);
verifyRowCount(query, Integer.MAX_VALUE, 5, 5);
verifyRowCount(query, Integer.MAX_VALUE, 7, 3);
} finally {
closeEntityManager(em);
}
}
@Test
@Bugzilla(bugid=301274)
public void testPagingDefaults() throws SQLException {
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
Query query = em.createQuery("select p from Project p");
assertEquals(0, query.getFirstResult());
assertEquals(Integer.MAX_VALUE, query.getMaxResults());
} finally {
closeEntityManager(em);
}
}
@Test
public void testFlushMode() throws SQLException {
testFlushMode(AUTO, null);
testFlushMode(AUTO, AUTO);
testFlushMode(AUTO, COMMIT);
testFlushMode(COMMIT, null);
testFlushMode(COMMIT, AUTO);
testFlushMode(COMMIT, COMMIT);
}
private void testFlushMode(FlushModeType flushModeEM, FlushModeType flushModeQuery) throws SQLException {
init();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
try {
env.beginTransaction(em);
Query query = em.createQuery("select d from Department d where d.name = 'updated'");
if (flushModeEM == COMMIT) {
em.setFlushMode(COMMIT);
}
verify(em.getFlushMode() == flushModeEM, "wrong flushMode");
if (flushModeQuery != null) {
query.setFlushMode(flushModeQuery);
}
boolean flushExpected = isFlushExpected(flushModeEM, flushModeQuery);
Department dep = em.find(Department.class, Integer.valueOf(10));
dep.setName("updated");
List result = query.getResultList();
if (flushExpected) {
verify(result.size() == 1, "wrong number of rows: " + result.size());
} else {
verify(result.size() == 0, "wrong number of rows: " + result.size());
}
env.commitTransaction(em);
} finally {
closeEntityManager(em);
}
}
private boolean isFlushExpected(FlushModeType flushModeEM, FlushModeType flushModeQuery) {
if (flushModeQuery == null) {
if (flushModeEM == COMMIT) {
return false;
} else {
return true;
}
} else if (flushModeQuery == COMMIT) {
return false;
} else if (flushModeQuery == AUTO) {
return true;
}
throw new IllegalArgumentException("Illegal flushMode(s): flushModeEM = " + flushModeEM + ", flushModeQuery = "
+ flushModeQuery);
}
@Test
public void testTransactionBoundaries() throws SQLException {
init();
JPAEnvironment env = getEnvironment();
EntityManager em = env.getEntityManager();
boolean extended = env.usesExtendedPC();
boolean failureExpected = false;
if (!extended) {
failureExpected = true;
}
try {
// create query outside transaction
Query query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "twenty");
List result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
// execute again
result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
// execute inside transaction
env.beginTransaction(em);
try {
result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
} catch (PersistenceException e) {
if (!failureExpected) {
throw e;
}
}
env.rollbackTransaction(em);
// create query inside transaction
env.beginTransaction(em);
query = em.createQuery("select d from Department d where d.name = :name");
query.setParameter("name", "twenty");
result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
env.commitTransaction(em);
// execute outside transaction
try {
result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
} catch (IllegalStateException e) {
if (!failureExpected) {
throw e;
}
}
// execute inside new transaction
env.beginTransaction(em);
try {
result = query.getResultList();
verify(result.size() == 1, "wrong number of rows: " + result.size());
verify(result.get(0).equals(dep20), "got wrong department");
} catch (IllegalStateException e) {
if (!failureExpected) {
throw e;
}
}
env.rollbackTransaction(em);
} finally {
closeEntityManager(em);
}
}
@Test
public void testBooleanParameter() {
EntityManager em = getEnvironment().getEntityManager();
JPAEnvironment env = getEnvironment();
try {
env.beginTransaction(em);
BasicTypesFieldAccess fieldAccess = new BasicTypesFieldAccess();
fieldAccess.setId(1);
fieldAccess.setPrimitiveBoolean(true);
em.persist(fieldAccess);
fieldAccess = new BasicTypesFieldAccess();
fieldAccess.setId(2);
fieldAccess.setPrimitiveBoolean(false);
em.persist(fieldAccess);
env.commitTransactionAndClear(em);
Query query = em.createQuery("select b from BasicTypesFieldAccess b where b.primitiveBoolean = ?1");
query.setParameter(1, Boolean.TRUE);
List list = query.getResultList();
Iterator iterator = list.iterator();
verify(iterator.hasNext(), "no rows");
BasicTypesFieldAccess value = (BasicTypesFieldAccess) iterator.next();
verify(value.getId() == 1, "wrong id: " + value.getId());
verify(!iterator.hasNext(), "too many rows");
} finally {
closeEntityManager(em);
}
}
}
|
// THIS LIBRARY IS UNTESTED???
public class TreeSet<E> implements Set{
E[] set;
int capacity;
int size;
static int INITIAL_CAPACITY = 16;
static int RESIZE_FACTOR = 2;
public TreeSet() {
set = new E[INITIAL_CAPACITY];
size = 0;
capacity = INITIAL_CAPACITY;
}
private void resize() {
int new_size = capacity * RESIZE_FACTOR;
E[] new_set = new E[new_size];
for (int i=0; i<capacity; i++) {
new_set[i] = set[i];
}
set = new_set;
capacity = capacity * RESIZE_FACTOR;
}
private void check_size() {
if (size >= capacity) {
resize();
}
}
public boolean add(E e) {
if (contains(e) || e == null) {
return false;
} else {
set[size] = e;
size ++;
check_size();
return true;
}
}
private int get_Index(Object o) {
for (int i=0; i<size; i++) {
if (o.equals(set[i])) {
return i;
}
}
return -1;
}
public boolean contains(Object o) {
return get_Index(o) >= 0;
}
public boolean remove(Object o) {
int index = get_Index(o);
if (index >= 0) {
for (int j=index; j<size-1; j++) {
set[j] = set[j+1];
}
set[size-1] = null;
size
return true;
} else {
return false;
}
}
public void clear() {
set = new E[INITIAL_CAPACITY];
size = 0;
capacity = INITIAL_CAPACITY;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public E last()
{
if (!isEmpty())
return set[size - 1];
else
return null;
}
}
|
package org.languagetool.tokenizers.de;
import com.google.common.base.Suppliers;
import de.danielnaber.jwordsplitter.EmbeddedGermanDictionary;
import de.danielnaber.jwordsplitter.GermanWordSplitter;
import de.danielnaber.jwordsplitter.InputTooLongException;
import gnu.trove.THashSet;
import org.languagetool.tokenizers.Tokenizer;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static java.util.Arrays.asList;
/**
* Split German nouns using the jWordSplitter library.
*
* @author Daniel Naber
*/
public class GermanCompoundTokenizer implements Tokenizer {
private static final Supplier<GermanCompoundTokenizer> strictInstance = Suppliers.memoize(() -> {
try {
return new GermanCompoundTokenizer(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
private static final Supplier<GermanCompoundTokenizer> nonStrictInstance = Suppliers.memoize(() -> {
try {
return new GermanCompoundTokenizer(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
private final ExtendedGermanWordSplitter wordSplitter;
public GermanCompoundTokenizer() throws IOException {
this(true);
}
static class ExtendedGermanWordSplitter extends GermanWordSplitter {
ExtendedGermanWordSplitter(boolean hideInterfixCharacters) throws IOException {
super(hideInterfixCharacters, extendedList());
}
static Set<String> extendedList() {
THashSet<String> words = new THashSet<>(EmbeddedGermanDictionary.getWords());
// add compound parts here so we don't need to update JWordSplitter for every missing word we find:
words.add("synonym");
words.trimToSize();
return words;
}
}
public GermanCompoundTokenizer(boolean strictMode) throws IOException {
wordSplitter = new ExtendedGermanWordSplitter(false);
// add exceptions here so we don't need to update JWordSplitter for every exception we find:
//wordSplitter.addException("Maskerade", Collections.singletonList("Maskerade"));
//wordSplitter.addException("Sportshorts", asList("Sport", "shorts"));
wordSplitter.addException("Hallesche", asList("Hallesche"));
wordSplitter.addException("Halleschen", asList("Halleschen"));
wordSplitter.addException("Reinigungstab", asList("Reinigungs", "tab"));
wordSplitter.addException("Reinigungstabs", asList("Reinigungs", "tabs"));
wordSplitter.addException("Tauschwerte", asList("Tausch", "werte"));
wordSplitter.addException("Tauschwertes", asList("Tausch", "wertes"));
wordSplitter.addException("Kinderspielen", asList("Kinder", "spielen"));
wordSplitter.addException("Buchhaltungstrick", asList("Buchhaltungs", "trick"));
wordSplitter.addException("Buchhaltungstricks", asList("Buchhaltungs", "tricks"));
wordSplitter.addException("Verkaufstrick", asList("Verkaufs", "trick"));
wordSplitter.addException("Verkaufstricks", asList("Verkaufs", "tricks"));
wordSplitter.addException("Ablenkungstrick", asList("Ablenkungs", "trick"));
wordSplitter.addException("Ablenkungstricks", asList("Ablenkungs", "tricks"));
wordSplitter.addException("Manipulationstrick", asList("Manipulations", "trick"));
wordSplitter.addException("Manipulationstricks", asList("Manipulations", "tricks"));
wordSplitter.addException("Erziehungstrick", asList("Erziehungs", "trick"));
wordSplitter.addException("Erziehungstricks", asList("Erziehungs", "tricks"));
wordSplitter.addException("karamelligen", asList("karamelligen")); // != Karamel+Ligen
wordSplitter.setStrictMode(strictMode);
wordSplitter.setMinimumWordLength(3);
}
@Override
public List<String> tokenize(String word) {
try {
return wordSplitter.splitWord(word);
} catch (InputTooLongException e) {
return Collections.singletonList(word);
}
}
public static GermanCompoundTokenizer getStrictInstance() {
return strictInstance.get();
}
public static GermanCompoundTokenizer getNonStrictInstance() {
return nonStrictInstance.get();
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: " + GermanCompoundTokenizer.class.getSimpleName() + " <wordsToSplit... or file>");
System.exit(1);
}
GermanCompoundTokenizer tokenizer = new GermanCompoundTokenizer();
if (new File(args[0]).exists()) {
System.out.println("Working on lines from " + args[0] + ":");
List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
System.out.println(tokenizer.tokenize(line));
}
} else {
for (String arg : args) {
System.out.println(tokenizer.tokenize(arg));
}
}
}
}
|
package org.broadinstitute.sting.gatk.walkers.genotyper;
import org.broadinstitute.sting.utils.BaseUtils;
public enum DiploidGenotype {
AA ('A', 'A'),
AC ('A', 'C'),
AG ('A', 'G'),
AT ('A', 'T'),
CC ('C', 'C'),
CG ('C', 'G'),
CT ('C', 'T'),
GG ('G', 'G'),
GT ('G', 'T'),
TT ('T', 'T');
public byte base1, base2;
@Deprecated
private DiploidGenotype(char base1, char base2) {
this((byte)base1, (byte)base2);
}
private DiploidGenotype(byte base1, byte base2) {
this.base1 = base1;
this.base2 = base2;
}
public boolean isHomRef(byte r) {
return isHom() && r == base1;
}
public boolean isHomVar(byte r) {
return isHom() && r != base1;
}
public boolean isHetRef(byte r) {
if ( base1 == r )
return r != base2;
else
return base2 == r;
//return MathUtils.countOccurrences(r, this.toString()) == 1;
}
public boolean isHom() {
return ! isHet();
}
public boolean isHet() {
return base1 != base2;
}
/**
* create a diploid genotype, given a character to make into a hom genotype
* @param hom the character to turn into a hom genotype, i.e. if it is A, then returned will be AA
* @return the diploid genotype
*/
public static DiploidGenotype createHomGenotype(byte hom) {
int index = BaseUtils.simpleBaseToBaseIndex(hom);
if ( index == -1 )
throw new IllegalArgumentException(hom + " is not a valid base character");
return conversionMatrix[index][index];
}
/**
* create a diploid genotype, given 2 chars which may not necessarily be ordered correctly
* @param base1 base1
* @param base2 base2
* @return the diploid genotype
*/
public static DiploidGenotype createDiploidGenotype(byte base1, byte base2) {
int index1 = BaseUtils.simpleBaseToBaseIndex(base1);
if ( index1 == -1 )
throw new IllegalArgumentException(base1 + " is not a valid base character");
int index2 = BaseUtils.simpleBaseToBaseIndex(base2);
if ( index2 == -1 )
throw new IllegalArgumentException(base2 + " is not a valid base character");
return conversionMatrix[index1][index2];
}
private static final DiploidGenotype[][] conversionMatrix = {
{ DiploidGenotype.AA, DiploidGenotype.AC, DiploidGenotype.AG, DiploidGenotype.AT },
{ DiploidGenotype.AC, DiploidGenotype.CC, DiploidGenotype.CG, DiploidGenotype.CT },
{ DiploidGenotype.AG, DiploidGenotype.CG, DiploidGenotype.GG, DiploidGenotype.GT },
{ DiploidGenotype.AT, DiploidGenotype.CT, DiploidGenotype.GT, DiploidGenotype.TT }
};
}
|
package mmsort;
import java.util.Comparator;
public class Simple_ManyPivotSort implements ISortAlgorithm {
protected static final int PIVOTS_SIZE = 127; // 2 - 1
protected static final int SWITCH_SIZE = 3000; // Quick Sort (Median of 3)
/**
* Many pivot sort
*
*
*
* internal method (Added argument the pivot array)
*
*
* @param array sort target /
* @param from index of first element /
* @param to index of last element (exclusive) / + 1
* @param pivots array of pivot /
* @param fromPivots from index of pivots / pivots
* @param toPivots to index of pivots (last element of exclusive) / pivots + 1
* @param comparator comparator of array element /
*/
protected static final <T> void mpSort(final T[] array, final int from, final int to, final T[] pivots, final int fromPivots, final int toPivots, final Comparator<? super T> comparator)
{
final int pivotIdx = fromPivots + (toPivots - fromPivots) / 2; // using index from pivots (center position) / pivots
final T pivot = pivots[pivotIdx]; // pivot value /
int curFrom = from; // min index /
int curTo = to - 1; // max index /
while (true) {
while (comparator.compare(array[curFrom], pivot) < 0)
curFrom++;
while (comparator.compare(pivot, array[curTo]) < 0)
curTo
if (curTo < curFrom)
break;
final T work = array[curFrom];
array[curFrom] = array[curTo];
array[curTo] = work;
curFrom++;
curTo
}
if (from < curTo) {
if (fromPivots >= pivotIdx - 3) // pivotspivots
mpSort(array, from, curTo + 1, comparator);
else
mpSort(array, from, curTo + 1, pivots, fromPivots, pivotIdx, comparator);
}
if (curFrom < to - 1) {
if (pivotIdx + 1 >= toPivots - 3) // pivotspivots
mpSort(array, curFrom, to, comparator);
else
mpSort(array, curFrom, to, pivots, pivotIdx + 1, toPivots, comparator);
}
}
/**
* Many pivot sort
*
*
* @param array sort target /
* @param from index of first element /
* @param to index of last element (exclusive) / + 1
* @param comparator comparator of array element /
*/
public static final <T> void mpSort(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
final int range = to - from; // sort range /
if (range < SWITCH_SIZE) {
QuickSortM3.quickSortMedian3(array, from, to, comparator);
return;
}
int pivotsSize = PIVOTS_SIZE;
/*
if (range >= 1000000)
pivotsSize = 2048 - 1;
else if (range >= 500000)
pivotsSize = 1024 - 1;
else if (range >= 250000)
pivotsSize = 512 - 1;
else if (range >= 120000)
pivotsSize = 256 - 1;
else if (range >= 60000)
pivotsSize = 128 - 1;
else if (range >= 30000)
pivotsSize = 64 - 1;
else
pivotsSize = 32 - 1;
*/
@SuppressWarnings("unchecked")
final T[] pivots = (T[])new Object[pivotsSize]; // pivot candidates /
for (int i = 0; i < pivots.length; i++) {
pivots[i] = array[(int)(from + (long)range * i / pivots.length + range / 2 / pivots.length)];
}
// sort of pivot candidates /
BinInsertionSort.binInsertionSort(pivots, 0, pivots.length, comparator);
// sort of array /
mpSort(array, from, to, pivots, 0, pivots.length, comparator);
}
@Override
public <T> void sort(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
mpSort(array, from, to, comparator);
}
@Override
public boolean isStable()
{
return false;
}
@Override
public String getName()
{
return "Many Pivot Sort (Simple implementation)";
}
}
|
package model;
public class TransposedMatrixValue extends MatrixValue{
private Value<?> m;
public TransposedMatrixValue(Value<?> m, int line) {
super(line);
this.m = m;
}
@Override
public Matrix value() {
Value<?> v = (m instanceof Variable ? ((Variable) m).value() : m);
if (v instanceof MatrixValue){
Matrix mat = ((MatrixValue) v).value();
return mat.transposed();
} else {
//TT_INVALID
return null;
}
}
}
|
package io.spine.server.storage.jdbc.record;
import com.google.common.base.Optional;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Message;
import io.spine.client.ColumnFilter;
import io.spine.client.CompositeColumnFilter;
import io.spine.client.EntityFilters;
import io.spine.server.entity.Entity;
import io.spine.server.entity.EntityRecord;
import io.spine.server.entity.storage.ColumnTypeRegistry;
import io.spine.server.entity.storage.EntityQueries;
import io.spine.server.entity.storage.EntityQuery;
import io.spine.server.entity.storage.EntityRecordWithColumns;
import io.spine.server.storage.RecordStorage;
import io.spine.server.storage.RecordStorageShould;
import io.spine.server.storage.jdbc.DataSourceWrapper;
import io.spine.server.storage.jdbc.GivenDataSource;
import io.spine.server.storage.jdbc.record.given.JdbcRecordStorageTestEnv;
import io.spine.server.storage.jdbc.record.given.JdbcRecordStorageTestEnv.TestCounterEntityJdbc;
import io.spine.server.storage.jdbc.record.given.JdbcRecordStorageTestEnv.TestEntityWithStringId;
import io.spine.server.storage.jdbc.type.JdbcColumnType;
import io.spine.server.storage.jdbc.type.JdbcTypeRegistryFactory;
import io.spine.test.storage.Project;
import io.spine.test.storage.ProjectId;
import io.spine.testdata.Sample;
import org.junit.Test;
import static io.spine.Identifier.newUuid;
import static io.spine.client.ColumnFilters.gt;
import static io.spine.client.ColumnFilters.lt;
import static io.spine.client.CompositeColumnFilter.CompositeOperator.ALL;
import static io.spine.server.storage.jdbc.PredefinedMapping.MYSQL_5_7;
import static io.spine.test.Tests.nullRef;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author Alexander Litus
*/
public class JdbcRecordStorageShould
extends RecordStorageShould<String, JdbcRecordStorage<String>> {
@Test
public void clear_itself() {
final JdbcRecordStorage<String> storage = getStorage();
final String id = newUuid();
final EntityRecord entityRecord = newStorageRecord();
final EntityRecordWithColumns record = EntityRecordWithColumns.of(entityRecord);
storage.writeRecord(id, record);
storage.clear();
final Optional<EntityRecord> actual = storage.readRecord(id);
assertNotNull(actual);
assertFalse(actual.isPresent());
close(storage);
}
@Test(expected = IllegalStateException.class)
public void throw_exception_when_closing_twice() throws Exception {
final RecordStorage<?> storage = getStorage();
storage.close();
storage.close();
}
@Test
public void use_column_names_for_storing() {
final JdbcRecordStorage<String> storage = newStorage(TestEntityWithStringId.class);
final int entityColumnIndex = RecordTable.StandardColumn.values().length;
final String customColumnName = storage.getTable()
.getTableColumns()
.get(entityColumnIndex)
.name();
assertEquals(JdbcRecordStorageTestEnv.COLUMN_NAME_FOR_STORING, customColumnName);
close(storage);
}
@Test
public void read_by_composite_filter_with_column_filters_for_same_column() {
final JdbcRecordStorage<String> storage = newStorage(TestEntityWithStringId.class);
final String columnName = "value";
final ColumnFilter lessThan = lt(columnName, -5);
final ColumnFilter greaterThan = gt(columnName, 5);
final CompositeColumnFilter columnFilter = CompositeColumnFilter.newBuilder()
.addFilter(lessThan)
.addFilter(greaterThan)
.setOperator(ALL)
.build();
final EntityFilters entityFilters = EntityFilters.newBuilder()
.addFilter(columnFilter)
.build();
final EntityQuery<String> query = EntityQueries.from(entityFilters, storage.getEntityColumnCache());
storage.readAll(query, FieldMask.getDefaultInstance());
close(storage);
}
@Test(expected = NullPointerException.class)
public void require_non_null_entity_class() {
final Class<? extends Entity<Object, ?>> nullEntityCls = nullRef();
JdbcRecordStorage.newBuilder()
.setEntityClass(nullEntityCls);
}
@Test(expected = NullPointerException.class)
public void require_non_null_column_type_registry() {
final ColumnTypeRegistry<? extends JdbcColumnType<? super Object, ? super Object>> registry
= nullRef();
JdbcRecordStorage.newBuilder()
.setColumnTypeRegistry(registry);
}
@Override
protected JdbcRecordStorage<String> newStorage(Class<? extends Entity> cls) {
final DataSourceWrapper dataSource = GivenDataSource.whichIsStoredInMemory(
"entityStorageTests");
@SuppressWarnings("unchecked") // Test invariant.
final Class<? extends Entity<String, ?>> entityClass =
(Class<? extends Entity<String, ?>>) cls;
final JdbcRecordStorage<String> storage =
JdbcRecordStorage.<String>newBuilder()
.setDataSource(dataSource)
.setEntityClass(entityClass)
.setMultitenant(false)
.setColumnTypeRegistry(JdbcTypeRegistryFactory.defaultInstance())
.setTypeMapping(MYSQL_5_7)
.build();
return storage;
}
@Override
protected String newId() {
return newUuid();
}
@Override
protected Message newState(String id) {
final Project.Builder builder = Sample.builderForType(Project.class);
builder.setId(ProjectId.newBuilder()
.setId(id));
return builder.build();
}
@Override
protected Class<? extends TestCounterEntity> getTestEntityClass() {
return TestCounterEntityJdbc.class;
}
}
|
package net.sandius.rembulan.compiler.gen;
import net.sandius.rembulan.lbc.Prototype;
import net.sandius.rembulan.util.Check;
import net.sandius.rembulan.util.IntVector;
public class PrototypePath {
private final IntVector indices;
private PrototypePath(IntVector indices) {
this.indices = Check.notNull(indices);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PrototypePath that = (PrototypePath) o;
return this.indices.equals(that.indices);
}
@Override
public int hashCode() {
return indices.hashCode();
}
private final static PrototypePath ROOT = new PrototypePath(IntVector.EMPTY);
public static PrototypePath root() {
return ROOT;
}
public static PrototypePath fromIndices(IntVector indices) {
Check.notNull(indices);
return indices.isEmpty() ? root() : new PrototypePath(indices);
}
@Override
public String toString() {
return "/" + indices.toString("/");
}
public IntVector indices() {
return indices;
}
public boolean isRoot() {
return indices.isEmpty();
}
public PrototypePath child(int index) {
Check.nonNegative(index);
int[] newIndices = new int[indices.length() + 1];
indices.copyToArray(newIndices, 0);
newIndices[indices.length()] = index;
return new PrototypePath(IntVector.wrap(newIndices));
}
public Prototype resolve(Prototype root) {
Prototype p = Check.notNull(root);
for (int i = 0; i < indices.length(); i++) {
p = p.getNestedPrototypes().get(indices.get(i));
}
return p;
}
}
|
package com.alibaba.rocketmq.example.concurrent;
import com.alibaba.rocketmq.client.log.ClientLogger;
import com.alibaba.rocketmq.client.producer.concurrent.MultiThreadMQProducer;
import com.alibaba.rocketmq.common.ThreadFactoryImpl;
import com.alibaba.rocketmq.common.message.Message;
import org.slf4j.Logger;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class Producer {
private static final AtomicLong SEQUENCE_GENERATOR = new AtomicLong(0L);
private static final Random RANDOM = new Random();
private static final Logger LOGGER = ClientLogger.getLog();
private static byte[] messageBody = new byte[1024];
static {
Arrays.fill(messageBody, (byte) 'x');
}
public static void main(String[] args) {
int count = 0;
if (args.length > 0) {
count = Integer.parseInt(args[0]);
} else {
count = -1;
}
final AtomicLong successCount = new AtomicLong(0L);
final AtomicLong lastSent = new AtomicLong(0L);
final MultiThreadMQProducer producer = MultiThreadMQProducer.configure()
.configureProducerGroup("PG_QuickStart")
.configureRetryTimesBeforeSendingFailureClaimed(3)
.configureSendMessageTimeOutInMilliSeconds(3000)
.configureDefaultTopicQueueNumber(16)
.build();
producer.registerCallback(new ExampleSendCallback(successCount));
Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("TPSService"))
.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long currentSuccessSent = successCount.longValue();
LOGGER.info("TPS: " + (currentSuccessSent - lastSent.longValue()) +
". Semaphore available number:" + producer.getSemaphore().availablePermits());
lastSent.set(currentSuccessSent);
}
}, 0, 1, TimeUnit.SECONDS);
if (count < 0) {
final AtomicLong adder = new AtomicLong(0L);
Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("MessageManufactureService"))
.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
Message[] messages = buildMessages(RANDOM.nextInt(4));
producer.send(messages);
adder.incrementAndGet();
if (adder.longValue() % 10 == 0) {
LOGGER.info(messages.length + " messages from client are required to send.");
}
} catch (Exception e) {
LOGGER.error("Message manufacture caught an exception.", e);
}
}
}, 3000, 100, TimeUnit.MILLISECONDS);
} else {
long start = System.currentTimeMillis();
Message[] messages = buildMessages(count);
producer.send(messages);
LOGGER.info("Messages are sent in async manner. Cost " + (System.currentTimeMillis() - start) + "ms");
}
}
public static Message[] buildMessages(int n) {
Message[] messages = new Message[n];
for (int i = 0; i < n; i++) {
messages[i] = new Message("T_QuickStart", messageBody);
messages[i].putUserProperty("sequenceId", String.valueOf(SEQUENCE_GENERATOR.incrementAndGet()));
}
return messages;
}
}
|
package net.runelite.client.plugins.agility;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Provides;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.inject.Inject;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Item;
import net.runelite.api.ItemID;
import static net.runelite.api.ItemID.AGILITY_ARENA_TICKET;
import net.runelite.api.Player;
import static net.runelite.api.Skill.AGILITY;
import net.runelite.api.Tile;
import net.runelite.api.TileObject;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.DecorativeObjectChanged;
import net.runelite.api.events.DecorativeObjectDespawned;
import net.runelite.api.events.DecorativeObjectSpawned;
import net.runelite.api.events.ExperienceChanged;
import net.runelite.api.events.GameObjectChanged;
import net.runelite.api.events.GameObjectDespawned;
import net.runelite.api.events.GameObjectSpawned;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.GroundObjectChanged;
import net.runelite.api.events.GroundObjectDespawned;
import net.runelite.api.events.GroundObjectSpawned;
import net.runelite.api.events.ItemDespawned;
import net.runelite.api.events.ItemSpawned;
import net.runelite.api.events.WallObjectChanged;
import net.runelite.api.events.WallObjectDespawned;
import net.runelite.api.events.WallObjectSpawned;
import net.runelite.client.Notifier;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.game.ItemManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.ui.overlay.infobox.InfoBoxManager;
@PluginDescriptor(
name = "Agility",
description = "Show helpful information about agility courses and obstacles",
tags = {"grace", "marks", "overlay", "shortcuts", "skilling", "traps"}
)
@Slf4j
public class AgilityPlugin extends Plugin
{
private static final int AGILITY_ARENA_REGION_ID = 11157;
@Getter
private final Map<TileObject, Tile> obstacles = new HashMap<>();
@Getter
private Tile markOfGrace;
@Inject
private OverlayManager overlayManager;
@Inject
private AgilityOverlay agilityOverlay;
@Inject
private LapCounterOverlay lapCounterOverlay;
@Inject
private Notifier notifier;
@Inject
private Client client;
@Inject
private InfoBoxManager infoBoxManager;
@Inject
private AgilityConfig config;
@Inject
private ItemManager itemManager;
@Getter
private AgilitySession session;
private int lastAgilityXp;
private WorldPoint lastArenaTicketPosition;
@Provides
AgilityConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(AgilityConfig.class);
}
@Override
protected void startUp() throws Exception
{
overlayManager.add(agilityOverlay);
overlayManager.add(lapCounterOverlay);
}
@Override
protected void shutDown() throws Exception
{
overlayManager.remove(agilityOverlay);
overlayManager.remove(lapCounterOverlay);
markOfGrace = null;
obstacles.clear();
session = null;
}
@Subscribe
public void onGameStateChange(GameStateChanged event)
{
switch (event.getGameState())
{
case HOPPING:
case LOGIN_SCREEN:
session = null;
lastArenaTicketPosition = null;
removeAgilityArenaTimer();
break;
case LOADING:
markOfGrace = null;
obstacles.clear();
break;
case LOGGED_IN:
if (!isInAgilityArena())
{
lastArenaTicketPosition = null;
removeAgilityArenaTimer();
}
break;
}
}
@Subscribe
public void onConfigChanged(ConfigChanged event)
{
if (!config.showAgilityArenaTimer())
{
removeAgilityArenaTimer();
}
}
@Subscribe
public void onExperienceChanged(ExperienceChanged event)
{
if (event.getSkill() != AGILITY || !config.showLapCount())
{
return;
}
// Determine how much EXP was actually gained
int agilityXp = client.getSkillExperience(AGILITY);
int skillGained = agilityXp - lastAgilityXp;
lastAgilityXp = agilityXp;
// Get course
Courses course = Courses.getCourse(client.getLocalPlayer().getWorldLocation().getRegionID());
if (course == null
|| (course.getCourseEndWorldPoints().length == 0
? Math.abs(course.getLastObstacleXp() - skillGained) > 1
: Arrays.stream(course.getCourseEndWorldPoints()).noneMatch(wp -> wp.equals(client.getLocalPlayer().getWorldLocation()))))
{
return;
}
if (session != null && session.getCourse() == course)
{
session.incrementLapCount(client);
}
else
{
session = new AgilitySession(course);
// New course found, reset lap count and set new course
session.resetLapCount();
session.incrementLapCount(client);
}
}
@Subscribe
public void onItemSpawned(ItemSpawned itemSpawned)
{
if (obstacles.isEmpty())
{
return;
}
final Item item = itemSpawned.getItem();
final Tile tile = itemSpawned.getTile();
if (item.getId() == ItemID.MARK_OF_GRACE)
{
markOfGrace = tile;
}
}
@Subscribe
public void onItemDespawned(ItemDespawned itemDespawned)
{
final Item item = itemDespawned.getItem();
if (item.getId() == ItemID.MARK_OF_GRACE)
{
markOfGrace = null;
}
}
@Subscribe
public void onGameTick(GameTick tick)
{
if (isInAgilityArena())
{
// Hint arrow has no plane, and always returns the current plane
WorldPoint newTicketPosition = client.getHintArrowPoint();
WorldPoint oldTickPosition = lastArenaTicketPosition;
lastArenaTicketPosition = newTicketPosition;
if (oldTickPosition != null && newTicketPosition != null
&& (oldTickPosition.getX() != newTicketPosition.getX() || oldTickPosition.getY() != newTicketPosition.getY()))
{
log.debug("Ticked position moved from {} to {}", oldTickPosition, newTicketPosition);
if (config.notifyAgilityArena())
{
notifier.notify("Ticket location changed");
}
if (config.showAgilityArenaTimer())
{
showNewAgilityArenaTimer();
}
}
}
}
private boolean isInAgilityArena()
{
Player local = client.getLocalPlayer();
if (local == null)
{
return false;
}
WorldPoint location = local.getWorldLocation();
return location.getRegionID() == AGILITY_ARENA_REGION_ID;
}
private void removeAgilityArenaTimer()
{
infoBoxManager.removeIf(infoBox -> infoBox instanceof AgilityArenaTimer);
}
private void showNewAgilityArenaTimer()
{
removeAgilityArenaTimer();
infoBoxManager.addInfoBox(new AgilityArenaTimer(this, itemManager.getImage(AGILITY_ARENA_TICKET)));
}
@Subscribe
public void onGameObjectSpawned(GameObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getGameObject());
}
@Subscribe
public void onGameObjectChanged(GameObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getGameObject());
}
@Subscribe
public void onGameObjectDeSpawned(GameObjectDespawned event)
{
onTileObject(event.getTile(), event.getGameObject(), null);
}
@Subscribe
public void onGroundObjectSpawned(GroundObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getGroundObject());
}
@Subscribe
public void onGroundObjectChanged(GroundObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getGroundObject());
}
@Subscribe
public void onGroundObjectDeSpawned(GroundObjectDespawned event)
{
onTileObject(event.getTile(), event.getGroundObject(), null);
}
@Subscribe
public void onWallObjectSpawned(WallObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getWallObject());
}
@Subscribe
public void onWallObjectChanged(WallObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getWallObject());
}
@Subscribe
public void onWallObjectDeSpawned(WallObjectDespawned event)
{
onTileObject(event.getTile(), event.getWallObject(), null);
}
@Subscribe
public void onDecorativeObjectSpawned(DecorativeObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getDecorativeObject());
}
@Subscribe
public void onDecorativeObjectChanged(DecorativeObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getDecorativeObject());
}
@Subscribe
public void onDecorativeObjectDeSpawned(DecorativeObjectDespawned event)
{
onTileObject(event.getTile(), event.getDecorativeObject(), null);
}
private void onTileObject(Tile tile, TileObject oldObject, TileObject newObject)
{
obstacles.remove(oldObject);
if (newObject == null)
{
return;
}
if (Obstacles.COURSE_OBSTACLE_IDS.contains(newObject.getId()) ||
Obstacles.SHORTCUT_OBSTACLE_IDS.contains(newObject.getId()) ||
(Obstacles.TRAP_OBSTACLE_IDS.contains(newObject.getId())
&& Obstacles.TRAP_OBSTACLE_REGIONS.contains(newObject.getWorldLocation().getRegionID())))
{
obstacles.put(newObject, tile);
}
}
}
|
package com.quickblox.sample.chat.ui.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.view.ActionMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBGroupChat;
import com.quickblox.chat.QBGroupChatManager;
import com.quickblox.chat.QBPrivateChat;
import com.quickblox.chat.QBPrivateChatManager;
import com.quickblox.chat.listeners.QBGroupChatManagerListener;
import com.quickblox.chat.listeners.QBPrivateChatManagerListener;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.sample.chat.R;
import com.quickblox.sample.chat.ui.adapter.DialogsAdapter;
import com.quickblox.sample.chat.utils.Consts;
import com.quickblox.sample.chat.utils.SharedPreferencesUtil;
import com.quickblox.sample.chat.utils.chat.ChatHelper;
import com.quickblox.sample.core.gcm.GooglePlayServicesHelper;
import com.quickblox.sample.core.utils.constant.GcmConsts;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DialogsActivity extends BaseActivity {
private static final String TAG = DialogsActivity.class.getSimpleName();
private static final int REQUEST_SELECT_PEOPLE = 174;
private ListView dialogsListView;
private LinearLayout emptyHintLayout;
private ProgressBar progressBar;
private FloatingActionButton fab;
private ActionMode currentActionMode;
private BroadcastReceiver pushBroadcastReceiver;
private GooglePlayServicesHelper googlePlayServicesHelper;
private DialogsAdapter dialogsAdapter;
public static void start(Context context) {
Intent intent = new Intent(context, DialogsActivity.class);
context.startActivity(intent);
}
private QBPrivateChatManagerListener privateChatManagerListener;
private QBGroupChatManagerListener groupChatManagerListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialogs);
googlePlayServicesHelper = new GooglePlayServicesHelper();
if (googlePlayServicesHelper.checkPlayServicesAvailable(this)) {
googlePlayServicesHelper.registerForGcm(Consts.GCM_SENDER_ID);
}
pushBroadcastReceiver = new PushBroadcastReceiver();
privateChatManagerListener = new QBPrivateChatManagerListener() {
@Override
public void chatCreated(QBPrivateChat qbPrivateChat, boolean createdLocally) {
loadDialogsFromQbInUiThread(true);
}
};
groupChatManagerListener = new QBGroupChatManagerListener() {
@Override
public void chatCreated(QBGroupChat qbGroupChat) {
loadDialogsFromQbInUiThread(true);
}
};
initUi();
}
@Override
protected void onResume() {
super.onResume();
googlePlayServicesHelper.checkPlayServicesAvailable(this);
LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver,
new IntentFilter(GcmConsts.ACTION_NEW_GCM_EVENT));
if (isAppSessionActive) {
registerQbChatListeners();
loadDialogsFromQb(true);
}
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(pushBroadcastReceiver);
if (isAppSessionActive) {
unregisterQbChatListeners();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_dialogs, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dialogs_action_logout:
ChatHelper.getInstance().logout();
if (googlePlayServicesHelper.checkPlayServicesAvailable()) {
googlePlayServicesHelper.unregisterFromGcm(Consts.GCM_SENDER_ID);
}
SharedPreferencesUtil.removeQbUser();
LoginActivity.start(this);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onSessionCreated(boolean success) {
if (success) {
QBUser currentUser = ChatHelper.getCurrentUser();
if (currentUser != null) {
actionBar.setTitle(getString(R.string.dialogs_logged_in_as, currentUser.getFullName()));
}
registerQbChatListeners();
loadDialogsFromQb();
}
}
@SuppressWarnings("unchecked")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PEOPLE) {
ArrayList<QBUser> selectedUsers = (ArrayList<QBUser>) data
.getSerializableExtra(SelectUsersActivity.EXTRA_QB_USERS);
createDialog(selectedUsers);
}
}
}
@Override
protected View getSnackbarAnchorView() {
return findViewById(R.id.layout_root);
}
@Override
public ActionMode startSupportActionMode(ActionMode.Callback callback) {
currentActionMode = super.startSupportActionMode(callback);
return currentActionMode;
}
public void onStartNewChatClick(View view) {
SelectUsersActivity.startForResult(this, REQUEST_SELECT_PEOPLE);
}
private void initUi() {
emptyHintLayout = _findViewById(R.id.layout_chat_empty);
dialogsListView = _findViewById(R.id.list_dialogs_chats);
progressBar = _findViewById(R.id.progress_dialogs);
fab = _findViewById(R.id.fab_dialogs_new_chat);
TextView listHeader = (TextView) LayoutInflater.from(this)
.inflate(R.layout.include_list_hint_header, dialogsListView, false);
listHeader.setText(R.string.dialogs_list_hint);
dialogsListView.addHeaderView(listHeader, null, false);
dialogsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBDialog selectedDialog = (QBDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
ChatActivity.start(DialogsActivity.this, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
dialogsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
QBDialog selectedDialog = (QBDialog) parent.getItemAtPosition(position);
startSupportActionMode(new DeleteActionModeCallback());
dialogsAdapter.selectItem(selectedDialog);
return true;
}
});
}
private void registerQbChatListeners() {
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBGroupChatManager groupChatManager = QBChatService.getInstance().getGroupChatManager();
if (privateChatManager != null) {
privateChatManager.addPrivateChatManagerListener(privateChatManagerListener);
}
if (groupChatManager != null) {
groupChatManager.addGroupChatManagerListener(groupChatManagerListener);
}
}
private void unregisterQbChatListeners() {
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBGroupChatManager groupChatManager = QBChatService.getInstance().getGroupChatManager();
if (privateChatManager != null) {
privateChatManager.removePrivateChatManagerListener(privateChatManagerListener);
}
if (groupChatManager != null) {
groupChatManager.removeGroupChatManagerListener(groupChatManagerListener);
}
}
private void createDialog(final ArrayList<QBUser> selectedUsers) {
ChatHelper.getInstance().createDialogWithSelectedUsers(selectedUsers,
new QBEntityCallback<QBDialog>() {
@Override
public void onSuccess(QBDialog dialog, Bundle args) {
ChatActivity.start(DialogsActivity.this, dialog);
loadDialogsFromQb();
}
@Override
public void onError(QBResponseException e) {
showErrorSnackbar(R.string.dialogs_creation_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
createDialog(selectedUsers);
}
});
}
}
);
}
private void loadDialogsFromQb() {
loadDialogsFromQb(false);
}
private void loadDialogsFromQbInUiThread(final boolean silentUpdate) {
runOnUiThread(new Runnable() {
@Override
public void run() {
loadDialogsFromQb(silentUpdate);
}
});
}
private void loadDialogsFromQb(final boolean silentUpdate) {
if (!silentUpdate) {
progressBar.setVisibility(View.VISIBLE);
}
ChatHelper.getInstance().getDialogs(new QBEntityCallback<ArrayList<QBDialog>>() {
@Override
public void onSuccess(ArrayList<QBDialog> dialogs, Bundle bundle) {
progressBar.setVisibility(View.GONE);
fillListView(dialogs);
}
@Override
public void onError(QBResponseException e) {
progressBar.setVisibility(View.GONE);
if (!silentUpdate) {
showErrorSnackbar(R.string.dialogs_get_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
loadDialogsFromQb();
}
});
}
}
});
}
private void fillListView(List<QBDialog> dialogs) {
dialogsAdapter = new DialogsAdapter(this, dialogs);
dialogsListView.setEmptyView(emptyHintLayout);
dialogsListView.setAdapter(dialogsAdapter);
}
private class DeleteActionModeCallback implements ActionMode.Callback {
public DeleteActionModeCallback() {
fab.hide();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.action_mode_dialogs, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dialogs_action_delete:
deleteSelectedDialogs();
if (currentActionMode != null) {
currentActionMode.finish();
}
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
currentActionMode = null;
dialogsAdapter.clearSelection();
fab.show();
}
private void deleteSelectedDialogs() {
Collection<QBDialog> selectedDialogs = dialogsAdapter.getSelectedItems();
ChatHelper.getInstance().deleteDialogs(selectedDialogs, new QBEntityCallback<Void>() {
@Override
public void onSuccess(Void aVoid, Bundle bundle) {
loadDialogsFromQb();
}
@Override
public void onError(QBResponseException e) {
showErrorSnackbar(R.string.dialogs_deletion_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteSelectedDialogs();
}
});
}
});
}
}
private class PushBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra(GcmConsts.EXTRA_GCM_MESSAGE);
Log.i(TAG, "Received broadcast " + intent.getAction() + " with data: " + message);
loadDialogsFromQb(true);
}
}
}
|
package bt.net;
import bt.event.EventSource;
import bt.metainfo.TorrentId;
import bt.module.PeerConnectionSelector;
import bt.protocol.Message;
import bt.runtime.Config;
import bt.service.IRuntimeLifecycleBinder;
import bt.torrent.TorrentDescriptor;
import bt.torrent.TorrentRegistry;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Default single-threaded message dispatcher implementation.
*
*<p><b>Note that this class implements a service.
* Hence, is not a part of the public API and is a subject to change.</b></p>
*/
public class MessageDispatcher implements IMessageDispatcher {
private static final Logger LOGGER = LoggerFactory.getLogger(MessageDispatcher.class);
private final Map<Peer, Collection<Consumer<Message>>> consumers;
private final Map<Peer, Collection<Supplier<Message>>> suppliers;
private TorrentRegistry torrentRegistry;
@Inject
public MessageDispatcher(IRuntimeLifecycleBinder lifecycleBinder,
IPeerConnectionPool pool,
TorrentRegistry torrentRegistry,
EventSource eventSource,
@PeerConnectionSelector SharedSelector selector,
Config config) {
this.consumers = new ConcurrentHashMap<>();
this.suppliers = new ConcurrentHashMap<>();
this.torrentRegistry = torrentRegistry;
Queue<PeerMessage> messages = new LinkedBlockingQueue<>(); // shared message queue
initializeMessageLoop(lifecycleBinder, pool, messages, config);
initializeMessageReceiver(eventSource, pool, selector, torrentRegistry, lifecycleBinder, messages);
}
private void initializeMessageLoop(IRuntimeLifecycleBinder lifecycleBinder,
IPeerConnectionPool pool,
Queue<PeerMessage> messages,
Config config) {
ExecutorService executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "bt.net.message-dispatcher"));
LoopControl loopControl = new LoopControl(config.getMaxMessageProcessingInterval().toMillis());
MessageDispatchingLoop loop = new MessageDispatchingLoop(pool, loopControl, messages::poll);
lifecycleBinder.onStartup("Initialize message dispatcher", () -> executor.execute(loop));
lifecycleBinder.onShutdown("Shutdown message dispatcher", () -> {
try {
loop.shutdown();
} finally {
executor.shutdownNow();
}
});
}
private void initializeMessageReceiver(EventSource eventSource,
IPeerConnectionPool pool,
SharedSelector selector,
TorrentRegistry torrentRegistry,
IRuntimeLifecycleBinder lifecycleBinder,
Queue<PeerMessage> messages) {
ExecutorService executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "bt.net.message-receiver"));
BiConsumer<Peer, Message> messageSink = (peer, message) ->
messages.add(new PeerMessage(Objects.requireNonNull(peer), Objects.requireNonNull(message)));
MessageReceivingLoop loop = new MessageReceivingLoop(eventSource, pool, selector, messageSink, torrentRegistry);
lifecycleBinder.onStartup("Initialize message receiver", () -> executor.execute(loop));
lifecycleBinder.onShutdown("Shutdown message receiver", () -> {
try {
loop.shutdown();
} finally {
executor.shutdownNow();
}
});
}
private class PeerMessage {
private final Peer peer;
private final Message message;
public PeerMessage(Peer peer, Message message) {
this.peer = peer;
this.message = message;
}
public Peer getPeer() {
return peer;
}
public Message getMessage() {
return message;
}
}
private class MessageReceivingLoop implements Runnable {
private static final int NO_OPS = 0;
private final EventSource eventSource;
private final IPeerConnectionPool pool;
private final SharedSelector selector;
private final BiConsumer<Peer, Message> messageSink;
private final TorrentRegistry torrentRegistry;
private volatile boolean shutdown;
MessageReceivingLoop(EventSource eventSource,
IPeerConnectionPool pool,
SharedSelector selector,
BiConsumer<Peer, Message> messageSink,
TorrentRegistry torrentRegistry) {
this.eventSource = eventSource;
this.pool = pool;
this.selector = selector;
this.messageSink = messageSink;
this.torrentRegistry = torrentRegistry;
}
private synchronized void onPeerConnected(Peer peer) {
PeerConnection connection = pool.getConnection(peer);
if (connection != null) {
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Registering new connection for peer: {}", peer);
}
registerConnection(connection);
} catch (Exception e) {
LOGGER.error("Failed to register new connection for peer: " + peer, e);
}
}
}
private void registerConnection(PeerConnection connection) {
if (connection instanceof SocketPeerConnection) {
SocketChannel channel = ((SocketPeerConnection)connection).getChannel();
// use atomic wakeup-and-register to prevent blocking of registration,
// if selection is resumed before call to register is performed
// (there is a race between the message receiving loop and current thread)
// TODO: move this to the main loop instead?
int interestOps = getInterestOps(connection.getTorrentId());
selector.wakeupAndRegister(channel, interestOps, connection);
}
}
private int getInterestOps(TorrentId torrentId) {
Optional<TorrentDescriptor> descriptor = torrentRegistry.getDescriptor(torrentId);
boolean active = descriptor.isPresent() && descriptor.get().isActive();
return active ? SelectionKey.OP_READ : NO_OPS;
}
private synchronized void onTorrentStarted(TorrentId torrentId) {
pool.visitConnections(torrentId, connection -> {
Peer peer = connection.getRemotePeer();
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Activating connection for peer: {}", peer);
}
updateInterestOps(connection, SelectionKey.OP_READ);
} catch (Exception e) {
LOGGER.error("Failed to activate connection for peer: " + peer, e);
}
});
}
private synchronized void onTorrentStopped(TorrentId torrentId) {
pool.visitConnections(torrentId, connection -> {
Peer peer = connection.getRemotePeer();
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("De-activating connection for peer: {}", peer);
}
updateInterestOps(connection, NO_OPS);
} catch (Exception e) {
LOGGER.error("Failed to de-activate connection for peer: " + peer, e);
}
});
}
private void updateInterestOps(PeerConnection connection, int interestOps) {
if (connection instanceof SocketPeerConnection) {
SocketChannel channel = ((SocketPeerConnection)connection).getChannel();
selector.keyFor(channel).ifPresent(key -> {
// synchronizing on the selection key,
// as we will be using it in a separate, message receiving thread
synchronized (key) {
key.interestOps(interestOps);
}
});
}
}
@Override
public void run() {
eventSource.onPeerConnected(e -> onPeerConnected(e.getPeer()));
eventSource.onTorrentStarted(e -> onTorrentStarted(e.getTorrentId()));
eventSource.onTorrentStopped(e -> onTorrentStopped(e.getTorrentId()));
while (!shutdown) {
if (!selector.isOpen()) {
LOGGER.info("Selector is closed, stopping...");
break;
}
try {
// wakeup periodically to check if there are unprocessed keys left
long t1 = System.nanoTime();
long timeToBlockMillis = 1000;
while (selector.select(timeToBlockMillis) == 0) {
Thread.yield();
long t2 = System.nanoTime();
// check that the selection timeout period is expired, before dealing with unprocessed keys;
// it could be a call to wake up, that made the select() return,
// and we don't want to perform extra work on each spin iteration
if ((t2 - t1 >= timeToBlockMillis * 1000) && !selector.selectedKeys().isEmpty()) {
// try to deal with unprocessed keys, left from the previous iteration
break;
}
}
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
try {
// do not remove the key if it hasn't been processed,
// we'll try again in the next loop iteration
if (processKey(selectedKeys.next())) {
selectedKeys.remove();
}
} catch (ClosedSelectorException e) {
// selector has been closed, there's no point to continue processing
throw e;
} catch (Exception e) {
LOGGER.error("Failed to process key", e);
selectedKeys.remove();
}
}
} catch (ClosedSelectorException e) {
LOGGER.info("Selector has been closed, will stop receiving messages...");
return;
} catch (IOException e) {
throw new RuntimeException("Unexpected I/O exception when selecting peer connections", e);
}
}
}
/**
* @return true, if the key has been processed and can be removed
*/
private boolean processKey(final SelectionKey key) {
PeerConnection connection;
Peer peer;
// synchronizing on the selection key,
// as we will be updating it in a separate, event-listening thread
synchronized (key) {
Object obj = key.attachment();
if (obj == null || !(obj instanceof PeerConnection)) {
LOGGER.warn("Unexpected attachment in selection key: {}. Skipping..", obj);
return false;
}
connection = (PeerConnection) obj;
peer = connection.getRemotePeer();
if (!key.isValid() || !key.isReadable()) {
LOGGER.warn("Selected connection for peer {}, but the key is cancelled or read op is not indicated. Skipping..", peer);
return false;
}
}
if (connection.isClosed()) {
LOGGER.warn("Selected connection for peer {}, but the connection has already been closed. Skipping..", peer);
throw new RuntimeException("Connection closed");
}
TorrentId torrentId = connection.getTorrentId();
if (torrentId == null) {
LOGGER.warn("Selected connection for peer {}, but the connection does not indicate a torrent ID. Skipping..", peer);
return false;
} else if (!isSupportedAndActive(torrentId)) {
LOGGER.warn("Selected connection for peer {}, but the torrent ID is unknown or inactive: {}. Skipping..", peer, torrentId);
return false;
}
while (true) {
Message message = null;
boolean error = false;
try {
message = connection.readMessageNow();
} catch (EOFException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Received EOF from peer: {}. Disconnecting...", peer);
}
error = true;
} catch (IOException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("I/O error when reading message from peer: {}. Reason: {} ({})",
peer, e.getClass().getName(), e.getMessage());
}
error = true;
} catch (Exception e) {
LOGGER.error("Unexpected error when reading message from peer: " + peer, e);
error = true;
}
if (error) {
connection.closeQuietly();
key.cancel();
break;
} else if (message == null) {
break;
} else {
messageSink.accept(peer, message);
}
}
return true;
}
public void shutdown() {
shutdown = true;
}
}
private class MessageDispatchingLoop implements Runnable {
private final IPeerConnectionPool pool;
private final LoopControl loopControl;
private final Supplier<PeerMessage> messageSource;
private volatile boolean shutdown;
MessageDispatchingLoop(IPeerConnectionPool pool, LoopControl loopControl, Supplier<PeerMessage> messageSource) {
this.pool = pool;
this.loopControl = loopControl;
this.messageSource = messageSource;
}
@Override
public void run() {
while (!shutdown) {
// TODO: restrict max amount of incoming messages per iteration
PeerMessage envelope;
while ((envelope = messageSource.get()) != null) {
loopControl.incrementProcessed();
Peer peer = envelope.getPeer();
Message message = envelope.getMessage();
Collection<Consumer<Message>> peerConsumers = consumers.get(peer);
if (peerConsumers != null && peerConsumers.size() > 0) {
for (Consumer<Message> consumer : peerConsumers) {
try {
consumer.accept(message);
} catch (Exception e) {
LOGGER.error("Unexpected exception when processing message " + message + " for peer " + peer, e);
}
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Discarding message {} for peer {}, because no consumers were registered", message, peer);
}
}
}
if (!suppliers.isEmpty()) {
for (Map.Entry<Peer, Collection<Supplier<Message>>> entry : suppliers.entrySet()) {
Peer peer = entry.getKey();
Collection<Supplier<Message>> suppliers = entry.getValue();
PeerConnection connection = pool.getConnection(peer);
if (connection != null && !connection.isClosed()) {
if (isSupportedAndActive(connection.getTorrentId())) {
for (Supplier<Message> messageSupplier : suppliers) {
Message message = null;
try {
message = messageSupplier.get();
} catch (Exception e) {
LOGGER.warn("Error in message supplier", e);
}
if (message != null) {
loopControl.incrementProcessed();
try {
connection.postMessage(message);
} catch (Exception e) {
LOGGER.error("Error when writing message", e);
}
}
}
}
}
}
}
loopControl.iterationFinished();
}
}
public void shutdown() {
shutdown = true;
}
}
/**
* Controls the amount of time to sleep after each iteration of the main message processing loop.
* It implements an adaptive strategy and increases the amount of time for the dispatcher to sleep
* after each iteration during which no messages were either received or sent.
* This strategy greatly reduces CPU load when there is little network activity.
*/
private static class LoopControl {
private ReentrantLock lock;
private Condition timer;
private long maxTimeToSleep;
private int messagesProcessed;
private long timeToSleep;
LoopControl(long maxTimeToSleep) {
this.maxTimeToSleep = maxTimeToSleep;
lock = new ReentrantLock();
timer = lock.newCondition();
}
void incrementProcessed() {
messagesProcessed++;
timeToSleep = 1;
}
void iterationFinished() {
if (messagesProcessed == 0) {
lock.lock();
try {
timer.await(timeToSleep, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignore
} finally {
lock.unlock();
}
timeToSleep = Math.min(timeToSleep << 1, maxTimeToSleep);
}
messagesProcessed = 0;
}
}
private boolean isSupportedAndActive(TorrentId torrentId) {
Optional<TorrentDescriptor> descriptor = torrentRegistry.getDescriptor(torrentId);
// it's OK if descriptor is not present -- torrent might be being fetched at the time
return torrentRegistry.getTorrentIds().contains(torrentId)
&& (!descriptor.isPresent() || descriptor.get().isActive());
}
@Override
public synchronized void addMessageConsumer(Peer sender, Consumer<Message> messageConsumer) {
Collection<Consumer<Message>> peerConsumers = consumers.get(sender);
if (peerConsumers == null) {
peerConsumers = ConcurrentHashMap.newKeySet();
consumers.put(sender, peerConsumers);
}
peerConsumers.add(messageConsumer);
}
@Override
public synchronized void addMessageSupplier(Peer recipient, Supplier<Message> messageSupplier) {
Collection<Supplier<Message>> peerSuppliers = suppliers.get(recipient);
if (peerSuppliers == null) {
peerSuppliers = ConcurrentHashMap.newKeySet();
suppliers.put(recipient, peerSuppliers);
}
peerSuppliers.add(messageSupplier);
}
}
|
package org.myLazyClock.travelApi;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
public class TravelTanStrategy implements TravelStrategy {
public static final int ID = 2;
@Override
public Integer getId() {
return ID;
}
@Override
public String getName() {
return "traveling with tan";
}
@Override
public TravelDuration getDuration(String from, String to, Date dateArrival, Map<String, String> param) {
long travelTime=0;
String idFrom=this.setFromId(from);
String idTo=this.setToId(to);
String urlItineraire="https:
urlItineraire=urlItineraire+"depart="+ URLEncoder.encode(idFrom)+"&arrive="+URLEncoder.encode(idTo)+""+"&type=1&accessible=0&temps="+dateArrival+"&retour=0";
urlItineraire=urlItineraire.replace("+","%20");
URL url = null;
HttpURLConnection request = null;
JsonObject root=null;
try {
url = new URL(urlItineraire);
request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
root = jp.parse(new InputStreamReader((InputStream) request.getContent()))
.getAsJsonArray()
.get(0)
.getAsJsonObject();
String strTime= root.get("duree").getAsString();
if(strTime.contains("mn")){
strTime=strTime.replace(" mn","");
travelTime=(Integer.parseInt(strTime)*60);
}else if (strTime.contains(":")){ // au dela d'une heure format hh:mm
String[] TimeParts=strTime.split(":");
travelTime=Long.parseLong(TimeParts[0])*3600+Long.parseLong(TimeParts[1])*60;
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return new TravelDuration(travelTime);
}
private String setFromId(String from) {
from=from.replace("\\s","%20");
String urlAdressFrom="https:
String fromId="";
URL url = null;
HttpURLConnection request = null;
try {
url = new URL(urlAdressFrom);
request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonObject root = jp.parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonArray().get(0).getAsJsonObject();
JsonObject adresseFrom = root.get("lieux").getAsJsonArray().get(0).getAsJsonObject();
fromId+=adresseFrom.get("id").getAsString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fromId;
}
private String setToId(String to){
to=to.replace("\\s","%20");
String urlAdressTo="https:
String toId="";
try {
URL url = new URL(urlAdressTo);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonObject root = jp.parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonArray().get(0).getAsJsonObject();
JsonObject adresseFrom = root.get("lieux").getAsJsonArray().get(0).getAsJsonObject();
toId+=adresseFrom.get("id").getAsString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toId;
}
}
|
package org.zanata.webtrans.client.history;
import org.zanata.webtrans.client.presenter.AppPresenter;
import org.zanata.webtrans.shared.model.DocumentId;
import com.allen_sauer.gwt.log.client.Log;
/**
* Encapsulates a string token of key-value pairs for GWT history operations.
*
* @author David Mason, damason@redhat.com
*
*/
public class HistoryToken
{
private static final String DELIMITER_K_V = ":";
private static final String PAIR_SEPARATOR = ";";
public static final String KEY_DOCUMENT = "doc";
public static final String KEY_VIEW = "view";
public static final String VALUE_DOCLIST_VIEW = "list";
public static final String VALUE_EDITOR_VIEW = "doc";
public static final String KEY_DOC_FILTER_TEXT = "filter";
public static final String KEY_DOC_FILTER_OPTION = "filtertype";
public static final String VALUE_DOC_FILTER_EXACT = "exact";
public static final String VALUE_DOC_FILTER_INEXACT = "substr";
private AppPresenter.Display.MainView view = null;
private DocumentId docId = null;
private Boolean docFilterExact = null;
private String docFilterText = null;
/**
* Generate a history token from the given token string
*
* @param token A GWT history token in the form key1:value1,key2:value2,...
*/
public static HistoryToken fromTokenString(String token)
{
HistoryToken historyToken = new HistoryToken();
String[] pair;
try
{
for (String pairString : token.split(PAIR_SEPARATOR))
{
pair = pairString.split(DELIMITER_K_V);
String key = pair[0];
String value = pair[1];
if (key == HistoryToken.KEY_DOCUMENT)
{
try
{
historyToken.setDocumentId(new DocumentId(Long.parseLong(value)));
}
catch (NullPointerException e)
{
historyToken.setDocumentId(null);
}
catch (NumberFormatException e)
{
historyToken.setDocumentId(null);
}
}
else if (key == HistoryToken.KEY_VIEW)
{
if (value.equals(VALUE_EDITOR_VIEW))
{
historyToken.setView(AppPresenter.Display.MainView.Editor);
}
else if (value.equals(VALUE_DOCLIST_VIEW))
{
historyToken.setView(AppPresenter.Display.MainView.Documents);
}
else
{ // invalid view
historyToken.setView(null);
}
}
else if (key == HistoryToken.KEY_DOC_FILTER_OPTION)
{
if (value == VALUE_DOC_FILTER_EXACT)
historyToken.setDocFilterExact(true);
else if (value == VALUE_DOC_FILTER_INEXACT)
historyToken.setDocFilterExact(false);
}
else if (key == HistoryToken.KEY_DOC_FILTER_TEXT)
{
historyToken.setDocFilterText(value);
}
else
Log.info("unrecognised history key: " + key);
}
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException("token must be a list of key-value pairs in the form key1:value1,key2:value2,...", e);
}
return historyToken;
}
public boolean hasDocumentId()
{
return docId != null;
}
public DocumentId getDocumentId()
{
return docId;
}
public void setDocumentId(DocumentId docId)
{
this.docId = docId;
}
public boolean hasView()
{
return view != null;
}
public AppPresenter.Display.MainView getView()
{
return view;
}
public void setView(AppPresenter.Display.MainView view)
{
this.view = view;
}
public boolean hasDocFilterExact()
{
return docFilterExact != null;
}
public Boolean getDocFilterExact()
{
return docFilterExact;
}
public void setDocFilterExact(boolean exactMatch)
{
docFilterExact = exactMatch;
}
public boolean hasDocFilterText()
{
return docFilterText != null;
}
public String getDocFilterText()
{
return docFilterText;
}
public void setDocFilterText(String value)
{
this.docFilterText = value;
}
/**
* @return a token string for use with
* {@link com.google.gwt.user.client.History}
*/
public String toTokenString()
{
// TODO put old setter logic in here
String token = "";
boolean first = true;
if (hasView())
{
if (first)
first = false;
else
token += PAIR_SEPARATOR;
token += KEY_VIEW + DELIMITER_K_V;
if (view == AppPresenter.Display.MainView.Editor)
{
token += VALUE_EDITOR_VIEW;
}
else if (view == AppPresenter.Display.MainView.Documents)
{
token += VALUE_DOCLIST_VIEW;
}
}
if (hasDocumentId())
{
if (first)
first = false;
else
token += PAIR_SEPARATOR;
token += KEY_DOCUMENT + DELIMITER_K_V + docId.toString();
}
if (hasDocFilterExact())
{
if (first)
first = false;
else
token += PAIR_SEPARATOR;
token += KEY_DOC_FILTER_OPTION + DELIMITER_K_V;
token += docFilterExact ? VALUE_DOC_FILTER_EXACT : VALUE_DOC_FILTER_INEXACT;
}
if (hasDocFilterText())
{
if (first)
first = false;
else
token += PAIR_SEPARATOR;
token += KEY_DOC_FILTER_TEXT + DELIMITER_K_V + docFilterText;
}
return token;
}
}
|
package org.osgi.framework;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
/**
* Version identifier for bundles and packages.
*
* <p>
* Version identifiers have four components.
* <ol>
* <li>Major version. A non-negative integer.</li>
* <li>Minor version. A non-negative integer.</li>
* <li>Micro version. A non-negative integer.</li>
* <li>Qualifier. A text string. See <code>Version(String)</code> for the
* format of the qualifier string.</li>
* </ol>
*
* <p>
* <code>Version</code> instances are immutable.
*
* @version $Revision$
* @since 1.3
*/
public class Version implements Comparable {
private final int major;
private final int minor;
private final int micro;
private final String qualifier;
private static final String SEPARATOR = "."; //$NON-NLS-1$
/**
* The empty version "0.0.0". Equivalent to calling
* <code>new Version(0,0,0)</code>.
*/
public static final Version emptyVersion = new Version(0, 0, 0);
public Version(int major, int minor, int micro) {
this(major, minor, micro, null);
}
public Version(int major, int minor, int micro, String qualifier) {
if (qualifier == null) {
qualifier = ""; //$NON-NLS-1$
}
this.major = major;
this.minor = minor;
this.micro = micro;
this.qualifier = qualifier;
validate();
}
public Version(String version) {
int major = 0;
int minor = 0;
int micro = 0;
String qualifier = ""; //$NON-NLS-1$
try {
StringTokenizer st = new StringTokenizer(version, SEPARATOR, true);
major = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) {
st.nextToken(); // consume delimiter
minor = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) {
st.nextToken(); // consume delimiter
micro = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) {
st.nextToken(); // consume delimiter
qualifier = st.nextToken();
if (st.hasMoreTokens()) {
throw new IllegalArgumentException("invalid format"); //$NON-NLS-1$
}
}
}
}
}
catch (NoSuchElementException e) {
throw new IllegalArgumentException("invalid format"); //$NON-NLS-1$
}
this.major = major;
this.minor = minor;
this.micro = micro;
this.qualifier = qualifier;
validate();
}
private void validate() {
if (major < 0) {
throw new IllegalArgumentException("negative major"); //$NON-NLS-1$
}
if (minor < 0) {
throw new IllegalArgumentException("negative minor"); //$NON-NLS-1$
}
if (micro < 0) {
throw new IllegalArgumentException("negative micro"); //$NON-NLS-1$
}
int length = qualifier.length();
for (int i = 0; i < length; i++) {
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".indexOf(qualifier.charAt(i)) == -1) { //$NON-NLS-1$
throw new IllegalArgumentException("invalid qualifier"); //$NON-NLS-1$
}
}
}
public static Version parseVersion(String version) {
if (version == null) {
return emptyVersion;
}
version = version.trim();
if (version.length() == 0) {
return emptyVersion;
}
return new Version(version);
}
/**
* Returns the major component of this version identifier.
*
* @return The major component.
*/
public int getMajor() {
return major;
}
/**
* Returns the minor component of this version identifier.
*
* @return The minor component.
*/
public int getMinor() {
return minor;
}
/**
* Returns the micro component of this version identifier.
*
* @return The micro component.
*/
public int getMicro() {
return micro;
}
/**
* Returns the qualifier component of this version identifier.
*
* @return The qualifier component.
*/
public String getQualifier() {
return qualifier;
}
/**
* Returns the string representation of this version identifier.
*
* <p>
* The format of the version string will be <code>major.minor.micro</code>
* if qualifier is the empty string or
* <code>major.minor.micro.qualifier</code> otherwise.
*
* @return The string representation of this version identifier.
*/
public String toString() {
String base = major + SEPARATOR + minor + SEPARATOR + micro;
if (qualifier.length() == 0) { //$NON-NLS-1$
return base;
}
else {
return base + SEPARATOR + qualifier;
}
}
/**
* Returns a hash code value for the object.
*
* @return An integer which is a hash code value for this object.
*/
public int hashCode() {
return (major << 24) + (minor << 16) + (micro << 8)
+ qualifier.hashCode();
}
/**
* Compares this <code>Version</code> object to another object.
*
* <p>
* A version is considered to be <b>equal to </b> another version if the
* major, minor and micro components are equal and the qualifier component
* is equal (using <code>String.equals</code>).
*
* @param object The <code>Version</code> object to be compared.
* @return <code>true</code> if <code>object</code> is a
* <code>Version</code> and is equal to this object;
* <code>false</code> otherwise.
*/
public boolean equals(Object object) {
if (object == this) { // quicktest
return true;
}
if (!(object instanceof Version)) {
return false;
}
Version other = (Version) object;
return (major == other.major) && (minor == other.minor)
&& (micro == other.micro) && qualifier.equals(other.qualifier);
}
/**
* Compares this <code>Version</code> object to another object.
*
* <p>
* A version is considered to be <b>less than </b> another version if its
* major component is less than the other version's major component, or the
* major components are equal and its minor component is less than the other
* version's minor component, or the major and minor components are equal
* and its micro component is less than the other version's micro component,
* or the major, minor and micro components are equal and it's qualifier
* component is less than the other version's qualifier component (using
* <code>String.compareTo</code>).
*
* <p>
* A version is considered to be <b>equal to </b> another version if the
* major, minor and micro components are equal and the qualifier component
* is equal (using <code>String.compareTo</code>).
*
* @param object The <code>Version</code> object to be compared.
* @return A negative integer, zero, or a positive integer if this object is
* less than, equal to, or greater than the specified
* <code>Version</code> object.
* @throws ClassCastException If the specified object is not a
* <code>Version</code>.
*/
public int compareTo(Object object) {
if (object == this) { // quicktest
return 0;
}
Version other = (Version) object;
int result = major - other.major;
if (result != 0) {
return result;
}
result = minor - other.minor;
if (result != 0) {
return result;
}
result = micro - other.micro;
if (result != 0) {
return result;
}
return qualifier.compareTo(other.qualifier);
}
}
|
package io.skysail.server.app.metrics;
import java.util.List;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import io.skysail.api.metrics.MetricsImplementation;
import io.skysail.api.metrics.TimerDataProvider;
import io.skysail.server.app.ApiVersion;
import io.skysail.server.app.ApplicationConfiguration;
import io.skysail.server.app.ApplicationProvider;
import io.skysail.server.app.SkysailApplication;
import io.skysail.server.app.metrics.resources.BookmarkResource;
import io.skysail.server.app.metrics.resources.PutBookmarkResource;
import io.skysail.server.app.metrics.resources.TimersChartResource;
import io.skysail.server.app.metrics.resources.TimersResource;
import io.skysail.server.menus.MenuItemProvider;
import io.skysail.server.restlet.RouteBuilder;
import io.skysail.server.security.config.SecurityConfigBuilder;
@Component(immediate = true)
public class MetricsApplication extends SkysailApplication implements ApplicationProvider, MenuItemProvider {
public static final String LIST_ID = "lid";
public static final String TODO_ID = "id";
public static final String APP_NAME = "MetricsApp";
public MetricsApplication() {
super(APP_NAME, new ApiVersion(1));
setDescription("a skysail application");
}
//@Reference(cardinality = ReferenceCardinality.MANDATORY)
private MetricsImplementation metricsImpl;
@Activate
@Override
public void activate(ApplicationConfiguration appConfig, ComponentContext componentContext)
throws ConfigurationException {
super.activate(appConfig, componentContext);
}
@Override
protected void defineSecurityConfig(SecurityConfigBuilder securityConfigBuilder) {
securityConfigBuilder
.authorizeRequests().startsWithMatcher("").authenticated();
}
@Override
protected void attach() {
super.attach();
router.attach(new RouteBuilder("/Bookmarks/{id}", BookmarkResource.class));
router.attach(new RouteBuilder("/Bookmarks/{id}/", PutBookmarkResource.class));
router.attach(new RouteBuilder("/Timers", TimersResource.class));
router.attach(new RouteBuilder("/Timers/chart", TimersChartResource.class));
router.attach(new RouteBuilder("", TimersResource.class));
}
public List<TimerDataProvider> getTimerMetrics() {
return metricsImpl.getTimers();
}
}
|
package gov.nih.nci.caarray.magetab2;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* A Protocol is a parameterizable description of a method.
*/
public final class Protocol implements Serializable, TermSourceable {
private static final long serialVersionUID = 3130057952908619310L;
private String name;
private OntologyTerm type;
private String description;
private final List<Parameter> parameters = new ArrayList<Parameter>();
private String hardware;
private String software;
private String contact;
private TermSource termSource;
/**
* @return the contact
*/
public String getContact() {
return contact;
}
/**
* @param contact the contact to set
*/
public void setContact(String contact) {
this.contact = contact;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the hardware
*/
public String getHardware() {
return hardware;
}
/**
* @param hardware the hardware to set
*/
public void setHardware(String hardware) {
this.hardware = hardware;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the parameters
*/
public List<Parameter> getParameters() {
return parameters;
}
/**
* @return the software
*/
public String getSoftware() {
return software;
}
/**
* @param software the software to set
*/
public void setSoftware(String software) {
this.software = software;
}
/**
* @return the termSource
*/
public TermSource getTermSource() {
return termSource;
}
/**
* @param termSource the termSource to set
*/
public void setTermSource(TermSource termSource) {
this.termSource = termSource;
}
/**
* @return the type
*/
public OntologyTerm getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(OntologyTerm type) {
this.type = type;
}
}
|
package org.spoofax;
import org.spoofax.interpreter.Context;
import org.spoofax.interpreter.stratego.CallT;
import org.spoofax.interpreter.stratego.Let;
import org.spoofax.interpreter.stratego.Scope;
import org.spoofax.interpreter.stratego.Strategy;
public class DebugUtil {
public static boolean debugging = false;
public static boolean tracing = false;
public static final int INDENT_STEP = 2;
//public static boolean resetSSL = true;
//public static boolean cleanupInShutdown = true;
//public static boolean shareFactory = true;
/**
* Debug utility to trace the result of a completed strategy and the 'current'
* term upon it's completion. </br>
* We do not trace return of {@link org.spoofax.interpreter.stratego.Seq} or {@link org.spoofax.interpreter.stratego.Scope} for clarity.
*/
public static boolean traceReturn(boolean result, Object current, final Strategy strategy) {
if (debugging) {
// Indent just for stragies that use a scope.
boolean doIndent = strategy instanceof CallT || strategy instanceof Let || strategy instanceof Scope;
StringBuilder sb = buildIndent(doIndent ? INDENT_STEP : 0);
if(!result) {
Strategy.debug(sb, "=> failed: ", current, "\n");
} else {
Strategy.debug(sb, "=> succeeded: ", current, "\n");
}
}
return result;
}
public static void debug(Object... strings) {
String toPrint = "";
if (strings.length > 1) {
for (Object s : strings) {
if(s.getClass().isArray()) {
Object ss[] = (Object[])s;
for (Object o : ss) {
toPrint += o;
}
} else {
toPrint += s; //pay the price
}
}
}
else {
toPrint = (strings[0]).toString();
}
if (toPrint.length() < 20000) {
System.out.println(toPrint);
}
}
public static void setDebug(boolean b) {
debugging = b;
}
public static void bump(Context ctxt) {
Context.indentation += INDENT_STEP;
}
public static void unbump(Context ctxt) {
Context.indentation -= INDENT_STEP;
}
private final static char[] indent = new char[2000];
static {
for (int i = 0; i < indent.length; i++) {
indent[i] = ' ';
}
}
public static StringBuilder buildIndent(final int indentation) {
StringBuilder b = new StringBuilder(indentation);
b.append(indent, 0, indentation);
return b;
}
public static boolean isDebugging() {
return debugging;
}
public static void setTracing(boolean enableTracing) {
tracing = enableTracing;
}
}
|
package edu.nettester.task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//import java.lang.Float;
import java.lang.String;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import edu.nettester.db.MeasureContract.MeasureLog;
import edu.nettester.db.MeasureDBHelper;
import edu.nettester.util.CommonMethod;
import edu.nettester.util.Constant;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* One measurement task
*
* @author Daoyuan and Weichao
*/
public class RTTTask extends AsyncTask<String, Integer, String[]> implements Constant {
private Context mContext;
//private AndroidHttpClient httpClient = null;
public RTTTask(Context context) {
mContext = context;
}
@Override
protected String[] doInBackground(String... params) {
//for test only
String target = params[0];
String mserver = servermap.get(target);
String mid = String.valueOf(System.currentTimeMillis());
String mtime = String.valueOf(System.currentTimeMillis()); //TODO should be high-level time
String mnetwork = getNetworkType(mContext);
String mlocation = getLocation(mContext);
String deviceID = getDeviceID(mContext);
//perform ping task
ArrayList<Double> rtt_list = new ArrayList<Double>();
for(int i=0;i<10;i++) {
HTTPPinger pingtask = new HTTPPinger(mserver);
double rtt = pingtask.execute();
rtt_list.add(rtt);
//update progress
}
Collections.sort(rtt_list);
double min_rtt = rtt_list.get(0);
double max_rtt = rtt_list.get(9);
double avg_rtt = getAverage(rtt_list);
double median_rtt = getMedian(rtt_list);
double stdv_rtt = getStdDv(rtt_list);
//perform download throughput test
HTTPDownTP downtask = new HTTPDownTP(mserver);
float downtp = downtask.execute();
//update progress
//perform upload throughput test
HTTPUpTP uptask = new HTTPUpTP(mserver);
float uptp = uptask.execute();
//update progress
if (DEBUG) {
Log.d(TAG, "RTT: "+String.valueOf(median_rtt)+"ms");
Log.d(TAG, "Down TP: "+String.valueOf(downtp)+"kbps");
Log.d(TAG, "Up TP: "+String.valueOf(uptp)+"kbps");
}
return new String[] {mid, deviceID, mnetwork, mlocation, mserver, String.valueOf(avg_rtt),
String.valueOf(median_rtt), String.valueOf(min_rtt), String.valueOf(max_rtt),
String.valueOf(stdv_rtt), String.valueOf(downtp), String.valueOf(uptp), mtime};
}
/**
* handle progress bar
*/
@Override
protected void onProgressUpdate(Integer... progress) {
//TODO
}
/**
* insert into DB
*/
@Override
protected void onPostExecute(String[] result) {
MeasureDBHelper mDbHelper = new MeasureDBHelper(mContext);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String m_uid, m_hash;
if(CommonMethod.M_UID != null) {
m_uid = CommonMethod.M_UID;
m_hash = CommonMethod.M_HASH;
} else {
m_uid = "0";
m_hash = "";
}
// TODO insert some fake data
ContentValues values = new ContentValues();
values.put(MeasureLog.MUID, m_uid);
values.put(MeasureLog.MID, result[0]);
values.put(MeasureLog.M_NET_INFO, result[2]);
values.put(MeasureLog.M_LOC_INFO, result[3]);
values.put(MeasureLog.M_TAR_SERVER, result[4]);
values.put(MeasureLog.AVG_RTT, result[5]);
values.put(MeasureLog.MEDIAN_RTT, result[6]);
values.put(MeasureLog.MIN_RTT, result[7]);
values.put(MeasureLog.MAX_RTT, result[8]);
values.put(MeasureLog.STDV_RTT, result[9]);
values.put(MeasureLog.DOWN_TP, result[10]);
values.put(MeasureLog.UP_TP, result[11]);
values.put(MeasureLog.MTIME, result[12]);
long newRowId;
newRowId = db.insert(
MeasureLog.TABLE_NAME,
null,
values);
if (DEBUG)
Log.d(TAG, "Insert a db row: "+newRowId);
//upload data
if(DEBUG) {
Log.d(TAG, m_uid + ":" + m_hash);
}
List<NameValuePair> DataList = new ArrayList<NameValuePair>();
DataList.add(new BasicNameValuePair(MeasureLog.MUID, m_uid));
DataList.add(new BasicNameValuePair(MeasureLog.MHASH, m_hash));
DataList.add(new BasicNameValuePair(MeasureLog.MID, result[0]));
DataList.add(new BasicNameValuePair(MeasureLog.M_NET_INFO, result[2]));
DataList.add(new BasicNameValuePair(MeasureLog.M_LOC_INFO, result[3]));
DataList.add(new BasicNameValuePair(MeasureLog.M_TAR_SERVER, result[4]));
DataList.add(new BasicNameValuePair(MeasureLog.M_DEVID, result[1]));
DataList.add(new BasicNameValuePair(MeasureLog.AVG_RTT, result[5]));
DataList.add(new BasicNameValuePair(MeasureLog.MEDIAN_RTT, result[6]));
DataList.add(new BasicNameValuePair(MeasureLog.MAX_RTT, result[8]));
DataList.add(new BasicNameValuePair(MeasureLog.MIN_RTT, result[7]));
DataList.add(new BasicNameValuePair(MeasureLog.STDV_RTT, result[9]));
DataList.add(new BasicNameValuePair(MeasureLog.UP_TP, result[11]));
DataList.add(new BasicNameValuePair(MeasureLog.DOWN_TP, result[10]));
//OPHTTPClient mclient = new OPHTTPClient();
//String upload_output = mclient.postPage(CommonMethod.updata_url, DataList);
try {
UploadProc mupload = new UploadProc();
String upload_output = mupload.execute(DataList).get();
if(upload_output.equals("success") || upload_output.equals("exist")) {
//upload database
ContentValues upvalues = new ContentValues();
upvalues.put(MeasureLog.UPFLG, "1");
db.update(MeasureLog.TABLE_NAME, upvalues, MeasureLog._ID+"=?", new String[]{String.valueOf(newRowId)});
}
} catch (Exception e) {
Log.e(CommonMethod.TAG, e.getMessage());
}
}
public double getAverage(ArrayList<Double> inlist){
int num = inlist.size();
int sum = 0;
for(int i=0;i<num;i++){
sum += inlist.get(i);
}
return (double)(sum/num);
}
public double getStdDv(ArrayList<Double> inlist){
int num = inlist.size();
double sum = 0;
double avg_val = getAverage(inlist);
for(int i=0;i<num;i++){
double cur_val = inlist.get(i);
sum += Math.sqrt((cur_val - avg_val) * (cur_val - avg_val));
}
return (double)(sum/(num-1));
}
public double getMedian(ArrayList<Double> inlist) {
int num = inlist.size();
Collections.sort(inlist);
int rindex = 0;
double outval;
int a=num%2;
if (a==0) {
rindex = num/2;
outval = (inlist.get(rindex) + inlist.get(rindex+1))/2;
} else {
rindex = (num+1)/2;
outval = inlist.get(rindex);
}
return outval;
}
private String getNetworkType(Context mContext){
ConnectivityManager connManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connManager.getActiveNetworkInfo();
String networkType = "";
if(networkinfo != null) {
networkType = networkinfo.getTypeName();
}
if (DEBUG)
Log.d(TAG, "Network type:" + networkType);
return networkType;
}
private String getLocation(Context mContext) {
String outloc = "";
LocationManager lm = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setCostAllowed(false);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String providerName = lm.getBestProvider(criteria, true);
if (providerName != null) {
Location location = lm.getLastKnownLocation(providerName);
Log.i(TAG, "
double latitude = location.getLatitude();
double longitude = location.getLongitude();
outloc = String.valueOf(longitude) + "," + String.valueOf(latitude);
} else {
outloc = "Unknow place";
}
if (DEBUG)
Log.d(TAG, "Location:" + outloc);
return outloc;
}
private String getDeviceID(Context mContext) {
String deviceID = "NA";
TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = telephonyManager.getDeviceId(); // This ID is permanent to a physical phone.
// "generic" means the emulator.
if (deviceId == null || Build.DEVICE.equals("generic")) {
// This ID changes on OS reinstall/factory reset.
deviceId = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID);
}
if (DEBUG)
Log.d(TAG, "Device ID:" + deviceID);
return deviceID;
}
private class UploadProc extends AsyncTask<List<NameValuePair>, Void, String> {
@Override
protected String doInBackground(List<NameValuePair>...params) {
String output = "";
OPHTTPClient mclient = new OPHTTPClient();
output = mclient.postPage(CommonMethod.updata_url, params[0]);
if (CommonMethod.DEBUG)
Log.d(CommonMethod.TAG, output);
mclient.destroy();
return output;
}
@Override
protected void onPostExecute(String result) {
}
}
}
|
package com.srch2.android.http.service;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Represents an index in the SRCH2 search server. For every index to be searched on, users of the
* SRCH2 Android SDK should implement a separate subclass instance of this class.
* <br><br>
* For each implementation of this class, <b>it is necessary</b> to override:
* <br>
* {@link #getIndexName()}
* <br>
* {@link #getSchema()}
* <br><br>
* This class contains methods for performing CRUD actions on the index such as insertion and
* searching; in addition, specific <code>Indexable</code> instances can be obtained from the
* <code>SRCH2Engine</code> static method <code>getIndex(String indexName)</code> (where <code>
* indexName</code> matches the return value of <code>getIndexName())</code> to access these
* same methods.
*/
public abstract class Indexable {
IndexInternal indexInternal;
/**
* The default value for the numbers of search results to return per search request.
* <br><br>
* Has the <b>constant</b> value of <code>10</code>.
*/
public static final int DEFAULT_NUMBER_OF_SEARCH_RESULTS_TO_RETURN_AKA_TOPK = 10;
/**
* The default value for the fuzziness similarity threshold. Approximately one character
* per every three characters will be allowed to act as a wildcard during a search.
* <br><br>
* Has the <b>constant</b> value of <code>0.65</code>.
*/
public static final float DEFAULT_FUZZINESS_SIMILARITY_THRESHOLD = 0.65f;
/**
* Implementing this method sets the name of the index this <code>Indexable</code> represents.
* @return the name of the index this <code>Indexable</code> represents
*/
abstract public String getIndexName();
/**
* Implementing this method sets the schema of the index this <code>Indexable</code> represents. The schema
* defines the data fields of the index, much like the table structure of an SQLite database table. See
* {@link com.srch2.android.http.service.Schema} for more information.
* @return the schema to define the index structure this <code>Indexable</code> represents
*/
abstract public Schema getSchema();
public int getTopK() {
return DEFAULT_NUMBER_OF_SEARCH_RESULTS_TO_RETURN_AKA_TOPK;
}
public float getFuzzinessSimilarityThreshold() { return DEFAULT_FUZZINESS_SIMILARITY_THRESHOLD; }
/**
* Inserts the specified <code>JSONObject record</code> into the index that this
* <code>Indexable</code> represents. This <code>JSONObject</code> should be properly
* formed and its keys should only consist of the fields as defined in the index's
* schema; the values of these keys should match the type defined in the index's
* schema as well.
* <br><br>
* After the SRCH2 search server completes the insertion task, the callback method of the
* {@link com.srch2.android.http.service.StateResponseListener#onInsertRequestComplete(String, InsertResponse)}
* will be triggered containing the status of the
* completed insertion task.
* @param record the <code>JSONObject</code> representing the record to insert
*/
public final void insert(JSONObject record) {
if (indexInternal != null) {
indexInternal.insert(record);
}
}
/**
* Inserts the set of records represented as <code>JSONObject</code>s contained in the
* specified <code>JSONArray records</code>. Each <code>JSONObject</code> should be properly
* formed and its keys should only consist of the fields as defined in the index's
* schema; the values of these keys should match the type defined in the index's
* schema as well. The <code>JSONArray records</code> should also be properly formed
* and contain only the set of <code>JSONObect</code>s that represent the records to be
* inserted.
* <br><br>
* After the SRCH2 search server completes the insertion task, the callback method of the
* {@link com.srch2.android.http.service.StateResponseListener#onInsertRequestComplete(String, InsertResponse)}
* will be triggered containing the status of the
* completed insertion task.
* @param records the <code>JSONArray</code> containing the set of <code>JSONObject</code>s
* representing the records to insert
*/
public final void insert(JSONArray records) {
if (indexInternal != null) {
indexInternal.insert(records);
}
}
/**
* Updates the specified <code>JSONObject record</code> into the index that this
* <code>Indexable</code> represents. This <code>JSONObject</code> should be properly
* formed and its keys should only consist of the fields as defined in the index's
* schema; the values of these keys should match the type defined in the index's
* schema as well. If the primary key supplied in the <code>record</code> does not
* match the primary key of any existing record, the <code>record</code> will be
* inserted.
* <br><br>
* After the SRCH2 search server completes the update task, the callback method of the
* {@link com.srch2.android.http.service.StateResponseListener#onUpdateRequestComplete(String, UpdateResponse)}
* will be triggered containing the status of the
* completed update task.
* @param record the <code>JSONObject</code> representing the record to upsert
*/
public final void update(JSONObject record) {
if (indexInternal != null) {
indexInternal.update(record);
}
}
/**
* Updates the set of records represented as <code>JSONObject</code>s contained in the
* specified <code>JSONArray records</code>. Each <code>JSONObject</code> should be properly
* formed and its keys should only consist of the fields as defined in the index's
* schema; the values of these keys should match the type defined in the index's
* schema as well. The <code>JSONArray records</code> should also be properly formed
* and contain only the set of <code>JSONObect</code>s that represent the records to be
* updates. If the primary key of any of the supplied records in the <code>JSONArray</code>
* does not match the primary key of any existing record, that record will be
* inserted.
* <br><br>
* After the SRCH2 search server completes the update task, the callback method of the
* {@link com.srch2.android.http.service.StateResponseListener#onUpdateRequestComplete(String, UpdateResponse)}
* will be triggered containing the status of the
* completed update task.
* @param records the <code>JSONArray</code> containing the set of <code>JSONObject</code>s
* representing the records to upsert
*/
public final void update(JSONArray records) {
if (indexInternal != null) {
indexInternal.update(records);
}
}
/**
* Deletes from the index this record with a primary
* key matching the value of the <code>primaryKeyOfRecordToDelete</code>. If no record with
* a matching primary key is found, the index will remain as it is.
* <br><br>
* After the SRCH2 search server completes the deletion task, the callback method of the
* {@link com.srch2.android.http.service.StateResponseListener#onDeleteRequestComplete(String, DeleteResponse)}
* will be triggered containing the status of the
* completed deletion task.
* @param primaryKeyOfRecordToDelete the primary key of the record to delete
*/
public final void delete(String primaryKeyOfRecordToDelete) {
if (indexInternal != null) {
indexInternal.delete(primaryKeyOfRecordToDelete);
}
}
/**
* Performs an information task on the index that this <code>Indexable</code> represents. This
* method may be used to inspect the state of the index such as the number of records in the index
* by calling {@link InfoResponse#getNumberOfDocumentsInTheIndex()}
* <br><br>
* When the SRCH2 search server completes the information task, the
* method {@link com.srch2.android.http.service.StateResponseListener#onInfoRequestComplete(String, InfoResponse)}
* will be triggered. The <code>InfoResponse response</code> will contain information about the
* index such as the number of records it contains or the time stamp of the last time the index
* was updated to reflect any pending changes.
*/
public final void info() {
if (indexInternal != null) {
indexInternal.info();
}
}
/**
* Does a basic search on the index that this <code>Indexable</code> represents. A basic
* search means that all distinct keywords (delimited by white space) of the
* <code>searchInput</code> are treated as fuzzy, and the last keyword will
* be treated as fuzzy and prefix.
* <br><br>
* For more configurable searches, use the
* {@link com.srch2.android.http.service.Query} class in conjunction with the {@link #advancedSearch(Query)}
* method.
* <br><br>
* When the SRCH2 server is finished performing the search task, the method
* {@link com.srch2.android.http.service.SearchResultsListener#onNewSearchResults(int, String, java.util.HashMap)}
* will be triggered. The
* <code>HashMap</code> argument will contain the search results in the form of <code>
* JSONObject</code>s as they were originally inserted (and updated).
* <br><br>
* This method will throw an exception is the value of <code>searchInput</code> is null
* or has a length less than one.
* @param searchInput the textual input to search on
*/
public final void search(String searchInput) {
if (indexInternal != null) {
indexInternal.search(searchInput);
}
}
/**
* Does an advanced search by forming search request input as a {@link com.srch2.android.http.service.Query}. This enables
* searches to use all the advanced features of the SRCH2 search engine, such as per term
* fuzziness similarity thresholds, limiting the range of results to a refining field, and
* much more. See the {@link com.srch2.android.http.service.Query} for more details.
* <br><br>
* When the SRCH2 server is finished performing the search task, the method
* {@link com.srch2.android.http.service.SearchResultsListener#onNewSearchResults(int, String, java.util.HashMap)}
* will be triggered. The argument
* <code>HashMap</code> will contain the search results in the form of <code>
* JSONObject</code>s as they were originally inserted (and updated).
* <br><br>
* This method will throw an exception if the value of <code>query</code> is null.
* @param query the formation of the query to do the advanced search
*/
public final void advancedSearch(Query query) {
if (indexInternal != null) {
indexInternal.advancedSearch(query);
}
}
public final void getRecordbyID(String primaryKeyOfRecordToRetrieve) {
if (indexInternal != null) {
indexInternal.getRecordbyID(primaryKeyOfRecordToRetrieve);
}
}
}
|
package stsc.algorithms.indices.adi.stock;
import java.util.Optional;
import stsc.common.BadSignalException;
import stsc.common.Day;
import stsc.common.algorithms.BadAlgorithmException;
import stsc.common.algorithms.StockAlgorithm;
import stsc.common.algorithms.StockAlgorithmInit;
import stsc.common.signals.SignalsSerie;
import stsc.common.signals.SerieSignal;
import stsc.common.stocks.Prices;
import stsc.signals.DoubleSignal;
import stsc.signals.series.LimitSignalsSerie;
public final class AdiClv extends StockAlgorithm {
public AdiClv(StockAlgorithmInit init) throws BadAlgorithmException {
super(init);
}
@Override
public Optional<SignalsSerie<SerieSignal>> registerSignalsClass(StockAlgorithmInit initialize) throws BadAlgorithmException {
final int size = initialize.getSettings().getIntegerSetting("size", 2);
return Optional.of(new LimitSignalsSerie<>(DoubleSignal.class, size));
}
@Override
public void process(Day day) throws BadSignalException {
final Prices p = day.getPrices();
final double denominator = p.getHigh() - p.getLow();
if (Double.compare(denominator, 0.0) == 0) {
addSignal(day.getDate(), new DoubleSignal(0.0));
} else {
final double clv = ((p.getClose() - p.getLow() - (p.getHigh() - p.getClose()))) / (denominator);
addSignal(day.getDate(), new DoubleSignal(clv));
}
}
}
|
package pal;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main
{
private static HashMap<Integer, SoftReference<Node>> cache = new HashMap<Integer, SoftReference<Node>>();
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static ByteArrayOutputStream out = new ByteArrayOutputStream();
private static ArrayList<Integer> sort = new ArrayList<Integer>();
private static byte[] newline = System.getProperty("line.separator").getBytes();
private static Node root = null;
private static int name = 0;
public static void main(String ... args)
{
try
{
read_data ();
check_cyclic_dependedcy___dead_code___non_declaration ();
flush_data ();
}
catch(FatalError e){ System.out.println("ERROR"); }
}
static void check_cyclic_dependedcy___dead_code___non_declaration() throws FatalError
{ check_node(root); }
static void check_node(Node node) throws FatalError //non-recursive approach is slower
{
node . visited = true;
if( (!node.isDeclared && node.isDependency) || node.state==Node.GRAY ) throw new FatalError();
node.state = Node.GRAY;
for(Node n : node.link)
{
if(n.state==Node.BLACK) continue;
check_node(n);
}
node.state=Node.BLACK;
}
public static void read_data()
{
try
{
Node n = null;
Node m = null;
String line = "";
outer:while(true)
{
line = in.readLine();
if(line.getBytes()[0] == 9)
{ node(name).lines.add(line.getBytes()); }
else
{
StringTokenizer st = new StringTokenizer(line," ");
if(!st.hasMoreTokens()) continue outer;
String token = st.nextToken();
name = hash(token.substring(0, token.length()-1));
n = node(name);
n.isDeclared = true;
if(root==null) root = n;
while (st.hasMoreTokens())
{
m = node(hash(st.nextToken()));
m.isDependency = true;
n.addEdge(m);
}
n.lines . add(line.getBytes());
sort . add(name);
st = null;
}
}
}
catch(Exception e) { /*ignore*/ }
try { in.close(); }
catch (IOException e) { /*ignore*/ }
finally { in = null; }
}
static void flush_data() throws FatalError
{
try
{
Node n = null;
for(int index : sort)
{
n = node(index);
if(n.visited) for( byte[] line : n.lines )
{
out . write(line);
out . write(newline);
}
else for( byte[] line : n.lines )
{
out . write(0x23);
out . write(line);
out . write(newline);
}
release(index);
}
System.gc();
System.out.print(out);
}
catch(IOException e){ /*ignore*/ }
}
static void release(int key)
{
cache.remove(key).get().destroy();
}
static int hash(String text)
{
int hash = 0;
for( int i=0 ; i < text.length() ; hash = (hash << 5) - hash + text.charAt(i++) );
return hash;
}
// nested helpers
static class FatalError extends RuntimeException
{ private static final long serialVersionUID = 3638938829930139263L; }
static class Node
{
public static int WHITE = 0x01;
public static int GRAY = 0x02;
public static int BLACK = 0x03;
int state = WHITE;
boolean visited = false;
boolean marked = false;
boolean isDependency = false;
boolean isDeclared = false;
ArrayList<Node> link = new ArrayList<Node>();
ArrayList<byte[]> lines = new ArrayList<byte[]>();
int index = 0;
int id = 0;
public Node(int id)
{ this.id = id; }
public void addEdge(Node b)
{ link.add(b); }
public int hashCode()
{ return this.id; }
public boolean equals(Object another)
{
Node n = (Node) another;
return (n.id)==this.id;
}
public void destroy()
{
this.lines . clear();
this.link . clear();
this.lines = null;
this.link = null;
try { super.finalize(); }
catch (Throwable e) { /*ignore*/ }
}
}
public static Node node(int key)
{
Node node = null;
SoftReference<Node> ref = cache . get(key);
if(ref != null) node = ref . get();
if(node == null) cache . put( key, new SoftReference<Node>(node = new Node(key)) );
return node;
}
}
|
package com.exedio.copernica;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import com.exedio.cope.EnumValue;
import com.exedio.cope.Feature;
import com.exedio.cope.Item;
import com.exedio.cope.ObjectAttribute;
import com.exedio.cope.Type;
import com.exedio.cope.UniqueConstraint;
import com.exedio.cope.util.ServletUtil;
public abstract class TransientCopernicaProvider implements CopernicaProvider
{
public void initialize(final ServletConfig config)
{
ServletUtil.initialize(getModel(), config);
}
// Transient Languages
private HashMap transientLanguages = null;
protected final void setTransientLanguages(final TransientLanguage[] languages)
{
final HashMap result = new HashMap(languages.length);
for(int i = 0; i<languages.length; i++)
result.put(languages[i].getCopernicaID(), languages[i]);
transientLanguages = result;
}
public Collection getDisplayLanguages()
{
return
transientLanguages == null
? Collections.EMPTY_LIST
: transientLanguages.values();
}
public CopernicaLanguage findLanguageByID(final String copernicaID)
{
return
transientLanguages == null
? null
: (TransientLanguage)transientLanguages.get(copernicaID);
}
// Transient Users
private HashMap transientUsers = null;
protected final void setTransientUsers(final TransientUser[] users)
{
final HashMap result = new HashMap(users.length);
for(int i = 0; i<users.length; i++)
result.put(users[i].id, users[i]);
transientUsers = result;
}
public CopernicaUser findUserByID(String copernicaID)
{
return
transientUsers == null
? null
: (TransientUser)transientUsers.get(copernicaID);
}
public Collection getRootCategories()
{
return Collections.EMPTY_LIST;
}
// Transient Sections
private HashMap transientMainAttributes = null;
private HashMap transientSections = null;
protected final void setSections(final Type type, final Collection mainAttributes, final Collection sections)
{
if(transientMainAttributes==null)
{
transientMainAttributes = new HashMap();
transientSections = new HashMap();
}
transientMainAttributes.put(type, mainAttributes);
transientSections.put(type, sections);
}
public Collection getMainAttributes(final Type type)
{
return transientMainAttributes==null ? null : (Collection)transientMainAttributes.get(type);
}
public Collection getSections(final Type type)
{
return transientSections==null ? null : (Collection)transientSections.get(type);
}
public static final String breakupName(final String name)
{
final StringBuffer result = new StringBuffer(name.length());
boolean wordStart = true;
for(int i=0; i<name.length(); i++)
{
final char c = name.charAt(i);
if(Character.isUpperCase(c))
{
if(!wordStart)
result.append(' ');
wordStart = true;
}
else
wordStart = false;
if(i==0)
result.append(Character.toUpperCase(c));
else
result.append(c);
}
return result.toString();
}
public String getDisplayNameNull(CopernicaLanguage displayLanguage)
{
return
displayLanguage instanceof TransientLanguage
? ((TransientLanguage)displayLanguage).nullName
: "-";
}
public String getDisplayNameOn(CopernicaLanguage displayLanguage)
{
return
displayLanguage instanceof TransientLanguage
? ((TransientLanguage)displayLanguage).onName
: "X";
}
public String getDisplayNameOff(CopernicaLanguage displayLanguage)
{
return
displayLanguage instanceof TransientLanguage
? ((TransientLanguage)displayLanguage).offName
: "/";
}
public String getDisplayName(final CopernicaLanguage displayLanguage, final Type type)
{
final String className = type.getJavaClass().getName();
final int pos = className.lastIndexOf('.');
return breakupName(className.substring(pos+1));
}
public String getDisplayName(final CopernicaLanguage displayLanguage, final Feature feature)
{
String name = feature.getName();
return breakupName(name);
}
public String getDisplayName(final RequestCache cache, final CopernicaLanguage displayLanguage, final Item item)
{
final Type type = item.getCopeType();
final List uniqueConstraints = type.getUniqueConstraints();
if(uniqueConstraints.isEmpty())
return item.toString();
else
{
final StringBuffer result = new StringBuffer();
final UniqueConstraint uniqueConstraint = (UniqueConstraint)uniqueConstraints.iterator().next();
boolean first = true;
for(Iterator i = uniqueConstraint.getUniqueAttributes().iterator(); i.hasNext(); )
{
if(first)
first = false;
else
result.append(" - ");
final ObjectAttribute attribute = (ObjectAttribute)i.next();
final Object value = item.get(attribute);
final String valueString;
if(value == null)
valueString = "NULL";
else if(value instanceof Item)
valueString = cache.getDisplayName(displayLanguage, (Item)value);
else
valueString = value.toString();
result.append(valueString);
}
return result.toString();
}
}
protected final void putDisplayName(final TransientLanguage transientLanguage, final EnumValue value, final String name)
{
transientLanguage.enumerationValueNames.put(value, name);
}
public String getDisplayName(final CopernicaLanguage displayLanguage, final EnumValue value)
{
if(displayLanguage instanceof TransientLanguage)
{
final TransientLanguage transientLanguage = (TransientLanguage)displayLanguage;
final String name = (String)transientLanguage.enumerationValueNames.get(value);
if(name!=null)
return name;
}
return value.getCode();
}
public String getIconURL(final Type type)
{
return null;
}
public CopernicaCategory findCategoryByID(final String copernicaID)
{
return null;
}
public CopernicaSection findSectionByID(final String copernicaID)
{
return null;
}
public void handleException(
final PrintStream out, final CopernicaServlet servlet,
final HttpServletRequest request, final Exception e)
throws IOException
{
final boolean onPage = "jo-man".equals(request.getParameter("display_error"));
Copernica_Jspm.writeException(out, servlet, e, onPage);
}
public int getLimitCountCeiling(final Type type)
{
return 500;
}
}
|
package gov.nara.nwts.ftapp.filetest;
import gov.nara.nwts.ftapp.FTDriver;
import gov.nara.nwts.ftapp.filetest.DefaultFileTest;
import gov.nara.nwts.ftapp.filter.DefaultFileTestFilter;
import gov.nara.nwts.ftapp.ftprop.FTPropString;
import gov.nara.nwts.ftapp.stats.Stats;
import gov.nara.nwts.ftapp.stats.StatsGenerator;
import gov.nara.nwts.ftapp.stats.StatsItem;
import gov.nara.nwts.ftapp.stats.StatsItemConfig;
import gov.nara.nwts.ftapp.stats.StatsItemEnum;
import java.io.File;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Extract all metadata fields from a TIF or JPG using categorized tag defintions.
* @author TBrady
*
*/
class DigitalDerivatives extends DefaultFileTest {
public static enum FOUND {
NOT_FOUND,
FOUND,
FOUND_DUP
;
}
public static enum STAT {
INCOMPLETE,
COMPLETE,
EXTRA
}
private static enum DerivStatsItems implements StatsItemEnum {
Basename(StatsItem.makeStringStatsItem("Basename", 200)),
Stat(StatsItem.makeEnumStatsItem(STAT.class,"Status")),
Count(StatsItem.makeIntStatsItem("Count")),
CountExtra(StatsItem.makeIntStatsItem("Count Extra")),
Extras(StatsItem.makeStringStatsItem("Extra Items")),
;
StatsItem si;
DerivStatsItems(StatsItem si) {this.si=si;}
public StatsItem si() {return si;}
}
public static enum Generator implements StatsGenerator {
INSTANCE;
class DerivStats extends Stats {
public DerivStats(String key) {
super(details, key);
}
}
public DerivStats create(String key) {return new DerivStats(key);}
}
public static StatsItemConfig details = StatsItemConfig.create(DerivStatsItems.class);
long counter = 1000000;
public static final String REGX_MATCH = "regex-match";
public static final String REGX_REPLACE = "regex-replace";
public static final String EXT_REQ = "file-extensions-req";
public static final String EXT_OPT = "file-extensions-opt";
public static final String DEF_MATCH = "^(.*)\\.[^\\.]+$";
public static final String DEF_REPLACE = "$1";
public DigitalDerivatives(FTDriver dt) {
super(dt);
ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), REGX_MATCH, REGX_MATCH,
"Regex pattern to compute basename", DEF_MATCH));
ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), REGX_REPLACE, REGX_REPLACE,
"Regex replacement for basename", DEF_REPLACE));
ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), EXT_REQ, EXT_REQ,
"Required file extensions to report (lower-case, comma separated list)", "tif,jpg,xml"));
ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), EXT_OPT, EXT_OPT,
"Optional file extensions to report (lower-case, comma separated list)", ""));
extensions = new Vector<String>();
extensionsReq = new Vector<String>();
}
public String toString() {
return "Digital Derivatives";
}
String match;
Pattern pMatch;
String replace;
Vector<String>extensions;
Vector<String>extensionsReq;
public void init() {
match = getProperty(REGX_MATCH, DEF_MATCH).toString();
try {
pMatch = Pattern.compile(match);
} catch (Exception e) {
}
replace = getProperty(REGX_REPLACE, DEF_REPLACE).toString();
details = StatsItemConfig.create(DerivStatsItems.class);
extensions.clear();
extensionsReq.clear();
String ext = getProperty(EXT_REQ, "").toString();
for(String s:ext.split(",")) {
if (s.isEmpty()) continue;
s = s.trim().toLowerCase();
extensions.add(s);
extensionsReq.add(s);
details.addStatsItem(s, StatsItem.makeEnumStatsItem(FOUND.class, s+"*"));
}
ext = getProperty(EXT_OPT, "").toString();
for(String s:ext.split(",")) {
if (s.isEmpty()) continue;
s = s.trim().toLowerCase();
extensions.add(s);
details.addStatsItem(s, StatsItem.makeEnumStatsItem(FOUND.class, s));
}
}
public String getExt(String test) {
test = test.toLowerCase();
for(String ext: extensions) {
if (test.endsWith(ext)) return ext;
}
return null;
}
//public boolean isTestable(File f) {
// return getExt(f.getName()) != null;
public String getKey(File f) {
String s = f.getName().toLowerCase();
if (pMatch == null) return s;
Matcher m = pMatch.matcher(s);
if (m.matches()) {
s = m.replaceFirst(replace);
}
return s;
}
public String getShortName(){return "Deriv";}
public Object fileTest(File f) {
Stats s = getStats(f);
String suff = f.getName().toLowerCase().substring(s.key.length());
s.sumVal(DerivStatsItems.Count, 1);
String ext = getExt(f.getName().toLowerCase());
if (ext == null) {
s.sumVal(DerivStatsItems.CountExtra, 1);
s.appendVal(DerivStatsItems.Extras, suff+" ");
} else {
StatsItem si = details.getByKey(ext);
if (si == null) return null;
FOUND found = (FOUND) s.getKeyVal(si, FOUND.NOT_FOUND);
if (found == FOUND.NOT_FOUND) {
found = FOUND.FOUND;
} else if (found == FOUND.FOUND) {
found = FOUND.FOUND_DUP;
}
s.setKeyVal(si, found);
}
return s.key;
}
@Override public void refineResults() {
for(Stats curr: dt.types.values()) {
curr.setVal(DerivStatsItems.Stat, STAT.COMPLETE);
for(String s: extensionsReq) {
StatsItem si = details.getByKey(s);
if (si == null) continue;
FOUND found = (FOUND)curr.getKeyVal(si, FOUND.NOT_FOUND);
if (found == FOUND.NOT_FOUND) {
curr.setVal(DerivStatsItems.Stat, STAT.INCOMPLETE);
}
}
if (curr.getVal(DerivStatsItems.Stat) == STAT.INCOMPLETE) continue;
if (curr.getIntVal(DerivStatsItems.CountExtra) > 0) {
curr.setVal(DerivStatsItems.Stat, STAT.EXTRA);
continue;
}
for(String s: extensions) {
StatsItem si = details.getByKey(s);
if (si == null) continue;
FOUND found = (FOUND)curr.getKeyVal(si, FOUND.NOT_FOUND);
if (found == FOUND.FOUND_DUP) {
curr.setVal(DerivStatsItems.Stat, STAT.EXTRA);
}
}
}
}
public Stats createStats(String key){
return Generator.INSTANCE.create(key);
}
public StatsItemConfig getStatsDetails() {
return details;
}
public void initFilters() {
filters.add(new DefaultFileTestFilter());
}
public String getDescription() {
return "";
}
}
|
package io.bisq.core.payment.payload;
import io.bisq.common.locale.Res;
import io.bisq.common.proto.persistable.PersistablePayload;
import io.bisq.core.app.BisqEnvironment;
import io.bisq.generated.protobuffer.PB;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.bitcoinj.core.Coin;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@EqualsAndHashCode(exclude = {"maxTradePeriod", "maxTradeLimit"})
@ToString
@Slf4j
public final class PaymentMethod implements PersistablePayload, Comparable {
// Static
// time in blocks (average 10 min for one block confirmation
private static final long DAY = TimeUnit.HOURS.toMillis(24);
public static final String OK_PAY_ID = "OK_PAY";
public static final String UPHOLD_ID = "UPHOLD";
public static final String CASH_APP_ID = "CASH_APP";
public static final String MONEY_BEAM_ID = "MONEY_BEAM";
public static final String VENMO_ID = "VENMO";
public static final String POPMONEY_ID = "POPMONEY";
public static final String REVOLUT_ID = "REVOLUT";
public static final String PERFECT_MONEY_ID = "PERFECT_MONEY";
public static final String SEPA_ID = "SEPA";
public static final String SEPA_INSTANT_ID = "SEPA_INSTANT";
public static final String FASTER_PAYMENTS_ID = "FASTER_PAYMENTS";
public static final String NATIONAL_BANK_ID = "NATIONAL_BANK";
public static final String SAME_BANK_ID = "SAME_BANK";
public static final String SPECIFIC_BANKS_ID = "SPECIFIC_BANKS";
public static final String SWISH_ID = "SWISH";
public static final String ALI_PAY_ID = "ALI_PAY";
public static final String CLEAR_X_CHANGE_ID = "CLEAR_X_CHANGE";
public static final String CHASE_QUICK_PAY_ID = "CHASE_QUICK_PAY";
public static final String INTERAC_E_TRANSFER_ID = "INTERAC_E_TRANSFER";
public static final String US_POSTAL_MONEY_ORDER_ID = "US_POSTAL_MONEY_ORDER";
public static final String CASH_DEPOSIT_ID = "CASH_DEPOSIT";
public static final String WESTERN_UNION_ID = "WESTERN_UNION";
public static final String BLOCK_CHAINS_ID = "BLOCK_CHAINS";
public static PaymentMethod OK_PAY;
public static PaymentMethod UPHOLD;
public static PaymentMethod CASH_APP;
public static PaymentMethod MONEY_BEAM;
public static PaymentMethod VENMO;
public static PaymentMethod POPMONEY;
public static PaymentMethod REVOLUT;
public static PaymentMethod PERFECT_MONEY;
public static PaymentMethod SEPA;
public static PaymentMethod SEPA_INSTANT;
public static PaymentMethod FASTER_PAYMENTS;
public static PaymentMethod NATIONAL_BANK;
public static PaymentMethod SAME_BANK;
public static PaymentMethod SPECIFIC_BANKS;
public static PaymentMethod SWISH;
public static PaymentMethod ALI_PAY;
public static PaymentMethod CLEAR_X_CHANGE;
public static PaymentMethod CHASE_QUICK_PAY;
public static PaymentMethod INTERAC_E_TRANSFER;
public static PaymentMethod US_POSTAL_MONEY_ORDER;
public static PaymentMethod CASH_DEPOSIT;
public static PaymentMethod WESTERN_UNION;
public static PaymentMethod BLOCK_CHAINS;
private static List<PaymentMethod> ALL_VALUES;
public static void onAllServicesInitialized() {
getAllValues();
}
// Instance fields
@Getter
private final String id;
@Getter
private final long maxTradePeriod;
private final long maxTradeLimit;
// Constructor
/**
* @param id against charge back risk. If Bank do the charge back quickly the Arbitrator and the seller can push another
* double spend tx to invalidate the time locked payout tx. For the moment we set all to 0 but will have it in
* place when needed.
* @param maxTradePeriod The min. period a trader need to wait until he gets displayed the contact form for opening a dispute.
* @param maxTradeLimit The max. allowed trade amount in Bitcoin for that payment method (depending on charge back risk)
*/
public PaymentMethod(String id, long maxTradePeriod, @NotNull Coin maxTradeLimit) {
this.id = id;
this.maxTradePeriod = maxTradePeriod;
this.maxTradeLimit = maxTradeLimit.value;
}
public static List<PaymentMethod> getAllValues() {
if (ALL_VALUES == null) {
Coin maxTradeLimitHighRisk;
Coin maxTradeLimitMidRisk;
Coin maxTradeLimitLowRisk;
Coin maxTradeLimitVeryLowRisk;
switch (BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode()) {
case "BTC":
maxTradeLimitHighRisk = Coin.parseCoin("0.125");
maxTradeLimitMidRisk = Coin.parseCoin("0.25");
maxTradeLimitLowRisk = Coin.parseCoin("0.5");
maxTradeLimitVeryLowRisk = Coin.parseCoin("1");
break;
case "LTC":
maxTradeLimitHighRisk = Coin.parseCoin("12.5");
maxTradeLimitMidRisk = Coin.parseCoin("25");
maxTradeLimitLowRisk = Coin.parseCoin("50");
maxTradeLimitVeryLowRisk = Coin.parseCoin("100");
break;
case "DOGE":
maxTradeLimitHighRisk = Coin.parseCoin("125000");
maxTradeLimitMidRisk = Coin.parseCoin("250000");
maxTradeLimitLowRisk = Coin.parseCoin("500000");
maxTradeLimitVeryLowRisk = Coin.parseCoin("1000000");
break;
case "DASH":
maxTradeLimitHighRisk = Coin.parseCoin("5");
maxTradeLimitMidRisk = Coin.parseCoin("10");
maxTradeLimitLowRisk = Coin.parseCoin("20");
maxTradeLimitVeryLowRisk = Coin.parseCoin("40");
break;
default:
log.error("Unsupported BaseCurrency. " + BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode());
throw new RuntimeException("Unsupported BaseCurrency. " + BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode());
}
ALL_VALUES = new ArrayList<>(Arrays.asList(
// EUR
SEPA = new PaymentMethod(SEPA_ID, 6 * DAY, maxTradeLimitMidRisk),
SEPA_INSTANT = new PaymentMethod(SEPA_INSTANT_ID, DAY, maxTradeLimitMidRisk),
MONEY_BEAM = new PaymentMethod(MONEY_BEAM_ID, DAY, maxTradeLimitHighRisk),
FASTER_PAYMENTS = new PaymentMethod(FASTER_PAYMENTS_ID, DAY, maxTradeLimitMidRisk),
// Sweden
SWISH = new PaymentMethod(SWISH_ID, DAY, maxTradeLimitLowRisk),
CLEAR_X_CHANGE = new PaymentMethod(CLEAR_X_CHANGE_ID, 4 * DAY, maxTradeLimitMidRisk),
CASH_APP = new PaymentMethod(CASH_APP_ID, DAY, maxTradeLimitHighRisk),
VENMO = new PaymentMethod(VENMO_ID, DAY, maxTradeLimitHighRisk),
POPMONEY = new PaymentMethod(POPMONEY_ID, DAY, maxTradeLimitHighRisk),
CHASE_QUICK_PAY = new PaymentMethod(CHASE_QUICK_PAY_ID, DAY, maxTradeLimitMidRisk),
US_POSTAL_MONEY_ORDER = new PaymentMethod(US_POSTAL_MONEY_ORDER_ID, 8 * DAY, maxTradeLimitMidRisk),
// Canada
INTERAC_E_TRANSFER = new PaymentMethod(INTERAC_E_TRANSFER_ID, DAY, maxTradeLimitMidRisk),
// Global
CASH_DEPOSIT = new PaymentMethod(CASH_DEPOSIT_ID, 4 * DAY, maxTradeLimitMidRisk),
WESTERN_UNION = new PaymentMethod(WESTERN_UNION_ID, 4 * DAY, maxTradeLimitMidRisk),
NATIONAL_BANK = new PaymentMethod(NATIONAL_BANK_ID, 4 * DAY, maxTradeLimitMidRisk),
SAME_BANK = new PaymentMethod(SAME_BANK_ID, 2 * DAY, maxTradeLimitMidRisk),
SPECIFIC_BANKS = new PaymentMethod(SPECIFIC_BANKS_ID, 4 * DAY, maxTradeLimitMidRisk),
// Trans national
OK_PAY = new PaymentMethod(OK_PAY_ID, DAY, maxTradeLimitVeryLowRisk),
UPHOLD = new PaymentMethod(UPHOLD_ID, DAY, maxTradeLimitHighRisk),
REVOLUT = new PaymentMethod(REVOLUT_ID, DAY, maxTradeLimitHighRisk),
PERFECT_MONEY = new PaymentMethod(PERFECT_MONEY_ID, DAY, maxTradeLimitLowRisk),
// China
ALI_PAY = new PaymentMethod(ALI_PAY_ID, DAY, maxTradeLimitLowRisk),
// Altcoins
BLOCK_CHAINS = new PaymentMethod(BLOCK_CHAINS_ID, DAY, maxTradeLimitVeryLowRisk)
));
}
ALL_VALUES.sort((o1, o2) -> {
String id1 = o1.getId();
if (id1.equals(CLEAR_X_CHANGE_ID))
id1 = "ZELLE";
String id2 = o2.getId();
if (id2.equals(CLEAR_X_CHANGE_ID))
id2 = "ZELLE";
return id1.compareTo(id2);
});
return ALL_VALUES;
}
// PROTO BUFFER
@Override
public PB.PaymentMethod toProtoMessage() {
return PB.PaymentMethod.newBuilder()
.setId(id)
.setMaxTradePeriod(maxTradePeriod)
.setMaxTradeLimit(maxTradeLimit)
.build();
}
public static PaymentMethod fromProto(PB.PaymentMethod proto) {
return new PaymentMethod(proto.getId(),
proto.getMaxTradePeriod(),
Coin.valueOf(proto.getMaxTradeLimit()));
}
// API
// Used for dummy entries in payment methods list (SHOW_ALL)
public PaymentMethod(String id) {
this(id, 0, Coin.ZERO);
}
public static PaymentMethod getPaymentMethodById(String id) {
Optional<PaymentMethod> paymentMethodOptional = getAllValues().stream().filter(e -> e.getId().equals(id)).findFirst();
return paymentMethodOptional.orElseGet(() -> new PaymentMethod(Res.get("shared.na")));
}
// Hack for SF as the smallest unit is 1 SF ;-( and price is about 3 BTC!
public Coin getMaxTradeLimitAsCoin(String currencyCode) {
if (currencyCode.equals("SF") || currencyCode.equals("BSQ"))
return Coin.parseCoin("4");
else
return Coin.valueOf(maxTradeLimit);
}
@Override
public int compareTo(@NotNull Object other) {
if (id != null)
return this.id.compareTo(((PaymentMethod) other).id);
else
return 0;
}
}
|
package org.jeo.geojson.simple.encoder;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayDeque;
import org.jeo.geojson.simple.JSONValue;
public class JSONEncoder {
/**
* output
*/
final Writer out;
/**
* object stack
*/
final ArrayDeque<Thing> stack = new ArrayDeque<Thing>();
String indent;
String space;
String newline;
/**
* Creates a new encoder.
*
* @param out Writer to output to.
*/
public JSONEncoder(Writer out) {
this(out, 0);
}
/**
* Creates a new encoder with formatting.
*
* @param out Writer to output to.
* @param indentSize The number of spaces to use when indenting.
*/
public JSONEncoder(Writer out, int indentSize) {
this.out = out;
indent = spaces(indentSize);
space = indentSize > 0 ? " " : "";
newline = indentSize > 0 ? "\n" : "";
}
/**
* The underlying writer.
*/
public Writer getWriter() {
return out;
}
/*
* Helper to generate an indentation chunk.
*/
static String spaces(int indentSize) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indentSize; i++) {
sb.append(" ");
}
return sb.toString();
}
/**
* Starts a new JSON object.
*
* @return This encoder.
*/
public JSONEncoder object() throws IOException {
Thing t = peek();
if (t != null) {
if (t instanceof Arr) {
Arr a = (Arr) t;
if (a.size > 0) {
out.write(',');
}
}
else {
Obj o = (Obj) t;
if (!o.key) {
throw new IllegalArgumentException("no key for object");
}
}
t.size++;
}
stack.push(new Obj());
out.write('{');
return this;
}
/**
* Starts a new JSON array.
*
* @return This encoder.
*/
public JSONEncoder array() throws IOException {
Thing t = peek();
if (t != null) {
if (t instanceof Arr) {
Arr a = (Arr) t;
if (a.size > 0) {
out.write(',');
}
}
else if (t instanceof Obj) {
Obj o = (Obj) t;
if (!o.key) {
throw new IllegalStateException("no key");
}
}
t.size++;
}
stack.push(new Arr());
out.write('[');
return this;
}
/**
* Starts an object property.
*
* @param key The key/name of the property.
*
* @return This encoder.
*/
public JSONEncoder key(String key) throws IOException {
Thing t = peek();
if (!(t instanceof Obj)) {
throw new IllegalStateException("no object");
}
Obj o = (Obj) t;
if (o.key) {
throw new IllegalStateException("value required");
}
o.key = true;
if (o.size > 0) {
out.write(',');
}
newline();
out.write("\"");
out.write(JSONValue.escape(key));
out.write("\":");
out.write(space);
return this;
}
/**
* Specifies a numeric value for an object property.
* <p>
* You must call the {@link #key(String)} method before calling this method.
* </p>
* @param value The value.
* @return This encoder.
*/
public JSONEncoder value(Number value) throws IOException {
if (value != null) {
// check for double nan/infinte
if (value instanceof Double || value instanceof Float) {
Double val = value.doubleValue();
if (val.isInfinite() || val.isNaN()) {
value = null;
}
}
}
return doValue(value != null ? value.toString() : null);
}
/**
* Specifies a numeric value for an object property.
*
* @param value The value.
*
* @return This encoder.
*/
public JSONEncoder value(Object value) throws IOException {
if (value == null) {
return nul();
}
if (value instanceof Number) {
return value((Number)value);
}
else {
return value(value.toString());
}
}
/**
* Specified a null value for an object property.
* @return This encoder.
*/
public JSONEncoder nul() throws IOException {
return value((String)null);
}
/**
* Specifies a string value for an object property.
* <p>
* You must call the {@link #key(String)} method before calling this method.
* </p>
* @return This encoder.
*/
public JSONEncoder value(String value) throws IOException {
return doValue(value != null ? "\""+JSONValue.escape(value)+"\"" : null);
}
/*
* Helper to write out an already encoded value.
*/
JSONEncoder doValue(String encoded) throws IOException {
Thing t = peek();
if (t == null) {
throw new IllegalStateException("no object");
}
if (t instanceof Arr) {
Arr a = (Arr) t;
if (a.size > 0) {
out.write(',');
}
newline();
a.size++;
}
else {
Obj o = (Obj) t;
if (!o.key) {
throw new IllegalStateException("no key");
}
o.key = false;
o.size++;
}
if (encoded == null) {
encoded = "null";
}
out.write(encoded);
return this;
}
/**
* Ends the current JSON object.
*
* @return This encoder.
*/
public JSONEncoder endObject() throws IOException {
Thing t = peek();
if (!(t instanceof Obj)) {
throw new IllegalStateException("no object");
}
Obj o = (Obj) t;
if (o.key) {
throw new IllegalStateException("open key");
}
stack.pop();
if (o.size > 0) {
newline();
}
t = peek();
if (t instanceof Obj) {
o = (Obj) t;
if (!o.key) {
throw new IllegalStateException("no key");
}
o.key = false;
}
out.write('}');
return this;
}
/**
* Ends the current JSON array.
*
* @return This encoder.
*/
public JSONEncoder endArray() throws IOException {
Thing t = peek();
if (!(t instanceof Arr)) {
throw new IllegalStateException("no array");
}
Arr a = (Arr) t;
stack.pop();
if (a.size > 0) {
newline();
}
t = peek();
if (t instanceof Obj) {
Obj o = (Obj) t;
if (!o.key) {
throw new IllegalStateException("no key");
}
o.key = false;
}
out.write("]");
return this;
}
public JSONEncoder flush() throws IOException {
out.flush();
return this;
}
/*
* Moves output to the next line and indents. A no-op if formatting not active.
*/
void newline() throws IOException {
out.write(newline);
if (!"".equals(indent)) {
for (int i = 0; i < stack.size(); i++) {
out.write(indent);
}
}
}
/*
* Does a "safe" peek of the stack, returning null if empty.
*/
Thing peek() {
return stack.isEmpty() ? null : stack.peek();
}
static abstract class Thing {
protected int size = 0;
}
static class Obj extends Thing {
protected boolean key = false;
}
static class Arr extends Thing {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.